@reason-machines/cli-linux-x64 0.2.525 → 0.2.528

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 (109) hide show
  1. package/bin/reason +2 -2
  2. package/bin/vm-hands/api-credentials-5g66v8kk.js +2 -0
  3. package/bin/vm-hands/api-efs3jmyr.js +2 -0
  4. package/bin/vm-hands/connect-cli-zd9z2x4s.js +2 -0
  5. package/bin/vm-hands/credentials-ts56n6gk.js +2 -0
  6. package/bin/vm-hands/{custom-endpoint-device-hzgdnyx2.js → custom-endpoint-device-7tgcmhbz.js} +1 -1
  7. package/bin/vm-hands/desktop-account-jdqya1ff.js +2 -0
  8. package/bin/vm-hands/desktop-wallpaper-fd8f2wb2.jpg +0 -0
  9. package/bin/vm-hands/device-workspace-rxqaw78v.js +2 -0
  10. package/bin/vm-hands/dock-browser-y53t41cx.png +0 -0
  11. package/bin/vm-hands/dock-files-cp52htdw.png +0 -0
  12. package/bin/vm-hands/dock-terminal-1es514yq.png +0 -0
  13. package/bin/vm-hands/hands-worker-source-hkjndq4w.js +2 -0
  14. package/bin/vm-hands/install-receipt-8tpfepde.js +2 -0
  15. package/bin/vm-hands/local-automation-0yeamh23.js +2 -0
  16. package/bin/vm-hands/local-capabilities-xcgvjt4m.js +2 -0
  17. package/bin/vm-hands/local-desktop-users-tjcpyakd.js +2 -0
  18. package/bin/vm-hands/{local-display-mac-4654wqzs.js → local-display-mac-gtp439kc.js} +1 -1
  19. package/bin/vm-hands/local-display-session-2zb2t48b.js +2 -0
  20. package/bin/vm-hands/local-display-video-74qvb6rn.js +2 -0
  21. package/bin/vm-hands/local-managed-process-fk555zb4.js +2 -0
  22. package/bin/vm-hands/local-pty-session-tnz6jwtt.js +2 -0
  23. package/bin/vm-hands/managed-runtime-12kqhvk9.js +2 -0
  24. package/bin/vm-hands/{network-contract-5wc6wbn2.js → network-contract-e98v6mwd.js} +1 -1
  25. package/bin/vm-hands/permissions-jxstmabp.js +2 -0
  26. package/bin/vm-hands/{reason-hands-protocol-zffy7kc8.js → reason-hands-protocol-39wqa1xa.js} +1 -1
  27. package/bin/vm-hands/serve-service-g5fjd1bx.js +2 -0
  28. package/bin/vm-hands/{status-nvm1fe9h.js → status-qwjpxcsp.js} +1 -1
  29. package/bin/vm-hands/version-nj7n5by8.js +2 -0
  30. package/bin/vm-hands/{vm-hands-entry-lite-krnvgf71.js → vm-hands-entry-lite-04x5xjt6.js} +3 -3
  31. package/bin/vm-hands/vm-hands-entry-lite-0ry43hpj.js +4 -0
  32. package/bin/vm-hands/{vm-hands-entry-lite-0tavq3p4.js → vm-hands-entry-lite-13s0mfpr.js} +1 -1
  33. package/bin/vm-hands/{vm-hands-entry-lite-kwmjn9y3.js → vm-hands-entry-lite-2hfrcr50.js} +5 -5
  34. package/bin/vm-hands/{vm-hands-entry-lite-11dq75hb.js → vm-hands-entry-lite-2yx1aaq2.js} +3 -3
  35. package/bin/vm-hands/{vm-hands-entry-lite-mfvtp7py.js → vm-hands-entry-lite-37b5045h.js} +1 -1
  36. package/bin/vm-hands/vm-hands-entry-lite-3gbf905c.js +3 -0
  37. package/bin/vm-hands/{vm-hands-entry-lite-vf02kfyy.js → vm-hands-entry-lite-3x6zetc0.js} +5 -5
  38. package/bin/vm-hands/{vm-hands-entry-lite-t82dzcxb.js → vm-hands-entry-lite-4anjdcth.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-tash5m18.js → vm-hands-entry-lite-4r1yn35v.js} +22 -22
  40. package/bin/vm-hands/vm-hands-entry-lite-5jd2gqs8.js +150 -0
  41. package/bin/vm-hands/{vm-hands-entry-lite-a6w60nv9.js → vm-hands-entry-lite-5tnma5qb.js} +3 -3
  42. package/bin/vm-hands/{vm-hands-entry-lite-0zby1r00.js → vm-hands-entry-lite-610728bf.js} +21 -21
  43. package/bin/vm-hands/{vm-hands-entry-lite-70hq7mrs.js → vm-hands-entry-lite-72nj66ab.js} +2 -2
  44. package/bin/vm-hands/{vm-hands-entry-lite-tns12zqc.js → vm-hands-entry-lite-73f4cgkf.js} +2 -2
  45. package/bin/vm-hands/{vm-hands-entry-lite-nj4kjex8.js → vm-hands-entry-lite-7h86g4gd.js} +30 -30
  46. package/bin/vm-hands/{vm-hands-entry-lite-89ahrw19.js → vm-hands-entry-lite-8nzq0bpa.js} +2 -2
  47. package/bin/vm-hands/{vm-hands-entry-lite-60t7x9vw.js → vm-hands-entry-lite-8v8x8zn2.js} +9 -9
  48. package/bin/vm-hands/{vm-hands-entry-lite-wfc0agnt.js → vm-hands-entry-lite-9azmqs47.js} +3 -3
  49. package/bin/vm-hands/{vm-hands-entry-lite-39qv4sqt.js → vm-hands-entry-lite-a0g6c3wr.js} +2 -2
  50. package/bin/vm-hands/vm-hands-entry-lite-a64cxaqn.js +2 -0
  51. package/bin/vm-hands/{vm-hands-entry-lite-x5048q8d.js → vm-hands-entry-lite-av0j90wn.js} +5 -5
  52. package/bin/vm-hands/{vm-hands-entry-lite-1kt82jes.js → vm-hands-entry-lite-b6gsggvp.js} +2 -2
  53. package/bin/vm-hands/{vm-hands-entry-lite-x1vm200a.js → vm-hands-entry-lite-b7ar9xhg.js} +2 -2
  54. package/bin/vm-hands/{vm-hands-entry-lite-hc11hecd.js → vm-hands-entry-lite-cgddp0y3.js} +4 -4
  55. package/bin/vm-hands/{vm-hands-entry-lite-bvqwsd3b.js → vm-hands-entry-lite-ct4mtq1m.js} +1 -1
  56. package/bin/vm-hands/{vm-hands-entry-lite-h0s6n13f.js → vm-hands-entry-lite-gdggtj2d.js} +1 -1
  57. package/bin/vm-hands/{vm-hands-entry-lite-c4959xva.js → vm-hands-entry-lite-hfx1q0b0.js} +2 -2
  58. package/bin/vm-hands/{vm-hands-entry-lite-c0t5xpzh.js → vm-hands-entry-lite-hv3dxd5k.js} +1 -1
  59. package/bin/vm-hands/{vm-hands-entry-lite-5wsygx6n.js → vm-hands-entry-lite-j5t2pj4v.js} +2 -2
  60. package/bin/vm-hands/{vm-hands-entry-lite-haws181e.js → vm-hands-entry-lite-jvszqt0z.js} +2 -2
  61. package/bin/vm-hands/{vm-hands-entry-lite-sfmeafdm.js → vm-hands-entry-lite-k9vk84wa.js} +2 -2
  62. package/bin/vm-hands/{vm-hands-entry-lite-5qanp33p.js → vm-hands-entry-lite-m9416h05.js} +1 -1
  63. package/bin/vm-hands/{vm-hands-entry-lite-9knf91et.js → vm-hands-entry-lite-mzj7j4hp.js} +2 -2
  64. package/bin/vm-hands/{vm-hands-entry-lite-scvg31ds.js → vm-hands-entry-lite-nwq5fgz9.js} +7 -7
  65. package/bin/vm-hands/{vm-hands-entry-lite-r31yba20.js → vm-hands-entry-lite-q3mgvd2b.js} +2 -2
  66. package/bin/vm-hands/{vm-hands-entry-lite-88yjxxvf.js → vm-hands-entry-lite-qc6gxqgs.js} +4 -4
  67. package/bin/vm-hands/{vm-hands-entry-lite-n3274tws.js → vm-hands-entry-lite-vj7xzb3y.js} +1 -1
  68. package/bin/vm-hands/{vm-hands-entry-lite-9x81cr3a.js → vm-hands-entry-lite-xe0benev.js} +3 -3
  69. package/bin/vm-hands/vm-hands-entry-lite-y5hv1gjv.js +3 -0
  70. package/bin/vm-hands/{vm-hands-entry-lite-td73npv3.js → vm-hands-entry-lite-y9jarm7q.js} +2 -2
  71. package/bin/vm-hands/{vm-hands-entry-lite-ckezse0f.js → vm-hands-entry-lite-yptpy066.js} +2 -2
  72. package/bin/vm-hands/{vm-hands-entry-lite-4cdn822w.js → vm-hands-entry-lite-ztsp4gs8.js} +3 -3
  73. package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
  74. package/bin/vm-hands/{vm-hands-executor-ftg1qx7c.js → vm-hands-executor-htmapgrt.js} +2 -2
  75. package/bin/vm-hands/{vm-hands-op-runner-agy05x0c.js → vm-hands-op-runner-gmsqah3r.js} +1 -1
  76. package/bin/vm-hands/{vm-hands-runtime-kbdb0rj5.js → vm-hands-runtime-004m9v3r.js} +3 -3
  77. package/bin/vm-hands/worker-preview-readiness-84stxabw.js +2 -0
  78. package/bin/vm-hands/worker-sandbox-563c5g2f.js +2 -0
  79. package/package.json +1 -1
  80. package/bin/vm-hands/api-468skzhq.js +0 -2
  81. package/bin/vm-hands/api-credentials-9f82kd61.js +0 -2
  82. package/bin/vm-hands/connect-cli-4t15y12x.js +0 -2
  83. package/bin/vm-hands/credentials-md79hkqh.js +0 -2
  84. package/bin/vm-hands/desktop-account-gm7m5bwr.js +0 -2
  85. package/bin/vm-hands/desktop-wallpaper-0pjhgyfk.jpg +0 -0
  86. package/bin/vm-hands/device-workspace-qjyzphga.js +0 -2
  87. package/bin/vm-hands/dock-browser-afp005mt.png +0 -0
  88. package/bin/vm-hands/dock-files-rywdm96b.png +0 -0
  89. package/bin/vm-hands/dock-terminal-s41cj1jp.png +0 -0
  90. package/bin/vm-hands/hands-worker-source-hzkacxxz.js +0 -2
  91. package/bin/vm-hands/install-receipt-qtwtzafq.js +0 -2
  92. package/bin/vm-hands/local-automation-wjsbhagn.js +0 -2
  93. package/bin/vm-hands/local-capabilities-45tqt3q6.js +0 -2
  94. package/bin/vm-hands/local-desktop-users-qdpbfh6s.js +0 -2
  95. package/bin/vm-hands/local-display-session-efjd2gvs.js +0 -2
  96. package/bin/vm-hands/local-display-video-bdmm490z.js +0 -2
  97. package/bin/vm-hands/local-managed-process-z5jpvttg.js +0 -2
  98. package/bin/vm-hands/local-pty-session-s60ca00y.js +0 -2
  99. package/bin/vm-hands/managed-runtime-ze7n8w7x.js +0 -2
  100. package/bin/vm-hands/permissions-k1tnx28f.js +0 -2
  101. package/bin/vm-hands/serve-service-3kj6xp04.js +0 -2
  102. package/bin/vm-hands/version-qxsa289q.js +0 -2
  103. package/bin/vm-hands/vm-hands-entry-lite-413em054.js +0 -150
  104. package/bin/vm-hands/vm-hands-entry-lite-9y3dvyfj.js +0 -2
  105. package/bin/vm-hands/vm-hands-entry-lite-dhb4fwrv.js +0 -4
  106. package/bin/vm-hands/vm-hands-entry-lite-f8ts9y2q.js +0 -3
  107. package/bin/vm-hands/vm-hands-entry-lite-mcjca0ez.js +0 -3
  108. package/bin/vm-hands/worker-preview-readiness-8ftb3nbw.js +0 -2
  109. package/bin/vm-hands/worker-sandbox-k0vx97tx.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{R}from"./vm-hands-entry-lite-a3p6xz53.js";import{Gr}from"./vm-hands-entry-lite-vf02kfyy.js";import{mt}from"./vm-hands-entry-lite-tns12zqc.js";import{a}from"./vm-hands-entry-lite-haws181e.js";import{A}from"./vm-hands-entry-lite-1kt82jes.js";import{randomUUID as f}from"crypto";import{chmodSync as U,closeSync as h,constants as g,existsSync as me,fstatSync as F,lstatSync as p,mkdirSync as B,openSync as G,readFileSync as Y,readdirSync as z,readlinkSync as J,realpathSync as P,renameSync as _,rmSync as L,statSync as K,symlinkSync as _t,unlinkSync as M,writeFileSync as N}from"fs";import{basename as vt,dirname as k,isAbsolute as fe,join as c,relative as ge,resolve as b,sep as _e}from"path";import{createRequire as H}from"module";var q=1,j=1,ye=128,ve=65536;var he=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;var D=/^[a-z0-9_.-]{1,80}$/,be=64,Ee="so.ara.device-broker",Me=[Ee,"com.reasonmachines.device-broker"],Pt=Gr(Me);var we=["service.install_started","service.install_completed","service.install_failed","service.launcher_adopted","service.launcher_conflict","service.started","service.reconnecting","service.reconnected","service.idle_sleep_held","service.idle_sleep_released","service.idle_sleep_failed","service.start_failed","service.stopped","service.exit_failed","service.singleton_rejected","credential.migration_started","credential.migration_completed","credential.migration_failed","credential.store_started","credential.store_completed","credential.store_failed","credential.delete_started","credential.delete_completed","credential.delete_failed","update.check_started","update.not_available","update.download_started","update.downloaded","update.verified","update.activated","update.rollback","update.failed","executor.update.check_started","executor.update.not_available","executor.update.download_started","executor.update.downloaded","executor.update.verified","executor.update.activated","executor.update.rollback","executor.update.failed","identity.refresh_completed","identity.refresh_failed","update.device_moved","update.components_installed","update.deferred","update.deferral_expired","worker.previous_exit","worker.capabilities_withheld","identity.computer_use_unavailable"];function W(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function X(e,t,n=[]){let r=new Set([...t,...n]);return t.every((i)=>(i in e))&&Object.keys(e).every((i)=>r.has(i))}function E(e){return typeof e==="string"&&he.test(e)}function Z(e){return typeof e==="string"&&!Number.isNaN(Date.parse(e))&&new Date(e).toISOString()===e}function I(e){B(e,{recursive:!0,mode:448}),U(e,448)}function Re(e,t){I(k(e));let n=`${e}.${process.pid}.${f()}.tmp`;try{N(n,t,{mode:384,flag:"wx"}),U(n,384),_(n,e)}finally{if(me(n))M(n)}}function Rs(e={}){if((e.platform??process.platform)!=="darwin")throw new mt("unsupported_platform","The managed Reason runtime is currently available only on macOS.");let n=e.environment??process.env,r=R(n,"REASON_CLI_CHANNEL")==="staging",i=r?R(n,"REASON_MANAGED_RUNTIME_ROOT")?.trim():void 0,o=e.root!==void 0||Boolean(i&&fe(i))?null:c(e.home??a(),"Library","Application Support"),d=e.root??(o?c(o,r?"Reason Staging":"Reason","CLI"):i);return{executableName:"reason",root:d,...o?{legacyRoot:c(o,"Ara",...r?["staging","runtime"]:["runtime"])}:{},versions:c(d,"versions"),current:c(d,"current"),previous:c(d,"previous"),brokerLock:c(d,"broker.lock"),transitionLock:c(d,"transition.lock"),lifecycleEvents:c(d,"lifecycle-events")}}function Ts(e){let t=e.legacyRoot;if(!t)return null;return{root:t,versions:c(t,"versions"),current:c(t,"current"),previous:c(t,"previous"),brokerLock:c(t,"broker.lock"),transitionLock:c(t,"transition.lock"),lifecycleEvents:c(t,"lifecycle-events")}}function pe(e,t){let n;try{if(!p(e).isSymbolicLink())return null;n=J(e)}catch{return null}let r=n.match(/^versions\/(\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)\/(ara|Reason|reason)$/);return r&&(r[2]==="ara"||r[2]===t)?r[1]:null}function Os(e){return pe(e.current,e.executableName)}function O(e,t,n){let i=ge(t,e).split(_e);return i.length===2&&E(i[0])&&(i[1]==="ara"||n!==void 0&&i[1]===n)?i[0]:null}function Le(e,t){try{return p(t).isSymbolicLink()&&b(k(t),J(t))===b(e.current)}catch{return!1}}function Is(e,t=process.execPath){try{return O(P(t),P(e.versions),e.executableName)!==null}catch{let n=b(t);return n===b(e.current)||Le(e,n)||O(n,b(e.versions),e.executableName)!==null}}function Ae(e){return W(e)&&X(e,["schema_version","pid","nonce","started_at","runtime_version"])&&e.schema_version===q&&typeof e.pid==="number"&&Number.isSafeInteger(e.pid)&&e.pid>0&&typeof e.nonce==="string"&&/^[0-9a-f-]{36}$/.test(e.nonce)&&Z(e.started_at)&&E(e.runtime_version)}function Q(e,t){try{let n=p(e);if(!n.isDirectory()||!A(n))return null;let r=G(c(e,t),g.O_RDONLY|g.O_NOFOLLOW|g.O_NONBLOCK);try{let i=F(r);if(!i.isFile()||i.nlink!==1||!A(i)||i.size>4096)return null;return Y(r,"utf8")}finally{h(r)}}catch{return null}}function S(e){try{let t=JSON.parse(Q(e,"owner.json")??"null");return Ae(t)?t:null}catch{return null}}function ee(e){try{return process.kill(e,0),!0}catch(t){return!(t instanceof Error&&("code"in t)&&t.code==="ESRCH")}}var C="lease",Ne=2,Se=4,y;function ke(){if(y!==void 0)return y;if(y=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let e;try{e=H(import.meta.url)("bun:ffi")}catch{return null}let t=process.platform==="darwin"?"__error":"__errno_location",n=process.platform==="darwin"?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`];for(let r of n)try{let i=e.dlopen(r,{flock:{args:[e.FFIType.i32,e.FFIType.i32],returns:e.FFIType.i32},[t]:{args:[],returns:e.FFIType.ptr}}),s=i.symbols[t]();if(s===null)continue;return y={flock:(o,d)=>i.symbols.flock(o,d),errno:()=>e.read.i32(s),wouldBlock:process.platform==="darwin"?35:11},y}catch{}return null}var v,Ie=3221225472,Te=4,xe=128,Pe=32;function De(e){if(v===void 0){v=null;try{let s=H(import.meta.url)("bun:ffi"),{FFIType:o}=s;v={kernel:s.dlopen("kernel32.dll",{CreateFileW:{args:[o.ptr,o.u32,o.u32,o.ptr,o.u32,o.u32,o.ptr],returns:o.i64_fast},CloseHandle:{args:[o.i64_fast],returns:o.i32},GetLastError:{args:[],returns:o.u32}}).symbols,ptr:(l)=>s.ptr(l)}}catch{return null}}if(!v)return null;let{kernel:t,ptr:n}=v,r=Buffer.from(`${e}\x00`,"utf16le"),i=t.CreateFileW(n(r),Ie,0,null,Te,xe,null);if(Number(i)===-1)return t.GetLastError()===Pe?"busy":null;return{release:()=>{t.CloseHandle(i)}}}function Oe(e){if(process.platform==="win32")return De(`${e}.lease`);let t=ke();if(!t)return null;let n=G(`${e}.lease`,g.O_RDWR|g.O_CREAT|g.O_NOFOLLOW,384);try{let r=F(n);if(!r.isFile()||r.nlink!==1||!A(r))return h(n),"busy";if(t.flock(n,Ne|Se)===0)return{release:()=>h(n)};let i=t.errno();return h(n),i===t.wouldBlock?"busy":null}catch(r){throw h(n),r}}function Ds(e){I(k(e.path));let t=Oe(e.path);if(t==="busy")return{acquired:!1,owner:S(e.path),recoveredStaleOwner:!1};let n=t!==null;try{let r=Ce(e,t);if(r.acquired)n=!1;return r}finally{if(n)t.release()}}function Ce(e,t){let n=e.alive??ee,r=!1;for(let i=0;i<4;i+=1){let s={schema_version:q,pid:e.pid??process.pid,nonce:e.nonce?.()??f(),started_at:(e.now?.()??new Date).toISOString(),runtime_version:e.runtimeVersion},o=`${e.path}.init-${process.pid}-${f()}`,d=!1;try{if(B(o,{mode:448}),N(c(o,"owner.json"),`${JSON.stringify(s)}
2
+ import{R}from"./vm-hands-entry-lite-a3p6xz53.js";import{Gr}from"./vm-hands-entry-lite-3x6zetc0.js";import{mt}from"./vm-hands-entry-lite-73f4cgkf.js";import{a}from"./vm-hands-entry-lite-jvszqt0z.js";import{A}from"./vm-hands-entry-lite-b6gsggvp.js";import{randomUUID as f}from"crypto";import{chmodSync as U,closeSync as h,constants as g,existsSync as me,fstatSync as F,lstatSync as p,mkdirSync as B,openSync as G,readFileSync as Y,readdirSync as z,readlinkSync as J,realpathSync as P,renameSync as _,rmSync as L,statSync as K,symlinkSync as _t,unlinkSync as M,writeFileSync as N}from"fs";import{basename as vt,dirname as k,isAbsolute as fe,join as c,relative as ge,resolve as b,sep as _e}from"path";import{createRequire as H}from"module";var q=1,j=1,ye=128,ve=65536;var he=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;var D=/^[a-z0-9_.-]{1,80}$/,be=64,Ee="so.ara.device-broker",Me=[Ee,"com.reasonmachines.device-broker"],Pt=Gr(Me);var we=["service.install_started","service.install_completed","service.install_failed","service.launcher_adopted","service.launcher_conflict","service.started","service.reconnecting","service.reconnected","service.idle_sleep_held","service.idle_sleep_released","service.idle_sleep_failed","service.start_failed","service.stopped","service.exit_failed","service.singleton_rejected","credential.migration_started","credential.migration_completed","credential.migration_failed","credential.store_started","credential.store_completed","credential.store_failed","credential.delete_started","credential.delete_completed","credential.delete_failed","update.check_started","update.not_available","update.download_started","update.downloaded","update.verified","update.activated","update.rollback","update.failed","executor.update.check_started","executor.update.not_available","executor.update.download_started","executor.update.downloaded","executor.update.verified","executor.update.activated","executor.update.rollback","executor.update.failed","identity.refresh_completed","identity.refresh_failed","update.device_moved","update.components_installed","update.deferred","update.deferral_expired","worker.previous_exit","worker.capabilities_withheld","identity.computer_use_unavailable"];function W(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function X(e,t,n=[]){let r=new Set([...t,...n]);return t.every((i)=>(i in e))&&Object.keys(e).every((i)=>r.has(i))}function E(e){return typeof e==="string"&&he.test(e)}function Z(e){return typeof e==="string"&&!Number.isNaN(Date.parse(e))&&new Date(e).toISOString()===e}function I(e){B(e,{recursive:!0,mode:448}),U(e,448)}function Re(e,t){I(k(e));let n=`${e}.${process.pid}.${f()}.tmp`;try{N(n,t,{mode:384,flag:"wx"}),U(n,384),_(n,e)}finally{if(me(n))M(n)}}function Rs(e={}){if((e.platform??process.platform)!=="darwin")throw new mt("unsupported_platform","The managed Reason runtime is currently available only on macOS.");let n=e.environment??process.env,r=R(n,"REASON_CLI_CHANNEL")==="staging",i=r?R(n,"REASON_MANAGED_RUNTIME_ROOT")?.trim():void 0,o=e.root!==void 0||Boolean(i&&fe(i))?null:c(e.home??a(),"Library","Application Support"),d=e.root??(o?c(o,r?"Reason Staging":"Reason","CLI"):i);return{executableName:"reason",root:d,...o?{legacyRoot:c(o,"Ara",...r?["staging","runtime"]:["runtime"])}:{},versions:c(d,"versions"),current:c(d,"current"),previous:c(d,"previous"),brokerLock:c(d,"broker.lock"),transitionLock:c(d,"transition.lock"),lifecycleEvents:c(d,"lifecycle-events")}}function Ts(e){let t=e.legacyRoot;if(!t)return null;return{root:t,versions:c(t,"versions"),current:c(t,"current"),previous:c(t,"previous"),brokerLock:c(t,"broker.lock"),transitionLock:c(t,"transition.lock"),lifecycleEvents:c(t,"lifecycle-events")}}function pe(e,t){let n;try{if(!p(e).isSymbolicLink())return null;n=J(e)}catch{return null}let r=n.match(/^versions\/(\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)\/(ara|Reason|reason)$/);return r&&(r[2]==="ara"||r[2]===t)?r[1]:null}function Is(e){return pe(e.current,e.executableName)}function O(e,t,n){let i=ge(t,e).split(_e);return i.length===2&&E(i[0])&&(i[1]==="ara"||n!==void 0&&i[1]===n)?i[0]:null}function Le(e,t){try{return p(t).isSymbolicLink()&&b(k(t),J(t))===b(e.current)}catch{return!1}}function Ds(e,t=process.execPath){try{return O(P(t),P(e.versions),e.executableName)!==null}catch{let n=b(t);return n===b(e.current)||Le(e,n)||O(n,b(e.versions),e.executableName)!==null}}function Ae(e){return W(e)&&X(e,["schema_version","pid","nonce","started_at","runtime_version"])&&e.schema_version===q&&typeof e.pid==="number"&&Number.isSafeInteger(e.pid)&&e.pid>0&&typeof e.nonce==="string"&&/^[0-9a-f-]{36}$/.test(e.nonce)&&Z(e.started_at)&&E(e.runtime_version)}function Q(e,t){try{let n=p(e);if(!n.isDirectory()||!A(n))return null;let r=G(c(e,t),g.O_RDONLY|g.O_NOFOLLOW|g.O_NONBLOCK);try{let i=F(r);if(!i.isFile()||i.nlink!==1||!A(i)||i.size>4096)return null;return Y(r,"utf8")}finally{h(r)}}catch{return null}}function S(e){try{let t=JSON.parse(Q(e,"owner.json")??"null");return Ae(t)?t:null}catch{return null}}function ee(e){try{return process.kill(e,0),!0}catch(t){return!(t instanceof Error&&("code"in t)&&t.code==="ESRCH")}}var C="lease",Ne=2,Se=4,y;function ke(){if(y!==void 0)return y;if(y=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let e;try{e=H(import.meta.url)("bun:ffi")}catch{return null}let t=process.platform==="darwin"?"__error":"__errno_location",n=process.platform==="darwin"?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`];for(let r of n)try{let i=e.dlopen(r,{flock:{args:[e.FFIType.i32,e.FFIType.i32],returns:e.FFIType.i32},[t]:{args:[],returns:e.FFIType.ptr}}),s=i.symbols[t]();if(s===null)continue;return y={flock:(o,d)=>i.symbols.flock(o,d),errno:()=>e.read.i32(s),wouldBlock:process.platform==="darwin"?35:11},y}catch{}return null}var v,Ie=3221225472,Te=4,xe=128,Pe=32;function De(e){if(v===void 0){v=null;try{let s=H(import.meta.url)("bun:ffi"),{FFIType:o}=s;v={kernel:s.dlopen("kernel32.dll",{CreateFileW:{args:[o.ptr,o.u32,o.u32,o.ptr,o.u32,o.u32,o.ptr],returns:o.i64_fast},CloseHandle:{args:[o.i64_fast],returns:o.i32},GetLastError:{args:[],returns:o.u32}}).symbols,ptr:(l)=>s.ptr(l)}}catch{return null}}if(!v)return null;let{kernel:t,ptr:n}=v,r=Buffer.from(`${e}\x00`,"utf16le"),i=t.CreateFileW(n(r),Ie,0,null,Te,xe,null);if(Number(i)===-1)return t.GetLastError()===Pe?"busy":null;return{release:()=>{t.CloseHandle(i)}}}function Oe(e){if(process.platform==="win32")return De(`${e}.lease`);let t=ke();if(!t)return null;let n=G(`${e}.lease`,g.O_RDWR|g.O_CREAT|g.O_NOFOLLOW,384);try{let r=F(n);if(!r.isFile()||r.nlink!==1||!A(r))return h(n),"busy";if(t.flock(n,Ne|Se)===0)return{release:()=>h(n)};let i=t.errno();return h(n),i===t.wouldBlock?"busy":null}catch(r){throw h(n),r}}function Os(e){I(k(e.path));let t=Oe(e.path);if(t==="busy")return{acquired:!1,owner:S(e.path),recoveredStaleOwner:!1};let n=t!==null;try{let r=Ce(e,t);if(r.acquired)n=!1;return r}finally{if(n)t.release()}}function Ce(e,t){let n=e.alive??ee,r=!1;for(let i=0;i<4;i+=1){let s={schema_version:q,pid:e.pid??process.pid,nonce:e.nonce?.()??f(),started_at:(e.now?.()??new Date).toISOString(),runtime_version:e.runtimeVersion},o=`${e.path}.init-${process.pid}-${f()}`,d=!1;try{if(B(o,{mode:448}),N(c(o,"owner.json"),`${JSON.stringify(s)}
3
3
  `,{mode:384,flag:"wx"}),t!==null)N(c(o,C),`flock
4
4
  `,{mode:384,flag:"wx"});e.beforePublish?.();try{throw p(e.path),Object.assign(Error("Managed runtime lock exists."),{code:"EEXIST"})}catch(m){if(m.code!=="ENOENT")throw m}_(o,e.path),d=!0;let l=!1;return{acquired:!0,owner:s,recoveredStaleOwner:r,release(){if(l)return;if(l=!0,S(e.path)?.nonce===s.nonce)L(e.path,{recursive:!0,force:!0});t?.release()}}}catch(l){let m=l.code;if(!["EEXIST","ENOTEMPTY"].includes(m??""))throw l;let u=S(e.path),re=(e.now?.()??new Date).getTime(),ie=u&&e.staleAfterMs!==void 0?re-Date.parse(u.started_at)<e.staleAfterMs:!1,ae=u!==null&&!(t!==null&&Q(e.path,C)!==null)&&n(u.pid);if(!u||ae||ie)return{acquired:!1,owner:u,recoveredStaleOwner:!1};let T=`${e.path}.stale-${process.pid}-${f()}`;try{_(e.path,T),L(T,{recursive:!0,force:!0}),r=!0}catch(x){let oe=x.code;if(!["ENOENT","EEXIST"].includes(oe??""))throw x}}finally{if(!d)L(o,{recursive:!0,force:!0})}}throw new mt("lock_unavailable","Could not acquire the managed Reason runtime lock.")}function te(e){return W(e)&&X(e,["schema_version","event_id","occurred_at","event","runtime_version"],["from_version","to_version","reason_code","duration_ms","attempt_count","retry_in_ms","capabilities"])&&e.schema_version===j&&typeof e.event_id==="string"&&/^[0-9a-f-]{36}$/.test(e.event_id)&&Z(e.occurred_at)&&typeof e.event==="string"&&we.includes(e.event)&&E(e.runtime_version)&&(e.from_version===void 0||E(e.from_version))&&(e.to_version===void 0||E(e.to_version))&&(e.reason_code===void 0||typeof e.reason_code==="string"&&D.test(e.reason_code))&&(e.duration_ms===void 0||typeof e.duration_ms==="number"&&Number.isSafeInteger(e.duration_ms)&&e.duration_ms>=0&&e.duration_ms<=86400000)&&(e.attempt_count===void 0||typeof e.attempt_count==="number"&&Number.isSafeInteger(e.attempt_count)&&e.attempt_count>=1&&e.attempt_count<=1e5)&&(e.retry_in_ms===void 0||typeof e.retry_in_ms==="number"&&Number.isSafeInteger(e.retry_in_ms)&&e.retry_in_ms>=0&&e.retry_in_ms<=30000)&&(e.capabilities===void 0||Array.isArray(e.capabilities)&&e.capabilities.length<=be&&e.capabilities.every((t)=>typeof t==="string"&&D.test(t)))}var Ve=/^(\d{22}-[0-9a-f-]{36}\.json)$/,Ue=/^(\d{22}-[0-9a-f-]{36}\.json)\.sending-(\d+)-[0-9a-f-]{36}$/,Fe=300000,w=0n;function Be(e){let t=BigInt(new Date(e.occurred_at).getTime())*1000000n;return w=t>w?t:w+1n,`${String(w).padStart(22,"0")}-${e.event_id}.json`}function ne(e){try{return z(e.lifecycleEvents).filter((t)=>Ve.test(t)).sort()}catch{return[]}}function V(e){try{let t=JSON.parse(Y(e,"utf8"));return te(t)?t:null}catch{return null}}function $e(e,t=ee,n=Date.now()){let r;try{r=z(e.lifecycleEvents)}catch{return}for(let i of r){let s=i.match(Ue);if(!s)continue;let o=c(e.lifecycleEvents,i),d=c(e.lifecycleEvents,s[1]),l=!t(Number(s[2]));if(!l)try{l=n-K(o).mtimeMs>=Fe}catch{continue}if(!l)continue;try{_(o,d)}catch(m){let u=m.code;if(u==="EEXIST")M(o);else if(u!=="ENOENT")throw m}}}function Ge(e){let n=ne(e).flatMap((i)=>{try{return[{name:i,size:K(c(e.lifecycleEvents,i)).size}]}catch{return[]}}),r=n.reduce((i,s)=>i+s.size,0);while(n.length>ye||r>ve){let i=n.shift();if(!i)break;try{M(c(e.lifecycleEvents,i.name)),r-=i.size}catch(s){if(s.code!=="ENOENT")throw s}}}function Ns(e,t,n={}){let r={schema_version:j,event_id:n.eventId?.()??f(),occurred_at:(n.now?.()??new Date).toISOString(),...t};if(!te(r))throw new mt("invalid_lifecycle_event","Managed runtime lifecycle event is invalid.");return I(e.lifecycleEvents),Re(c(e.lifecycleEvents,Be(r)),`${JSON.stringify(r)}
5
- `),Ge(e),r}async function Ls(e,t,n){$e(e);let r=0;for(let i of ne(e)){let s=c(e.lifecycleEvents,i);if(n){let l=V(s);if(!l||!n(l))continue}let o=`${s}.sending-${process.pid}-${f()}`;try{_(s,o)}catch(l){if(l.code==="ENOENT")continue;throw l}let d=V(o);if(!d){M(o);continue}try{await t(d),M(o),r+=1}catch{try{_(o,s)}catch(l){if(l.code!=="ENOENT")throw l}break}}return r}export{Rs,Ts,Os,Is,Ds,Ns,Ls};
5
+ `),Ge(e),r}async function Ls(e,t,n){$e(e);let r=0;for(let i of ne(e)){let s=c(e.lifecycleEvents,i);if(n){let l=V(s);if(!l||!n(l))continue}let o=`${s}.sending-${process.pid}-${f()}`;try{_(s,o)}catch(l){if(l.code==="ENOENT")continue;throw l}let d=V(o);if(!d){M(o);continue}try{await t(d),M(o),r+=1}catch{try{_(o,s)}catch(l){if(l.code!=="ENOENT")throw l}break}}return r}export{Rs,Ts,Is,Ds,Os,Ns,Ls};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{_,Yr,yt,ke}from"./vm-hands-entry-lite-t82dzcxb.js";import{No}from"./vm-hands-entry-lite-tns12zqc.js";import{a}from"./vm-hands-entry-lite-haws181e.js";import{t,i,s,n}from"./vm-hands-entry-lite-4cdn822w.js";import{createHmac as _t,createPublicKey as be,randomBytes as bt,randomUUID as me,verify as he}from"crypto";import{chmodSync as L,existsSync as z,mkdirSync as Se,readFileSync as Ie,realpathSync as St,renameSync as De,statSync as It,unlinkSync as Le,writeFileSync as we}from"fs";import{basename as Dt,dirname as w,isAbsolute as Ae,join as m,resolve as Lt}from"path";var $e=[Object.freeze({family:"ara",channel:"stable",applicationId:"so.ara.desktop"}),Object.freeze({family:"ara",channel:"staging",applicationId:"so.ara.desktop.staging"}),Object.freeze({family:"reason",channel:"stable",applicationId:"com.reasonmachines.desktop"}),Object.freeze({family:"reason",channel:"staging",applicationId:"com.reasonmachines.desktop.staging"})];var Z="REASON_DESKTOP_RUNTIME",q="REASON_DESKTOP_RUNTIME_CHANNEL",Q="REASON_DESKTOP_RUNTIME_INSTANCE_ID",ee="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",We={[Z]:"ARA_DESKTOP_RUNTIME",[q]:"ARA_DESKTOP_RUNTIME_CHANNEL",[Q]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[ee]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function x(r){if(r===void 0)return;if(!/^[a-f0-9]{64}$/.test(r))throw Error("Invalid desktop workspace scope.");return r}import{chmodSync as h,existsSync as g,mkdirSync as S,readFileSync as N,realpathSync as te,renameSync as ne,unlinkSync as I,writeFileSync as k}from"fs";import{createPrivateKey as ie,createPublicKey as re,generateKeyPairSync as oe,randomUUID as ae,sign as se}from"crypto";import{createRequire as ce}from"module";import{homedir as le,platform as T}from"os";import{dirname as de,join as f}from"path";var O=1,ue=16384,y=65536,pe=128,ge=128,U=65536;class l extends Error{code;nativeStatus;constructor(r,e){super(`Reason Device proof boundary failed (${r}).${e===void 0?"":` Native status: ${e}.`}`);this.code=r;this.nativeStatus=e;this.name="LocalCredentialBoundaryError"}}var D=null;function F(){if(!D)try{D=ce(import.meta.url)("bun:ffi")}catch{throw new l("native_boundary_unavailable")}return D}function fe(r){if(typeof r!=="string")return null;try{let e=new URL(r);if(e.protocol!=="https:"&&e.hostname!=="127.0.0.1"&&e.hostname!=="localhost"&&e.hostname!=="[::1]"&&e.hostname!=="::1")return null;return e.origin}catch{return null}}function ye(r){if(!r||typeof r!=="object"||Array.isArray(r))throw new l("invalid_credential_record");let e=r,o=fe(e.apiOrigin);if(e.version!==O||!o||typeof e.orgId!=="string"||e.orgId.length<1||e.orgId.length>160||typeof e.deviceId!=="string"||e.deviceId.length<1||e.deviceId.length>160||typeof e.credential!=="string"||!/^(?:reason|ara)_dev_/.test(e.credential)||e.credential.length>4096)throw new l("invalid_credential_record");return{version:O,apiOrigin:o,orgId:e.orgId,deviceId:e.deviceId,credential:e.credential}}function Gt(r=process.execPath){let e=r;try{e=te(r)}catch{}return No(de(e))}function u(r){return F().ptr(r)}function ve(r){if(!g(r))throw new l("native_boundary_unavailable");let{dlopen:e,FFIType:o}=F();try{return e(r,{ara_device_configure_scope:{args:[o.ptr,o.u64],returns:o.i32},ara_device_key_load_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_create_fresh_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_sign:{args:[o.ptr,o.u64,o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_is_non_extractable:{args:[o.ptr],returns:o.i32},ara_device_key_delete:{args:[o.ptr],returns:o.i32},ara_device_binding_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_binding_create:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_update:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_delete:{args:[o.ptr],returns:o.i32},ara_device_keychain_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_keychain_delete:{args:[o.ptr],returns:o.i32}})}catch(c){if(c instanceof l)throw c;throw new l("native_boundary_unavailable")}}function K(r){return Buffer.from(r).toString("base64url")}function v(r){if(typeof r!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(r))return!1;try{let e=Buffer.from(r,"base64url");return e.byteLength===65&&e[0]===4}catch{return!1}}function M(r){if(r.byteLength<8||r.byteLength>72||r[0]!==48)return!1;let e=r[1];return e!==void 0&&e<128&&e+2===r.byteLength}class Ke{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(r=Gt(),e=T(),o){this.libraryPath=r;this.runtimePlatform=e;this.workspaceScope=o;x(o)}symbols(){if(this.runtimePlatform!=="darwin")throw new l("unsupported_platform");this.library??=ve(this.libraryPath);let r=new TextEncoder().encode(this.workspaceScope??""),e=this.library.symbols.ara_device_configure_scope(u(r.length?r:new Uint8Array(1)),BigInt(r.length));if(e!==0)throw new l("native_boundary_unavailable",e);return this.library.symbols}publicKey(r){let e=new Uint8Array(pe),o=new BigUint64Array(1),c=r==="load"?this.symbols().ara_device_key_load_public(u(e),BigInt(e.byteLength),u(o)):this.symbols().ara_device_key_create_fresh_public(u(e),BigInt(e.byteLength),u(o));if(c!==0)throw new l(r==="load"?"proof_key_read_failed":"proof_key_generation_failed",c);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d!==65)throw new l("invalid_public_key");let p=K(e.subarray(0,d));if(!v(p))throw new l("invalid_public_key");return p}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(r){if(r.byteLength<1||r.byteLength>U)throw new l("proof_sign_failed");let e=new Uint8Array(ge),o=new BigUint64Array(1),c=this.symbols().ara_device_key_sign(u(r),BigInt(r.byteLength),u(e),BigInt(e.byteLength),u(o));if(c!==0)throw new l("proof_sign_failed",c);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d<1||d>e.byteLength)throw new l("invalid_signature");let p=e.subarray(0,d);if(!M(p))throw new l("invalid_signature");return K(p)}privateKeyIsNonExtractable(){let r=new Uint8Array(1),e=this.symbols().ara_device_key_is_non_extractable(u(r));if(e!==0||r[0]!==1)throw new l("proof_key_read_failed",e);return!0}deleteKey(){let r=new Uint8Array(1),e=this.symbols().ara_device_key_delete(u(r));if(e!==0)throw new l("proof_key_delete_failed",e);return r[0]===1}loadBinding(){let r=new Uint8Array(y),e=new BigUint64Array(1),o=this.symbols().ara_device_binding_read(u(r),BigInt(r.byteLength),u(e));if(o===1)return null;if(o!==0)throw new l("binding_read_failed",o);let c=Number(e[0]);if(!Number.isSafeInteger(c)||c<1||c>r.byteLength)throw new l("invalid_binding");return r.slice(0,c)}createBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");let e=this.symbols().ara_device_binding_create(u(r),BigInt(r.byteLength));if(e!==0)throw new l("binding_create_failed",e)}updateBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");let e=this.symbols().ara_device_binding_update(u(r),BigInt(r.byteLength));if(e!==0)throw new l("binding_update_failed",e)}deleteBinding(){let r=new Uint8Array(1),e=this.symbols().ara_device_binding_delete(u(r));if(e!==0)throw new l("binding_delete_failed",e);return r[0]===1}loadLegacyCredential(){let r=new Uint8Array(ue),e=new BigUint64Array(1),o=this.symbols().ara_device_keychain_read(u(r),BigInt(r.byteLength),u(e));if(o===1)return null;if(o!==0)throw new l("legacy_credential_read_failed",o);let c=Number(e[0]);if(!Number.isSafeInteger(c)||c<1||c>r.byteLength)throw new l("invalid_credential_record");try{let d=new TextDecoder("utf-8",{fatal:!0}).decode(r.subarray(0,c));return ye(JSON.parse(d))}catch(d){if(d instanceof l)throw d;throw new l("invalid_credential_record")}}deleteLegacyCredential(){let r=new Uint8Array(1),e=this.symbols().ara_device_keychain_delete(u(r));if(e!==0)throw new l("legacy_credential_delete_failed",e);return r[0]===1}}function C(r){let e=r.export({format:"jwk"});if(e.crv!=="P-256"||typeof e.x!=="string"||typeof e.y!=="string")throw new l("invalid_public_key");let o=Buffer.from(e.x,"base64url"),c=Buffer.from(e.y,"base64url");if(o.byteLength!==32||c.byteLength!==32)throw new l("invalid_public_key");let d=Buffer.concat([Buffer.of(4),o,c]).toString("base64url");if(!v(d))throw new l("invalid_public_key");return d}function _e(){let r=process.env.XDG_CONFIG_HOME?.trim()||f(le(),".config");yt(r);let e=f(r,"ara");return Yr(e)?e:f(r,"reason")}class Lr{directory;constructor(r=_e()){this.directory=r}keyPath(){return f(this.directory,"local-device.key")}bindingPath(){return f(this.directory,"local-device.binding")}loadPrivateKeyObject(){let r=this.keyPath();if(!g(r))throw new l("proof_key_read_failed");try{let e=N(r,"utf8");return ie({key:e,format:"pem"})}catch{throw new l("proof_key_read_failed")}}loadPublicKey(){let r=this.loadPrivateKeyObject(),e=re(r);return C(e)}createFreshPublicKey(){S(this.directory,{recursive:!0,mode:448});let{privateKey:r,publicKey:e}=oe("ec",{namedCurve:"P-256"}),o=r.export({type:"pkcs8",format:"pem"}),c=this.keyPath();return k(c,o,{mode:384}),h(c,384),C(e)}sign(r){if(r.byteLength<1||r.byteLength>U)throw new l("proof_sign_failed");let e=this.loadPrivateKeyObject(),o;try{o=se("sha256",r,e)}catch{throw new l("proof_sign_failed")}if(!M(o))throw new l("invalid_signature");return o.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let r=this.keyPath();if(!g(r))return!1;return I(r),!0}loadBinding(){let r=this.bindingPath();if(!g(r))return null;try{return new Uint8Array(N(r))}catch{return null}}createBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");S(this.directory,{recursive:!0,mode:448});let e=this.bindingPath();if(g(e))throw new l("binding_create_failed");k(e,r,{mode:384}),h(e,384)}updateBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");S(this.directory,{recursive:!0,mode:448});let e=this.bindingPath();if(!g(e))throw new l("binding_update_failed");let o=`${e}.${ae()}`;try{k(o,r,{mode:384,flag:"wx"}),h(o,384),ne(o,e)}finally{if(g(o))I(o)}}deleteBinding(){let r=this.bindingPath();if(!g(r))return!1;return I(r),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function V(){return T()==="darwin"?new Ke:new Lr}var b=t().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),B=i({id:b,kind:n("permission_denied"),operation:s(["bash","read","write","edit"]),provenance:s(["sandbox_policy","os_permission_unknown"]),occurredAt:t().datetime(),expiresAt:t().datetime(),sessionId:b,deviceId:b,organizationId:b}).strict();var A=4;var P="macos-keychain-p256-v1",Pe=1,Ee=`ARA-DEVICE-BINDING-V1
3
- `;function Re(r){return r===void 0||typeof r==="number"&&Number.isInteger(r)&&r>=1&&r<=4}function G(r,e=Date.now()){let o=B.safeParse(r);if(!o.success)return!1;let c=o.data,d=typeof c.occurredAt==="string"?Date.parse(c.occurredAt):NaN,p=typeof c.expiresAt==="string"?Date.parse(c.expiresAt):NaN;return c.kind==="permission_denied"&&["bash","read","write","edit"].includes(c.operation)&&["sandbox_policy","os_permission_unknown"].includes(c.provenance)&&Number.isFinite(d)&&d<=e&&p>e&&p>d&&p-d<=600000}function Kt(r,e,o=Date.now()){if(!r||!e||r.state!=="connected"||r.deviceId!==e.deviceId)return null;let c=Date.parse(r.lastHeartbeatAt??""),d=r.permissionRecovery;if(!(o-c>=0&&o-c<30000)||!G(d,o)||d.deviceId!==e.deviceId||d.organizationId!==e.orgId)return null;try{process.kill(r.pid,0)}catch{return null}return d}function H(r={},e=a()){let o=_({env:{...process.env,...r}}),c=r.XDG_CONFIG_HOME?.trim()||m(e,".config");return ke(c,...o==="staging"?["staging"]:[])}function Mr(r={},e=a()){return m(H(r,e),"local-device.json")}function xe(r={},e=a()){return m(H(r,e),"local-daemon.json")}function Ne(r,e){Se(w(r),{recursive:!0,mode:448}),L(w(r),448);let o=`${r}.${process.pid}.${me()}.tmp`;try{we(o,`${JSON.stringify(e,null,2)}
4
- `,{mode:384,flag:"wx"}),L(o,384),De(o,r),L(r,384)}finally{if(z(o))Le(o)}return r}function E(r){if(!z(r))return null;try{return JSON.parse(Ie(r,"utf8"))}catch{return null}}function Oe(r){if(!Array.isArray(r))return null;let e=[];for(let o of r){if(!o||typeof o!=="object")return null;let c=o;if(typeof c.id!=="string"||typeof c.label!=="string"||typeof c.path!=="string"||typeof c.pathFingerprint!=="string"||!c.permissions||typeof c.permissions.read!=="boolean"||typeof c.permissions.write!=="boolean"||typeof c.permissions.execute!=="boolean"||typeof c.permissions.discover_environment!=="boolean"||typeof c.permissions.expose_mcp!=="boolean")return null;e.push({id:c.id,label:c.label,path:c.path,pathFingerprint:c.pathFingerprint,permissions:c.permissions})}return e}function J(r,e,o=[]){let c=Object.keys(r);return e.every((d)=>Object.hasOwn(r,d))&&c.every((d)=>e.includes(d)||o.includes(d))}function Ce(r){if(typeof r!=="string")return null;try{let e=new URL(r);if(e.protocol!=="https:"&&e.hostname!=="127.0.0.1"&&e.hostname!=="localhost")return null;return e.origin}catch{return null}}function Y(r){if(!r||typeof r!=="object"||Array.isArray(r))return null;let e=r,o=Oe(e.roots),c=Ce(e.apiOrigin);if(!c||typeof e.orgId!=="string"||typeof e.deviceId!=="string"||typeof e.displayName!=="string"||typeof e.registeredAt!=="string"||!Re(e.handsSlots)||e.worker!==void 0&&(!e.worker||!/^[a-f0-9]{64}$/.test(e.worker.configDigest)||!["persistent","ephemeral"].includes(e.worker.lifetime)||!Number.isFinite(Date.parse(e.worker.expiresAt)))||!o)return null;return{apiOrigin:c,orgId:e.orgId,deviceId:e.deviceId,displayName:e.displayName,registeredAt:e.registeredAt,...e.handsSlots!==void 0?{handsSlots:e.handsSlots}:{},...e.worker!==void 0?{worker:e.worker}:{},roots:o}}function Te(r){return{version:A,apiOrigin:r.apiOrigin,orgId:r.orgId,deviceId:r.deviceId,devicePublicKey:r.devicePublicKey,displayName:r.displayName,registeredAt:r.registeredAt,...r.handsSlots!==void 0?{handsSlots:r.handsSlots}:{},...r.worker!==void 0?{worker:r.worker}:{},roots:r.roots.map((e)=>({id:e.id,label:e.label,path:e.path,pathFingerprint:e.pathFingerprint,permissions:{read:e.permissions.read,write:e.permissions.write,execute:e.permissions.execute,discover_environment:e.permissions.discover_environment,expose_mcp:e.permissions.expose_mcp}})),credentialStorage:P}}function X(r){if(!r||typeof r!=="object"||Array.isArray(r))return null;let e=r;if(!J(e,["version","apiOrigin","orgId","deviceId","devicePublicKey","displayName","registeredAt","roots","credentialStorage"],["handsSlots","worker"]))return null;let o=Y(e);if(!o||e.version!==A||e.credentialStorage!==P||!v(e.devicePublicKey))return null;return{version:A,...o,devicePublicKey:e.devicePublicKey,credentialStorage:P}}function Ue(r){return new TextEncoder().encode(`${Ee}${JSON.stringify(Te(r))}`)}function Fe(r){let e=Buffer.from(r,"base64url");return be({format:"jwk",key:{kty:"EC",crv:"P-256",x:e.subarray(1,33).toString("base64url"),y:e.subarray(33,65).toString("base64url")}})}function Me(r){let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new l("invalid_binding")}if(!e||typeof e!=="object"||Array.isArray(e))throw new l("invalid_binding");let o=e;if(!J(o,["version","state","signature"])||o.version!==Pe||typeof o.signature!=="string"||!/^[A-Za-z0-9_-]{10,128}$/.test(o.signature))throw new l("invalid_binding");let c=X(o.state);if(!c)throw new l("invalid_binding");let d=!1;try{d=he("sha256",Ue(c),Fe(c.devicePublicKey),Buffer.from(o.signature,"base64url"))}catch{d=!1}if(!d)throw new l("invalid_binding");return c}function je(r){let{credentialStorage:e,...o}=r;return o}function $r(r=Mr(),e={}){let o=E(r),c=e.proofStore??e.credentialStore??V(),d=c.loadBinding();if(!d){if(o&&typeof o==="object"&&!Array.isArray(o)&&Ve(o))return null;if(o!==null)throw new l("invalid_binding");return null}let p=Me(d),W=c.loadPublicKey();if(c.privateKeyIsNonExtractable(),W!==p.devicePublicKey)throw new l("invalid_public_key");let R=X(o);if(e.repair!==!1&&(!R||JSON.stringify(R)!==JSON.stringify(p)))Ne(r,p);return je(p)}function Ve(r){let e=r,o=Y(r);if(!o)return null;if(e.version===2){if(typeof e.deviceCredential!=="string"||!/^(?:reason|ara)_dev_/.test(e.deviceCredential)||e.deviceCredential.length>4096)return null;return{state:o,credentialSource:"plaintext-v2"}}if(e.version!==3||e.credentialStorage!=="macos-keychain-v1"||"deviceCredential"in e)return null;return{state:o,credentialSource:"keychain-v3"}}function ht(r=xe()){let e=E(r);if(!e||typeof e!=="object")return null;let o=e;if(o.version!==1||typeof o.pid!=="number"||!Number.isInteger(o.pid)||!["starting","connected","stopped","error"].includes(o.state??"")||typeof o.startedAt!=="string"||o.lastHeartbeatAt!==void 0&&typeof o.lastHeartbeatAt!=="string"||o.lastUsedAt!==void 0&&typeof o.lastUsedAt!=="string"||o.organizationId!==void 0&&typeof o.organizationId!=="string"||o.organizationName!==void 0&&typeof o.organizationName!=="string"||o.organizationSlug!==void 0&&typeof o.organizationSlug!=="string"||o.error!==void 0&&typeof o.error!=="string"||o.reconnectingSince!==void 0&&typeof o.reconnectingSince!=="string"||o.workspace!==void 0&&typeof o.workspace!=="string")return null;if(o.permissionRecovery!==void 0&&!G(o.permissionRecovery))delete o.permissionRecovery;return o}var Jt=1;function Be(r=Mr()){return m(w(r),"local-device.proxy.json")}function j(r=Be()){let e=E(r);if(!e||typeof e!=="object"||Array.isArray(e))return null;let o=e;if(o.version!==Jt||typeof o.url!=="string"||o.url.length===0||o.caFile!==void 0&&(typeof o.caFile!=="string"||!Ae(o.caFile)))return null;return{version:Jt,url:o.url,...o.caFile?{caFile:o.caFile}:{}}}
5
- export{l,Gt,Ke,Lr,Kt,Mr,$r,ht,Jt,j};
2
+ import{_,Zr,yt,ke}from"./vm-hands-entry-lite-4anjdcth.js";import{Lo}from"./vm-hands-entry-lite-73f4cgkf.js";import{a}from"./vm-hands-entry-lite-jvszqt0z.js";import{t,i,s,n}from"./vm-hands-entry-lite-ztsp4gs8.js";import{createHmac as _t,createPublicKey as be,randomBytes as bt,randomUUID as me,verify as he}from"crypto";import{chmodSync as L,existsSync as z,mkdirSync as Se,readFileSync as Ie,realpathSync as St,renameSync as De,statSync as It,unlinkSync as Le,writeFileSync as we}from"fs";import{basename as Dt,dirname as w,isAbsolute as Ae,join as m,resolve as Lt}from"path";var $e=[Object.freeze({family:"ara",channel:"stable",applicationId:"so.ara.desktop"}),Object.freeze({family:"ara",channel:"staging",applicationId:"so.ara.desktop.staging"}),Object.freeze({family:"reason",channel:"stable",applicationId:"com.reasonmachines.desktop"}),Object.freeze({family:"reason",channel:"staging",applicationId:"com.reasonmachines.desktop.staging"})];var Z="REASON_DESKTOP_RUNTIME",q="REASON_DESKTOP_RUNTIME_CHANNEL",Q="REASON_DESKTOP_RUNTIME_INSTANCE_ID",ee="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",We={[Z]:"ARA_DESKTOP_RUNTIME",[q]:"ARA_DESKTOP_RUNTIME_CHANNEL",[Q]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[ee]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function x(r){if(r===void 0)return;if(!/^[a-f0-9]{64}$/.test(r))throw Error("Invalid desktop workspace scope.");return r}import{chmodSync as h,existsSync as g,mkdirSync as S,readFileSync as N,realpathSync as te,renameSync as ne,unlinkSync as I,writeFileSync as k}from"fs";import{createPrivateKey as ie,createPublicKey as re,generateKeyPairSync as oe,randomUUID as ae,sign as se}from"crypto";import{createRequire as ce}from"module";import{homedir as le,platform as T}from"os";import{dirname as de,join as f}from"path";var O=1,ue=16384,y=65536,pe=128,ge=128,U=65536;class l extends Error{code;nativeStatus;constructor(r,e){super(`Reason Device proof boundary failed (${r}).${e===void 0?"":` Native status: ${e}.`}`);this.code=r;this.nativeStatus=e;this.name="LocalCredentialBoundaryError"}}var D=null;function F(){if(!D)try{D=ce(import.meta.url)("bun:ffi")}catch{throw new l("native_boundary_unavailable")}return D}function fe(r){if(typeof r!=="string")return null;try{let e=new URL(r);if(e.protocol!=="https:"&&e.hostname!=="127.0.0.1"&&e.hostname!=="localhost"&&e.hostname!=="[::1]"&&e.hostname!=="::1")return null;return e.origin}catch{return null}}function ye(r){if(!r||typeof r!=="object"||Array.isArray(r))throw new l("invalid_credential_record");let e=r,o=fe(e.apiOrigin);if(e.version!==O||!o||typeof e.orgId!=="string"||e.orgId.length<1||e.orgId.length>160||typeof e.deviceId!=="string"||e.deviceId.length<1||e.deviceId.length>160||typeof e.credential!=="string"||!/^(?:reason|ara)_dev_/.test(e.credential)||e.credential.length>4096)throw new l("invalid_credential_record");return{version:O,apiOrigin:o,orgId:e.orgId,deviceId:e.deviceId,credential:e.credential}}function Gt(r=process.execPath){let e=r;try{e=te(r)}catch{}return Lo(de(e))}function u(r){return F().ptr(r)}function ve(r){if(!g(r))throw new l("native_boundary_unavailable");let{dlopen:e,FFIType:o}=F();try{return e(r,{ara_device_configure_scope:{args:[o.ptr,o.u64],returns:o.i32},ara_device_key_load_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_create_fresh_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_sign:{args:[o.ptr,o.u64,o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_is_non_extractable:{args:[o.ptr],returns:o.i32},ara_device_key_delete:{args:[o.ptr],returns:o.i32},ara_device_binding_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_binding_create:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_update:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_delete:{args:[o.ptr],returns:o.i32},ara_device_keychain_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_keychain_delete:{args:[o.ptr],returns:o.i32}})}catch(c){if(c instanceof l)throw c;throw new l("native_boundary_unavailable")}}function K(r){return Buffer.from(r).toString("base64url")}function v(r){if(typeof r!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(r))return!1;try{let e=Buffer.from(r,"base64url");return e.byteLength===65&&e[0]===4}catch{return!1}}function M(r){if(r.byteLength<8||r.byteLength>72||r[0]!==48)return!1;let e=r[1];return e!==void 0&&e<128&&e+2===r.byteLength}class Ke{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(r=Gt(),e=T(),o){this.libraryPath=r;this.runtimePlatform=e;this.workspaceScope=o;x(o)}symbols(){if(this.runtimePlatform!=="darwin")throw new l("unsupported_platform");this.library??=ve(this.libraryPath);let r=new TextEncoder().encode(this.workspaceScope??""),e=this.library.symbols.ara_device_configure_scope(u(r.length?r:new Uint8Array(1)),BigInt(r.length));if(e!==0)throw new l("native_boundary_unavailable",e);return this.library.symbols}publicKey(r){let e=new Uint8Array(pe),o=new BigUint64Array(1),c=r==="load"?this.symbols().ara_device_key_load_public(u(e),BigInt(e.byteLength),u(o)):this.symbols().ara_device_key_create_fresh_public(u(e),BigInt(e.byteLength),u(o));if(c!==0)throw new l(r==="load"?"proof_key_read_failed":"proof_key_generation_failed",c);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d!==65)throw new l("invalid_public_key");let p=K(e.subarray(0,d));if(!v(p))throw new l("invalid_public_key");return p}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(r){if(r.byteLength<1||r.byteLength>U)throw new l("proof_sign_failed");let e=new Uint8Array(ge),o=new BigUint64Array(1),c=this.symbols().ara_device_key_sign(u(r),BigInt(r.byteLength),u(e),BigInt(e.byteLength),u(o));if(c!==0)throw new l("proof_sign_failed",c);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d<1||d>e.byteLength)throw new l("invalid_signature");let p=e.subarray(0,d);if(!M(p))throw new l("invalid_signature");return K(p)}privateKeyIsNonExtractable(){let r=new Uint8Array(1),e=this.symbols().ara_device_key_is_non_extractable(u(r));if(e!==0||r[0]!==1)throw new l("proof_key_read_failed",e);return!0}deleteKey(){let r=new Uint8Array(1),e=this.symbols().ara_device_key_delete(u(r));if(e!==0)throw new l("proof_key_delete_failed",e);return r[0]===1}loadBinding(){let r=new Uint8Array(y),e=new BigUint64Array(1),o=this.symbols().ara_device_binding_read(u(r),BigInt(r.byteLength),u(e));if(o===1)return null;if(o!==0)throw new l("binding_read_failed",o);let c=Number(e[0]);if(!Number.isSafeInteger(c)||c<1||c>r.byteLength)throw new l("invalid_binding");return r.slice(0,c)}createBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");let e=this.symbols().ara_device_binding_create(u(r),BigInt(r.byteLength));if(e!==0)throw new l("binding_create_failed",e)}updateBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");let e=this.symbols().ara_device_binding_update(u(r),BigInt(r.byteLength));if(e!==0)throw new l("binding_update_failed",e)}deleteBinding(){let r=new Uint8Array(1),e=this.symbols().ara_device_binding_delete(u(r));if(e!==0)throw new l("binding_delete_failed",e);return r[0]===1}loadLegacyCredential(){let r=new Uint8Array(ue),e=new BigUint64Array(1),o=this.symbols().ara_device_keychain_read(u(r),BigInt(r.byteLength),u(e));if(o===1)return null;if(o!==0)throw new l("legacy_credential_read_failed",o);let c=Number(e[0]);if(!Number.isSafeInteger(c)||c<1||c>r.byteLength)throw new l("invalid_credential_record");try{let d=new TextDecoder("utf-8",{fatal:!0}).decode(r.subarray(0,c));return ye(JSON.parse(d))}catch(d){if(d instanceof l)throw d;throw new l("invalid_credential_record")}}deleteLegacyCredential(){let r=new Uint8Array(1),e=this.symbols().ara_device_keychain_delete(u(r));if(e!==0)throw new l("legacy_credential_delete_failed",e);return r[0]===1}}function C(r){let e=r.export({format:"jwk"});if(e.crv!=="P-256"||typeof e.x!=="string"||typeof e.y!=="string")throw new l("invalid_public_key");let o=Buffer.from(e.x,"base64url"),c=Buffer.from(e.y,"base64url");if(o.byteLength!==32||c.byteLength!==32)throw new l("invalid_public_key");let d=Buffer.concat([Buffer.of(4),o,c]).toString("base64url");if(!v(d))throw new l("invalid_public_key");return d}function _e(){let r=process.env.XDG_CONFIG_HOME?.trim()||f(le(),".config");yt(r);let e=f(r,"ara");return Zr(e)?e:f(r,"reason")}class Lr{directory;constructor(r=_e()){this.directory=r}keyPath(){return f(this.directory,"local-device.key")}bindingPath(){return f(this.directory,"local-device.binding")}loadPrivateKeyObject(){let r=this.keyPath();if(!g(r))throw new l("proof_key_read_failed");try{let e=N(r,"utf8");return ie({key:e,format:"pem"})}catch{throw new l("proof_key_read_failed")}}loadPublicKey(){let r=this.loadPrivateKeyObject(),e=re(r);return C(e)}createFreshPublicKey(){S(this.directory,{recursive:!0,mode:448});let{privateKey:r,publicKey:e}=oe("ec",{namedCurve:"P-256"}),o=r.export({type:"pkcs8",format:"pem"}),c=this.keyPath();return k(c,o,{mode:384}),h(c,384),C(e)}sign(r){if(r.byteLength<1||r.byteLength>U)throw new l("proof_sign_failed");let e=this.loadPrivateKeyObject(),o;try{o=se("sha256",r,e)}catch{throw new l("proof_sign_failed")}if(!M(o))throw new l("invalid_signature");return o.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let r=this.keyPath();if(!g(r))return!1;return I(r),!0}loadBinding(){let r=this.bindingPath();if(!g(r))return null;try{return new Uint8Array(N(r))}catch{return null}}createBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");S(this.directory,{recursive:!0,mode:448});let e=this.bindingPath();if(g(e))throw new l("binding_create_failed");k(e,r,{mode:384}),h(e,384)}updateBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");S(this.directory,{recursive:!0,mode:448});let e=this.bindingPath();if(!g(e))throw new l("binding_update_failed");let o=`${e}.${ae()}`;try{k(o,r,{mode:384,flag:"wx"}),h(o,384),ne(o,e)}finally{if(g(o))I(o)}}deleteBinding(){let r=this.bindingPath();if(!g(r))return!1;return I(r),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function V(){return T()==="darwin"?new Ke:new Lr}var b=t().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),B=i({id:b,kind:n("permission_denied"),operation:s(["bash","read","write","edit"]),provenance:s(["sandbox_policy","os_permission_unknown"]),occurredAt:t().datetime(),expiresAt:t().datetime(),sessionId:b,deviceId:b,organizationId:b}).strict();var A=4;var P="macos-keychain-p256-v1",Pe=1,Ee=`ARA-DEVICE-BINDING-V1
3
+ `;function Re(r){return r===void 0||typeof r==="number"&&Number.isInteger(r)&&r>=1&&r<=4}function G(r,e=Date.now()){let o=B.safeParse(r);if(!o.success)return!1;let c=o.data,d=typeof c.occurredAt==="string"?Date.parse(c.occurredAt):NaN,p=typeof c.expiresAt==="string"?Date.parse(c.expiresAt):NaN;return c.kind==="permission_denied"&&["bash","read","write","edit"].includes(c.operation)&&["sandbox_policy","os_permission_unknown"].includes(c.provenance)&&Number.isFinite(d)&&d<=e&&p>e&&p>d&&p-d<=600000}function Kt(r,e,o=Date.now()){if(!r||!e||r.state!=="connected"||r.deviceId!==e.deviceId)return null;let c=Date.parse(r.lastHeartbeatAt??""),d=r.permissionRecovery;if(!(o-c>=0&&o-c<30000)||!G(d,o)||d.deviceId!==e.deviceId||d.organizationId!==e.orgId)return null;try{process.kill(r.pid,0)}catch{return null}return d}function H(r={},e=a()){let o=_({env:{...process.env,...r}}),c=r.XDG_CONFIG_HOME?.trim()||m(e,".config");return ke(c,...o==="staging"?["staging"]:[])}function $r(r={},e=a()){return m(H(r,e),"local-device.json")}function xe(r={},e=a()){return m(H(r,e),"local-daemon.json")}function Ne(r,e){Se(w(r),{recursive:!0,mode:448}),L(w(r),448);let o=`${r}.${process.pid}.${me()}.tmp`;try{we(o,`${JSON.stringify(e,null,2)}
4
+ `,{mode:384,flag:"wx"}),L(o,384),De(o,r),L(r,384)}finally{if(z(o))Le(o)}return r}function E(r){if(!z(r))return null;try{return JSON.parse(Ie(r,"utf8"))}catch{return null}}function Oe(r){if(!Array.isArray(r))return null;let e=[];for(let o of r){if(!o||typeof o!=="object")return null;let c=o;if(typeof c.id!=="string"||typeof c.label!=="string"||typeof c.path!=="string"||typeof c.pathFingerprint!=="string"||!c.permissions||typeof c.permissions.read!=="boolean"||typeof c.permissions.write!=="boolean"||typeof c.permissions.execute!=="boolean"||typeof c.permissions.discover_environment!=="boolean"||typeof c.permissions.expose_mcp!=="boolean")return null;e.push({id:c.id,label:c.label,path:c.path,pathFingerprint:c.pathFingerprint,permissions:c.permissions})}return e}function J(r,e,o=[]){let c=Object.keys(r);return e.every((d)=>Object.hasOwn(r,d))&&c.every((d)=>e.includes(d)||o.includes(d))}function Ce(r){if(typeof r!=="string")return null;try{let e=new URL(r);if(e.protocol!=="https:"&&e.hostname!=="127.0.0.1"&&e.hostname!=="localhost")return null;return e.origin}catch{return null}}function Y(r){if(!r||typeof r!=="object"||Array.isArray(r))return null;let e=r,o=Oe(e.roots),c=Ce(e.apiOrigin);if(!c||typeof e.orgId!=="string"||typeof e.deviceId!=="string"||typeof e.displayName!=="string"||typeof e.registeredAt!=="string"||!Re(e.handsSlots)||e.worker!==void 0&&(!e.worker||!/^[a-f0-9]{64}$/.test(e.worker.configDigest)||!["persistent","ephemeral"].includes(e.worker.lifetime)||!Number.isFinite(Date.parse(e.worker.expiresAt)))||!o)return null;return{apiOrigin:c,orgId:e.orgId,deviceId:e.deviceId,displayName:e.displayName,registeredAt:e.registeredAt,...e.handsSlots!==void 0?{handsSlots:e.handsSlots}:{},...e.worker!==void 0?{worker:e.worker}:{},roots:o}}function Te(r){return{version:A,apiOrigin:r.apiOrigin,orgId:r.orgId,deviceId:r.deviceId,devicePublicKey:r.devicePublicKey,displayName:r.displayName,registeredAt:r.registeredAt,...r.handsSlots!==void 0?{handsSlots:r.handsSlots}:{},...r.worker!==void 0?{worker:r.worker}:{},roots:r.roots.map((e)=>({id:e.id,label:e.label,path:e.path,pathFingerprint:e.pathFingerprint,permissions:{read:e.permissions.read,write:e.permissions.write,execute:e.permissions.execute,discover_environment:e.permissions.discover_environment,expose_mcp:e.permissions.expose_mcp}})),credentialStorage:P}}function X(r){if(!r||typeof r!=="object"||Array.isArray(r))return null;let e=r;if(!J(e,["version","apiOrigin","orgId","deviceId","devicePublicKey","displayName","registeredAt","roots","credentialStorage"],["handsSlots","worker"]))return null;let o=Y(e);if(!o||e.version!==A||e.credentialStorage!==P||!v(e.devicePublicKey))return null;return{version:A,...o,devicePublicKey:e.devicePublicKey,credentialStorage:P}}function Ue(r){return new TextEncoder().encode(`${Ee}${JSON.stringify(Te(r))}`)}function Fe(r){let e=Buffer.from(r,"base64url");return be({format:"jwk",key:{kty:"EC",crv:"P-256",x:e.subarray(1,33).toString("base64url"),y:e.subarray(33,65).toString("base64url")}})}function Me(r){let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new l("invalid_binding")}if(!e||typeof e!=="object"||Array.isArray(e))throw new l("invalid_binding");let o=e;if(!J(o,["version","state","signature"])||o.version!==Pe||typeof o.signature!=="string"||!/^[A-Za-z0-9_-]{10,128}$/.test(o.signature))throw new l("invalid_binding");let c=X(o.state);if(!c)throw new l("invalid_binding");let d=!1;try{d=he("sha256",Ue(c),Fe(c.devicePublicKey),Buffer.from(o.signature,"base64url"))}catch{d=!1}if(!d)throw new l("invalid_binding");return c}function je(r){let{credentialStorage:e,...o}=r;return o}function Mr(r=$r(),e={}){let o=E(r),c=e.proofStore??e.credentialStore??V(),d=c.loadBinding();if(!d){if(o&&typeof o==="object"&&!Array.isArray(o)&&Ve(o))return null;if(o!==null)throw new l("invalid_binding");return null}let p=Me(d),W=c.loadPublicKey();if(c.privateKeyIsNonExtractable(),W!==p.devicePublicKey)throw new l("invalid_public_key");let R=X(o);if(e.repair!==!1&&(!R||JSON.stringify(R)!==JSON.stringify(p)))Ne(r,p);return je(p)}function Ve(r){let e=r,o=Y(r);if(!o)return null;if(e.version===2){if(typeof e.deviceCredential!=="string"||!/^(?:reason|ara)_dev_/.test(e.deviceCredential)||e.deviceCredential.length>4096)return null;return{state:o,credentialSource:"plaintext-v2"}}if(e.version!==3||e.credentialStorage!=="macos-keychain-v1"||"deviceCredential"in e)return null;return{state:o,credentialSource:"keychain-v3"}}function ht(r=xe()){let e=E(r);if(!e||typeof e!=="object")return null;let o=e;if(o.version!==1||typeof o.pid!=="number"||!Number.isInteger(o.pid)||!["starting","connected","stopped","error"].includes(o.state??"")||typeof o.startedAt!=="string"||o.lastHeartbeatAt!==void 0&&typeof o.lastHeartbeatAt!=="string"||o.lastUsedAt!==void 0&&typeof o.lastUsedAt!=="string"||o.organizationId!==void 0&&typeof o.organizationId!=="string"||o.organizationName!==void 0&&typeof o.organizationName!=="string"||o.organizationSlug!==void 0&&typeof o.organizationSlug!=="string"||o.error!==void 0&&typeof o.error!=="string"||o.reconnectingSince!==void 0&&typeof o.reconnectingSince!=="string"||o.workspace!==void 0&&typeof o.workspace!=="string")return null;if(o.permissionRecovery!==void 0&&!G(o.permissionRecovery))delete o.permissionRecovery;return o}var Jt=1;function Be(r=$r()){return m(w(r),"local-device.proxy.json")}function j(r=Be()){let e=E(r);if(!e||typeof e!=="object"||Array.isArray(e))return null;let o=e;if(o.version!==Jt||typeof o.url!=="string"||o.url.length===0||o.caFile!==void 0&&(typeof o.caFile!=="string"||!Ae(o.caFile)))return null;return{version:Jt,url:o.url,...o.caFile?{caFile:o.caFile}:{}}}
5
+ export{l,Gt,Ke,Lr,Kt,$r,Mr,ht,Jt,j};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{a}from"./vm-hands-entry-lite-haws181e.js";import{readFileSync as c}from"fs";import{isAbsolute as l,normalize as i}from"path";var m="REASON_WORKER_DESKTOP_USER",u=null;function p(t,o){for(let s of o.split(`
2
+ import{a}from"./vm-hands-entry-lite-jvszqt0z.js";import{readFileSync as c}from"fs";import{isAbsolute as l,normalize as i}from"path";var m="REASON_WORKER_DESKTOP_USER",u=null;function p(t,o){for(let s of o.split(`
3
3
  `)){let e=s.split(":");if(e.length<7||Number(e[2])!==t||!/^\d+$/.test(e[2])||!/^\d+$/.test(e[3]))continue;let n=e[5];if(!/^[a-z_][a-z0-9_-]*$/i.test(e[0])||!l(n)||i(n)!==n||n==="/")return null;return{username:e[0],uid:t,gid:Number(e[3]),home:n}}return null}function Gs(t={}){let o="value"in t?t.value:process.env[m];if(u=null,o===void 0||o==="")return null;let s=t.platform??process.platform,e="euid"in t?t.euid:process.geteuid?.(),n=/^[1-9]\d{0,9}$/.test(o)?Number(o):NaN,r=s==="linux"&&e===0&&Number.isSafeInteger(n)?p(n,(t.passwd??(()=>c("/etc/passwd","utf8")))()):null;if(!r||r.gid===0)throw Error("worker_desktop_user_invalid");return u=r,r}function K(){return u}function Ln(){return u?.home??a()}
4
4
  export{Gs,K,Ln};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- var tr={name:"github-native-engineer-device-worker-production",version:"0.2.525",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@agentclientprotocol/sdk":"1.9.0","@anthropic-ai/sandbox-runtime":"^0.0.80","@earendil-works/pi-tui":"1.0.0","@reason/runtime-distribution":"workspace:*",diff:"8.0.4","open-browser-use-sdk":"0.1.42","playwright-core":"1.60.0",toml:"4.2.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"}};
2
+ var tr={name:"github-native-engineer-device-worker-production",version:"0.2.528",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@agentclientprotocol/sdk":"1.9.0","@anthropic-ai/sandbox-runtime":"^0.0.80","@earendil-works/pi-tui":"1.0.0","@reason/runtime-distribution":"workspace:*",diff:"8.0.4","open-browser-use-sdk":"0.1.42","playwright-core":"1.60.0",toml:"4.2.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
3
  export{tr};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{A}from"./vm-hands-entry-lite-1kt82jes.js";import{randomUUID as m}from"crypto";import{closeSync as k,constants as c,fstatSync as u,lstatSync as s,mkdirSync as l,openSync as E,readFileSync as S,realpathSync as a,renameSync as g,unlinkSync as p,writeFileSync as O}from"fs";import{dirname as w,resolve as _}from"path";var d=65536;function f(r){try{return s(r),!0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return!1;throw o}}function v(r,o=!1){if(!f(r)){if(!o)throw Error("worker_state_missing");y(r),l(r,{mode:448})}let e=s(r);if(!e.isDirectory()||e.isSymbolicLink()||!A(e)||a(r)!==_(r))throw Error("worker_state_directory_not_private_or_canonical")}function y(r){let o=w(r);if(!f(o))y(o),l(o,{mode:448});if(a(o)!==_(o))throw Error("worker_parent_not_canonical")}function h(r,o=d){let e=E(r,c.O_RDONLY|c.O_NOFOLLOW);try{let n=u(e);if(!n.isFile()||n.nlink!==1||!A(n)||n.size>o)throw Error("worker_file_not_private");return S(e,"utf8")}finally{k(e)}}function fo(r,o,e=d){let n=JSON.stringify(o);if(n===void 0)throw Error("worker_file_invalid");let t=n+`
2
+ import{A}from"./vm-hands-entry-lite-b6gsggvp.js";import{randomUUID as m}from"crypto";import{closeSync as k,constants as c,fstatSync as u,lstatSync as s,mkdirSync as l,openSync as E,readFileSync as S,realpathSync as a,renameSync as g,unlinkSync as p,writeFileSync as O}from"fs";import{dirname as w,resolve as _}from"path";var d=65536;function f(r){try{return s(r),!0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return!1;throw o}}function v(r,o=!1){if(!f(r)){if(!o)throw Error("worker_state_missing");y(r),l(r,{mode:448})}let e=s(r);if(!e.isDirectory()||e.isSymbolicLink()||!A(e)||a(r)!==_(r))throw Error("worker_state_directory_not_private_or_canonical")}function y(r){let o=w(r);if(!f(o))y(o),l(o,{mode:448});if(a(o)!==_(o))throw Error("worker_parent_not_canonical")}function h(r,o=d){let e=E(r,c.O_RDONLY|c.O_NOFOLLOW);try{let n=u(e);if(!n.isFile()||n.nlink!==1||!A(n)||n.size>o)throw Error("worker_file_not_private");return S(e,"utf8")}finally{k(e)}}function mo(r,o,e=d){let n=JSON.stringify(o);if(n===void 0)throw Error("worker_file_invalid");let t=n+`
3
3
  `;if(Buffer.byteLength(t,"utf8")>e)throw Error("worker_file_too_large");if(v(w(r)),f(r))h(r,e);let i=`${r}.${m()}`;try{O(i,t,{mode:384,flag:"wx"}),g(i,r)}finally{if(f(i))p(i)}}
4
- export{f,v,h,fo};
4
+ export{f,v,h,mo};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{H}from"./vm-hands-entry-lite-39qv4sqt.js";var To=32;var Oo="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",Io=262144;var P=2,Br=33554432,Fr=200000,zn=4000000,ft=240000;var qn=2000;var jr=16384,Je=32768,Se=128,Wn=64,Ze=2097152,Xt=1,ne=16384,Xe=32768,Vn=8388608,Ee=1000,Yt=2500,Ur=2000,Qt=Yt+Ur,R=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/,h=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Hr={text_only:4430,invalid_json:4431,invalid_cancel_request:4432,invalid_sdk_response:4433,claim_required:4434,invalid_claim:4435,executor_mismatch:4436,stale_generation:4437,fence_conflict:4438,frame_too_large:4439,result_too_large:4440,progress_too_large:4441,terminal_cleanup_started:4442,job_journal_unavailable:4443},I=new Map(Object.entries(Hr).map(([t,n])=>[n,t]));var y=["cancelled","command_failed","duplicate_request_id","duplicate_result_evicted","invalid_repl_response","invalid_request","process_group_cleanup_unconfirmed","repl_failed","result_too_large","repl_response_too_large","repl_transport_failed","request_ledger_full","request_journal_unavailable","request_outcome_uncertain","maintenance_held","request_not_found","resume_digest_mismatch","spawn_failed","stale_generation","timeout"],k=new Set(y),Gn=16384,w=["maintenance_held","invalid_job_request","jobs_disabled","job_not_found","job_conflict","job_capacity","job_journal_unavailable","job_not_running","job_lease_expired","job_input_sequence","job_input_backpressure","stale_generation","pty_unsupported","job_mode_mismatch"];class r extends Error{code;constructor(t){super(t);this.name="HandsProtocolError",this.code=t}}function m(t){return new TextEncoder().encode(t).byteLength}function a(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function i(t,n){let e=new Set(n);return Object.keys(t).every((s)=>e.has(s))}function ae(t){return typeof t==="string"&&R.test(t)}function U(t){return Number.isSafeInteger(t)&&Number(t)>=1}function N(t){return typeof t==="string"&&h.test(t)}function ce(t){return typeof t==="string"&&t.startsWith("pty-")&&N(t.slice(4))}function p(t){return[t.cols,t.rows].every((n)=>Number.isSafeInteger(n)&&Number(n)>=1&&Number(n)<=Ee)}function _(t){if(typeof t!=="string"||t.length>Math.ceil(ne/3)*4||t.length%4!==0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return-1;let n=t.endsWith("==")?2:t.endsWith("=")?1:0;if(n&&"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(t[t.length-n-1])&(n===2?15:3))return-1;let s=t.length/4*3-n;return s<=ne?s:-1}function l(t){if(m(t)>Br)throw new r("frame_too_large");try{return JSON.parse(t)}catch{throw new r("invalid_json")}}function zr(t){let n=l(t);if(!a(n)||!i(n,["type","version","generation","id","jobId","action","input"])||n.type!=="job"||n.version!==P||!U(n.generation)||!ae(n.id)||!ae(n.jobId)||!a(n.input))throw new r("invalid_job_request");let e=n.input,s=Number.isSafeInteger(e.leaseExpiresAtMs)&&Number(e.leaseExpiresAtMs)>0,d=Number.isSafeInteger(e.sequence)&&Number(e.sequence)>=1;if(!(n.action==="start"?e.mode==="pty"?i(e,["mode","cols","rows","leaseExpiresAtMs"])&&ce(n.jobId)&&p(e)&&s:i(e,["script","leaseExpiresAtMs"])&&typeof e.script==="string"&&e.script.length<=Fr&&s:n.action==="inspect"?i(e,["after"])&&Number.isSafeInteger(e.after)&&Number(e.after)>=0:n.action==="input"?"dataBase64"in e?i(e,["sequence","dataBase64"])&&ce(n.jobId)&&d&&_(e.dataBase64)>0:i(e,["sequence","data","eof"])&&d&&typeof e.data==="string"&&e.data.length<=jr&&typeof e.eof==="boolean":n.action==="resize"?i(e,["sequence","cols","rows"])&&ce(n.jobId)&&d&&p(e):n.action==="renew"?i(e,["leaseExpiresAtMs"])&&s:n.action==="cancel"&&i(e,[])))throw new r("invalid_job_request");return n}function qr(t){let n=l(t);if(!a(n)||!i(n,["type","version","generation","id","ok","job","error"])||n.type!=="job_result"||n.version!==P||!U(n.generation)||!ae(n.id))throw new r("invalid_job_result");if(n.ok===!1&&n.job===void 0&&typeof n.error==="string"&&w.some((o)=>o===n.error))return n;let e=n.job;if(n.ok!==!0||n.error!==void 0||!a(e)||!i(e,["jobId","state","startedAtMs","finishedAtMs","leaseExpiresAtMs","exitCode","inputSequence","output","firstCursor","nextCursor","truncated","process","environmentRevision","environmentSnapshotId","pty"])||!ae(e.jobId)||!["starting","running","exited","cancelled","expired","uncertain"].includes(String(e.state))||!Number.isSafeInteger(e.startedAtMs)||Number(e.startedAtMs)<1||!Number.isSafeInteger(e.leaseExpiresAtMs)||Number(e.leaseExpiresAtMs)<1||e.finishedAtMs!==null&&(!Number.isSafeInteger(e.finishedAtMs)||Number(e.finishedAtMs)<Number(e.startedAtMs))||e.exitCode!==null&&(!Number.isSafeInteger(e.exitCode)||Number(e.exitCode)<0||Number(e.exitCode)>255)||!Number.isSafeInteger(e.inputSequence)||Number(e.inputSequence)<0||!Number.isSafeInteger(e.firstCursor)||Number(e.firstCursor)<1||!Number.isSafeInteger(e.nextCursor)||Number(e.nextCursor)<Number(e.firstCursor)-1||typeof e.truncated!=="boolean"||!Array.isArray(e.output)||e.output.length>Se)throw new r("invalid_job_result");if(e.environmentRevision===void 0!==(e.environmentSnapshotId===void 0)||e.environmentRevision!==void 0&&(!Number.isSafeInteger(e.environmentRevision)||Number(e.environmentRevision)<1||!N(e.environmentSnapshotId)))throw new r("invalid_job_result");let s=Number(e.firstCursor)-1,d=0;for(let o of e.output){if(!a(o)||!i(o,["cursor","stream","text"])||!Number.isSafeInteger(o.cursor)||Number(o.cursor)<=s||Number(o.cursor)>Number(e.nextCursor)||!["stdout","stderr"].includes(String(o.stream))||typeof o.text!=="string")throw new r("invalid_job_result");d+=o.text.length,s=Number(o.cursor)}if(d>Je)throw new r("invalid_job_result");let c=e.state==="starting"||e.state==="running";if(c&&(e.finishedAtMs!==null||e.exitCode!==null)||!c&&e.finishedAtMs===null||e.state==="uncertain"&&e.exitCode!==null||e.state==="exited"&&e.exitCode===null||e.state==="cancelled"&&e.exitCode!==130||e.state==="expired"&&e.exitCode!==124)throw new r("invalid_job_result");if(e.process!==void 0){let o=e.process;if(!a(o)||!i(o,["pid","processGroupId","executorLaunchId"])||!Number.isSafeInteger(o.pid)||Number(o.pid)<1||o.processGroupId!==o.pid||!N(o.executorLaunchId)||!["starting","running"].includes(String(e.state)))throw new r("invalid_job_result")}if(e.pty!==void 0){let o=e.pty;if(!a(o)||!i(o,["version","cols","rows","output","cleanup"])||o.version!==Xt||!ce(e.jobId)||!p(o)||e.output.length!==0||!Array.isArray(o.output)||o.output.length>Se||(c?o.cleanup!=="pending":e.state==="uncertain"?o.cleanup!=="unconfirmed":o.cleanup!=="confirmed")||e.state==="running"&&(e.process===void 0||e.environmentRevision===void 0))throw new r("invalid_job_result");let g=Number(e.firstCursor)-1,b=0;for(let u of o.output){if(!a(u)||!i(u,["cursor","dataBase64"])||!Number.isSafeInteger(u.cursor)||Number(u.cursor)<=g||Number(u.cursor)>Number(e.nextCursor))throw new r("invalid_job_result");let f=_(u.dataBase64);if(f<=0||(b+=f)>Xe)throw new r("invalid_job_result");g=Number(u.cursor)}}return n}function Kn(t){if(m(t)>Ze)throw new r("frame_too_large");let n=l(t);if(!a(n)||!i(n,["version","sessionId","operationId","runId","deviceId","rootId","workspace","binding","targetRevision","rootGrantRevision","generation","fenceId","executorLaunchId","job"])||n.version!==Xt||![n.sessionId,n.operationId,n.runId].every(ae)||![n.deviceId,n.rootId,n.fenceId,n.executorLaunchId].every(N)||!U(n.generation)||!Number.isSafeInteger(n.rootGrantRevision)||Number(n.rootGrantRevision)<1||!["workspace_source","mcp_control"].includes(String(n.binding))||!Number.isSafeInteger(n.targetRevision)||Number(n.targetRevision)<0||n.binding==="workspace_source"&&n.targetRevision!==0||!a(n.workspace))throw new r("invalid_pty_receipt");if(!H(n.workspace))throw new r("invalid_pty_receipt");let e=qr(JSON.stringify({type:"job_result",version:P,generation:n.generation,id:n.operationId,ok:!0,job:n.job}));if(!e.ok||!e.job.pty||e.job.pty.output.length!==0||e.job.process&&e.job.process.executorLaunchId!==n.executorLaunchId)throw new r("invalid_pty_receipt");return n}export{To,Oo,Io,P,Br,Fr,zn,ft,qn,jr,Je,Se,Wn,Ze,Xt,ne,Xe,Vn,Ee,Yt,Ur,Qt,Hr,Gn,ae,U,N,ce,zr,qr,Kn};
2
+ import{U}from"./vm-hands-entry-lite-a0g6c3wr.js";var Io=32;var Do="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",Oo=262144;var P=2,Br=33554432,Fr=200000,zn=4000000,ft=240000;var qn=2000;var jr=16384,Je=32768,Se=128,Wn=64,Xe=2097152,Yt=1,ne=16384,Ye=32768,Vn=8388608,Ee=1000,Zt=2500,Hr=2000,Qt=Zt+Hr,R=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/,h=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Ur={text_only:4430,invalid_json:4431,invalid_cancel_request:4432,invalid_sdk_response:4433,claim_required:4434,invalid_claim:4435,executor_mismatch:4436,stale_generation:4437,fence_conflict:4438,frame_too_large:4439,result_too_large:4440,progress_too_large:4441,terminal_cleanup_started:4442,job_journal_unavailable:4443},I=new Map(Object.entries(Ur).map(([t,n])=>[n,t]));var y=["cancelled","command_failed","duplicate_request_id","duplicate_result_evicted","invalid_repl_response","invalid_request","process_group_cleanup_unconfirmed","repl_failed","result_too_large","repl_response_too_large","repl_transport_failed","request_ledger_full","request_journal_unavailable","request_outcome_uncertain","maintenance_held","request_not_found","resume_digest_mismatch","spawn_failed","stale_generation","timeout"],k=new Set(y),Gn=16384,w=["maintenance_held","invalid_job_request","jobs_disabled","job_not_found","job_conflict","job_capacity","job_journal_unavailable","job_not_running","job_lease_expired","job_input_sequence","job_input_backpressure","stale_generation","pty_unsupported","job_mode_mismatch"];class r extends Error{code;constructor(t){super(t);this.name="HandsProtocolError",this.code=t}}function m(t){return new TextEncoder().encode(t).byteLength}function a(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function i(t,n){let e=new Set(n);return Object.keys(t).every((s)=>e.has(s))}function ae(t){return typeof t==="string"&&R.test(t)}function H(t){return Number.isSafeInteger(t)&&Number(t)>=1}function N(t){return typeof t==="string"&&h.test(t)}function ce(t){return typeof t==="string"&&t.startsWith("pty-")&&N(t.slice(4))}function p(t){return[t.cols,t.rows].every((n)=>Number.isSafeInteger(n)&&Number(n)>=1&&Number(n)<=Ee)}function _(t){if(typeof t!=="string"||t.length>Math.ceil(ne/3)*4||t.length%4!==0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return-1;let n=t.endsWith("==")?2:t.endsWith("=")?1:0;if(n&&"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(t[t.length-n-1])&(n===2?15:3))return-1;let s=t.length/4*3-n;return s<=ne?s:-1}function l(t){if(m(t)>Br)throw new r("frame_too_large");try{return JSON.parse(t)}catch{throw new r("invalid_json")}}function zr(t){let n=l(t);if(!a(n)||!i(n,["type","version","generation","id","jobId","action","input"])||n.type!=="job"||n.version!==P||!H(n.generation)||!ae(n.id)||!ae(n.jobId)||!a(n.input))throw new r("invalid_job_request");let e=n.input,s=Number.isSafeInteger(e.leaseExpiresAtMs)&&Number(e.leaseExpiresAtMs)>0,d=Number.isSafeInteger(e.sequence)&&Number(e.sequence)>=1;if(!(n.action==="start"?e.mode==="pty"?i(e,["mode","cols","rows","leaseExpiresAtMs"])&&ce(n.jobId)&&p(e)&&s:i(e,["script","leaseExpiresAtMs"])&&typeof e.script==="string"&&e.script.length<=Fr&&s:n.action==="inspect"?i(e,["after"])&&Number.isSafeInteger(e.after)&&Number(e.after)>=0:n.action==="input"?"dataBase64"in e?i(e,["sequence","dataBase64"])&&ce(n.jobId)&&d&&_(e.dataBase64)>0:i(e,["sequence","data","eof"])&&d&&typeof e.data==="string"&&e.data.length<=jr&&typeof e.eof==="boolean":n.action==="resize"?i(e,["sequence","cols","rows"])&&ce(n.jobId)&&d&&p(e):n.action==="renew"?i(e,["leaseExpiresAtMs"])&&s:n.action==="cancel"&&i(e,[])))throw new r("invalid_job_request");return n}function qr(t){let n=l(t);if(!a(n)||!i(n,["type","version","generation","id","ok","job","error"])||n.type!=="job_result"||n.version!==P||!H(n.generation)||!ae(n.id))throw new r("invalid_job_result");if(n.ok===!1&&n.job===void 0&&typeof n.error==="string"&&w.some((o)=>o===n.error))return n;let e=n.job;if(n.ok!==!0||n.error!==void 0||!a(e)||!i(e,["jobId","state","startedAtMs","finishedAtMs","leaseExpiresAtMs","exitCode","inputSequence","output","firstCursor","nextCursor","truncated","process","environmentRevision","environmentSnapshotId","pty"])||!ae(e.jobId)||!["starting","running","exited","cancelled","expired","uncertain"].includes(String(e.state))||!Number.isSafeInteger(e.startedAtMs)||Number(e.startedAtMs)<1||!Number.isSafeInteger(e.leaseExpiresAtMs)||Number(e.leaseExpiresAtMs)<1||e.finishedAtMs!==null&&(!Number.isSafeInteger(e.finishedAtMs)||Number(e.finishedAtMs)<Number(e.startedAtMs))||e.exitCode!==null&&(!Number.isSafeInteger(e.exitCode)||Number(e.exitCode)<0||Number(e.exitCode)>255)||!Number.isSafeInteger(e.inputSequence)||Number(e.inputSequence)<0||!Number.isSafeInteger(e.firstCursor)||Number(e.firstCursor)<1||!Number.isSafeInteger(e.nextCursor)||Number(e.nextCursor)<Number(e.firstCursor)-1||typeof e.truncated!=="boolean"||!Array.isArray(e.output)||e.output.length>Se)throw new r("invalid_job_result");if(e.environmentRevision===void 0!==(e.environmentSnapshotId===void 0)||e.environmentRevision!==void 0&&(!Number.isSafeInteger(e.environmentRevision)||Number(e.environmentRevision)<1||!N(e.environmentSnapshotId)))throw new r("invalid_job_result");let s=Number(e.firstCursor)-1,d=0;for(let o of e.output){if(!a(o)||!i(o,["cursor","stream","text"])||!Number.isSafeInteger(o.cursor)||Number(o.cursor)<=s||Number(o.cursor)>Number(e.nextCursor)||!["stdout","stderr"].includes(String(o.stream))||typeof o.text!=="string")throw new r("invalid_job_result");d+=o.text.length,s=Number(o.cursor)}if(d>Je)throw new r("invalid_job_result");let c=e.state==="starting"||e.state==="running";if(c&&(e.finishedAtMs!==null||e.exitCode!==null)||!c&&e.finishedAtMs===null||e.state==="uncertain"&&e.exitCode!==null||e.state==="exited"&&e.exitCode===null||e.state==="cancelled"&&e.exitCode!==130||e.state==="expired"&&e.exitCode!==124)throw new r("invalid_job_result");if(e.process!==void 0){let o=e.process;if(!a(o)||!i(o,["pid","processGroupId","executorLaunchId"])||!Number.isSafeInteger(o.pid)||Number(o.pid)<1||o.processGroupId!==o.pid||!N(o.executorLaunchId)||!["starting","running"].includes(String(e.state)))throw new r("invalid_job_result")}if(e.pty!==void 0){let o=e.pty;if(!a(o)||!i(o,["version","cols","rows","output","cleanup"])||o.version!==Yt||!ce(e.jobId)||!p(o)||e.output.length!==0||!Array.isArray(o.output)||o.output.length>Se||(c?o.cleanup!=="pending":e.state==="uncertain"?o.cleanup!=="unconfirmed":o.cleanup!=="confirmed")||e.state==="running"&&(e.process===void 0||e.environmentRevision===void 0))throw new r("invalid_job_result");let g=Number(e.firstCursor)-1,b=0;for(let u of o.output){if(!a(u)||!i(u,["cursor","dataBase64"])||!Number.isSafeInteger(u.cursor)||Number(u.cursor)<=g||Number(u.cursor)>Number(e.nextCursor))throw new r("invalid_job_result");let f=_(u.dataBase64);if(f<=0||(b+=f)>Ye)throw new r("invalid_job_result");g=Number(u.cursor)}}return n}function Kn(t){if(m(t)>Xe)throw new r("frame_too_large");let n=l(t);if(!a(n)||!i(n,["version","sessionId","operationId","runId","deviceId","rootId","workspace","binding","targetRevision","rootGrantRevision","generation","fenceId","executorLaunchId","job"])||n.version!==Yt||![n.sessionId,n.operationId,n.runId].every(ae)||![n.deviceId,n.rootId,n.fenceId,n.executorLaunchId].every(N)||!H(n.generation)||!Number.isSafeInteger(n.rootGrantRevision)||Number(n.rootGrantRevision)<1||!["workspace_source","mcp_control"].includes(String(n.binding))||!Number.isSafeInteger(n.targetRevision)||Number(n.targetRevision)<0||n.binding==="workspace_source"&&n.targetRevision!==0||!a(n.workspace))throw new r("invalid_pty_receipt");if(!U(n.workspace))throw new r("invalid_pty_receipt");let e=qr(JSON.stringify({type:"job_result",version:P,generation:n.generation,id:n.operationId,ok:!0,job:n.job}));if(!e.ok||!e.job.pty||e.job.pty.output.length!==0||e.job.process&&e.job.process.executorLaunchId!==n.executorLaunchId)throw new r("invalid_pty_receipt");return n}export{Io,Do,Oo,P,Br,Fr,zn,ft,qn,jr,Je,Se,Wn,Xe,Yt,ne,Ye,Vn,Ee,Zt,Hr,Qt,Ur,Gn,ae,H,N,ce,zr,qr,Kn};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{H}from"./vm-hands-entry-lite-39qv4sqt.js";import{ft}from"./vm-hands-entry-lite-c0t5xpzh.js";import{Zt}from"./vm-hands-entry-lite-td73npv3.js";import{j}from"./vm-hands-entry-lite-hc11hecd.js";import{ie}from"./vm-hands-entry-lite-haws181e.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{$e}from"./vm-hands-entry-lite-mcjca0ez.js";import{existsSync as D,realpathSync as q,statSync as K}from"fs";import{platform as h}from"os";import{isAbsolute as z,sep as G}from"path";import{existsSync as X}from"fs";import{createRequire as Y}from"module";var k=$e(Zt)(()=>Y(import.meta.url)("bun:ffi"),X);function E(){return process.platform==="win32"&&typeof globalThis.Bun<"u"&&k.available()}function C(e=process.env){return k.defaultShell(e)}function M(e){return k.shellArgs(e)}function N(e){let n=k.spawn({...e,env:e.environment});return n.exited.then(()=>n.close()),{write:(o)=>n.write(o),resize:(o,t)=>n.resize(o,t),kill:()=>n.close(),exited:n.exited}}var Ir=43200000,Vt=ft,Dr=4,Q=/^[A-Za-z0-9._:-]{1,160}$/,V=1000;function I(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function P(e,n){if(typeof e!=="number"||!Number.isFinite(e)||e<=0)return n;return Math.min(V,Math.max(1,Math.floor(e)))}function Z(e,n=Date.now()){let o=["relay_url","session_id","expires_at"],t=new Set([...o,"cols","rows","cwd","workspace"]);if(!I(e)||o.some((b)=>!(b in e))||Object.keys(e).some((b)=>!t.has(b)))throw new r("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:c,session_id:m,expires_at:g}=e;if(typeof c!=="string")throw new r("invalid_pty_request","Reason terminal relay URL is missing.");let d;try{d=new URL(c)}catch{throw new r("invalid_pty_request","Reason terminal relay URL is invalid.")}if(d.protocol!=="wss:"&&d.protocol!=="ws:"||d.username||d.password)throw new r("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof m!=="string"||!Q.test(m))throw new r("invalid_pty_request","Reason terminal session identity is invalid.");let p=typeof g==="string"?Date.parse(g):Number.NaN;if(!Number.isFinite(p)||p<=n)throw new r("invalid_pty_request","Reason terminal session has already expired.");if(e.cwd!==void 0&&typeof e.cwd!=="string")throw new r("invalid_pty_request","Reason terminal working directory is invalid.");let a=e.workspace===void 0?void 0:H(e.workspace);if(a===null||a&&e.cwd!==void 0)throw new r("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:c,session_id:m,expires_at:new Date(Math.min(p,n+Ir)).toISOString(),cols:P(e.cols,80),rows:P(e.rows,24),...e.cwd===void 0?{}:{cwd:e.cwd},...a?{workspace:a}:{}}}function ee(e,n){if(h()==="win32")[e,n]=[e.toLowerCase(),n.toLowerCase()];return n===e||n.startsWith(e+G)}function W(e,n){if(n===void 0)return e;if(!z(n))throw new r("pty_cwd_invalid","Reason terminal working directory must be absolute.");let o;try{o=q(n)}catch{throw new r("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!ee(e,o))throw new r("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!K(o).isDirectory())throw new r("pty_cwd_invalid","Reason terminal working directory is not a directory.");return o}function ds(e=process.env){if(h()==="win32")return C(e);let n=e.SHELL;if(n&&z(n)&&D(n))return n;for(let o of h()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(D(o))return o;return"/bin/sh"}function ne(){let e=globalThis.Bun;if(!e)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");return e.spawn}function Un(){if(h()==="win32")return E();return typeof globalThis.Bun<"u"}var re=(e)=>{if(h()==="win32")try{return N({...e,file:e.shell,args:M(e.shell),environment:{...e.environment,TERM:"xterm-256color"}})}catch{throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}let n=ne()({cmd:[e.shell,"-i","-l"],cwd:e.cwd,env:{...e.environment,TERM:"xterm-256color"},terminal:{cols:e.cols,rows:e.rows,data:(t,c)=>{e.onData(c)}}}),o=n.terminal;if(!o){try{n.kill()}catch{}throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(t)=>o.write(t),resize:(t,c)=>o.resize(t,c),kill:()=>{try{n.kill()}catch{}},exited:n.exited.then((t)=>typeof t==="number"?t:null,()=>null)}},Nr=(e,n)=>n===void 0?new WebSocket(e):new WebSocket(e,{proxy:n}),v=new Set;function te(e){if(v.size>=Dr||v.has(e))return null;v.add(e);let n=!1;return()=>{if(n)return;n=!0,v.delete(e)}}async function Hn(e,n={}){let o=n.now??Date.now,t=Z(e.payload,o()),c=te(e.operationId);if(!c)throw new r("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let m=o(),g,d,p;try{let a=t.workspace?ie(e.root,t.workspace):void 0;g=a?W(D(a.boundary)?q(a.boundary):a.boundary,a.path):W(e.root,t.cwd),d=n.environment??process.env,p=n.shellPath??ds(d)}catch(a){throw c(),a}return await new Promise((a,b)=>{let w=null,i=null,S=!1,x=!1,y=!1,T=null,U=0,B=0,O=[],R=0,A=null,l=(s)=>{if(y)return;if(y=!0,A)clearTimeout(A);e.signal.removeEventListener("abort",L);try{w?.kill()}catch{}try{i?.close(1000,"pty_session_over")}catch{}if(c(),s.kind==="rejected"){b(s.error);return}let u={reason:s.reason,exit_code:T,output_bytes:U,input_bytes:B,duration_ms:Math.max(0,o()-m)};e.emitEvent("pty.stopped",{...u}).catch(()=>{return}),a({...u})},L=()=>{let s=e.signal.reason;l({kind:"rejected",error:s instanceof r?s:new r("cancelled","Reason closed the terminal session.")})};if(e.signal.aborted){L();return}e.signal.addEventListener("abort",L,{once:!0}),A=setTimeout(()=>l({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(t.expires_at)-o()));let F=(s)=>{if(U+=s.byteLength,!S||!i){if(O.push(s),R+=s.byteLength,R>Vt)l({kind:"resolved",reason:"output_backpressure"});return}try{i.send(s)}catch{l({kind:"resolved",reason:"relay_closed"});return}if(i.bufferedAmount>Vt)l({kind:"resolved",reason:"output_backpressure"})};try{w=(n.spawnPty??re)({shell:p,args:["-i","-l"],cwd:g,cols:t.cols,rows:t.rows,environment:d,onData:(s)=>{if(!y)F(s)}})}catch(s){l({kind:"rejected",error:s instanceof r?s:new r("pty_spawn_failed","Reason could not start the terminal shell.")});return}w.exited.then((s)=>{if(y)return;if(T=s,S&&i)try{i.send(JSON.stringify({t:"exit",code:s}))}catch{}l({kind:"resolved",reason:"shell_exited"})});let J=(n.loadProxy??j)()?.url;try{i=(n.connect??Nr)(t.relay_url,J)}catch{l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}i.binaryType="arraybuffer",i.onopen=()=>{if(y||!i)return;S=!0;try{i.send(JSON.stringify({t:"open",cols:t.cols,rows:t.rows}));for(let s of O.splice(0))i.send(s);R=0}catch{l({kind:"resolved",reason:"relay_closed"});return}x=!0,e.emitEvent("pty.ready",{session_id:t.session_id,cols:t.cols,rows:t.rows}).catch(()=>{return})},i.onmessage=(s)=>{if(y||!w)return;let u=s.data;if(typeof u==="string"){let f;try{f=JSON.parse(u)}catch{return}if(!I(f))return;if(f.t==="resize"){try{w.resize(P(f.cols,t.cols),P(f.rows,t.rows))}catch{}return}if(f.t==="close")l({kind:"resolved",reason:"client_closed"});return}let _=u instanceof ArrayBuffer?new Uint8Array(u):ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):null;if(!_||_.byteLength===0)return;B+=_.byteLength;try{w.write(_)}catch{}},i.onclose=()=>{if(y)return;if(!x){l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}l({kind:"resolved",reason:"relay_closed"})},i.onerror=()=>{if(y||x)return;l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
3
- export{Ir,Vt,Dr,ds,Un,Nr,Hn};
2
+ import{U}from"./vm-hands-entry-lite-a0g6c3wr.js";import{ft}from"./vm-hands-entry-lite-hv3dxd5k.js";import{Xt}from"./vm-hands-entry-lite-y9jarm7q.js";import{j}from"./vm-hands-entry-lite-cgddp0y3.js";import{ie}from"./vm-hands-entry-lite-jvszqt0z.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{Me}from"./vm-hands-entry-lite-3gbf905c.js";import{existsSync as D,realpathSync as z,statSync as K}from"fs";import{platform as h}from"os";import{isAbsolute as I,sep as G}from"path";import{existsSync as X}from"fs";import{createRequire as Y}from"module";var k=Me(Xt)(()=>Y(import.meta.url)("bun:ffi"),X);function C(){return process.platform==="win32"&&typeof globalThis.Bun<"u"&&k.available()}function M(e=process.env){return k.defaultShell(e)}function N(e){return k.shellArgs(e)}function W(e){let n=k.spawn({...e,env:e.environment});return n.exited.then(()=>n.close()),{write:(o)=>n.write(o),resize:(o,t)=>n.resize(o,t),kill:()=>n.close(),exited:n.exited}}var Dr=43200000,Vt=ft,Or=4,Q=/^[A-Za-z0-9._:-]{1,160}$/,V=1000;function F(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function P(e,n){if(typeof e!=="number"||!Number.isFinite(e)||e<=0)return n;return Math.min(V,Math.max(1,Math.floor(e)))}function Z(e,n=Date.now()){let o=["relay_url","session_id","expires_at"],t=new Set([...o,"cols","rows","cwd","workspace"]);if(!F(e)||o.some((b)=>!(b in e))||Object.keys(e).some((b)=>!t.has(b)))throw new r("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:c,session_id:m,expires_at:g}=e;if(typeof c!=="string")throw new r("invalid_pty_request","Reason terminal relay URL is missing.");let d;try{d=new URL(c)}catch{throw new r("invalid_pty_request","Reason terminal relay URL is invalid.")}if(d.protocol!=="wss:"&&d.protocol!=="ws:"||d.username||d.password)throw new r("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof m!=="string"||!Q.test(m))throw new r("invalid_pty_request","Reason terminal session identity is invalid.");let p=typeof g==="string"?Date.parse(g):Number.NaN;if(!Number.isFinite(p)||p<=n)throw new r("invalid_pty_request","Reason terminal session has already expired.");if(e.cwd!==void 0&&typeof e.cwd!=="string")throw new r("invalid_pty_request","Reason terminal working directory is invalid.");let a=e.workspace===void 0?void 0:U(e.workspace);if(a===null||a&&e.cwd!==void 0)throw new r("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:c,session_id:m,expires_at:new Date(Math.min(p,n+Dr)).toISOString(),cols:P(e.cols,80),rows:P(e.rows,24),...e.cwd===void 0?{}:{cwd:e.cwd},...a?{workspace:a}:{}}}function ee(e,n){if(h()==="win32")[e,n]=[e.toLowerCase(),n.toLowerCase()];return n===e||n.startsWith(e+G)}function q(e,n){if(n===void 0)return e;if(!I(n))throw new r("pty_cwd_invalid","Reason terminal working directory must be absolute.");let o;try{o=z(n)}catch{throw new r("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!ee(e,o))throw new r("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!K(o).isDirectory())throw new r("pty_cwd_invalid","Reason terminal working directory is not a directory.");return o}function ds(e=process.env){if(h()==="win32")return M(e);let n=e.SHELL;if(n&&I(n)&&D(n))return n;for(let o of h()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(D(o))return o;return"/bin/sh"}function ne(){let e=globalThis.Bun;if(!e)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");return e.spawn}function Hn(){if(h()==="win32")return C();return typeof globalThis.Bun<"u"}var re=(e)=>{if(h()==="win32")try{return W({...e,file:e.shell,args:N(e.shell),environment:{...e.environment,TERM:"xterm-256color"}})}catch{throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}let n=ne()({cmd:[e.shell,"-i","-l"],cwd:e.cwd,env:{...e.environment,TERM:"xterm-256color"},terminal:{cols:e.cols,rows:e.rows,data:(t,c)=>{e.onData(c)}}}),o=n.terminal;if(!o){try{n.kill()}catch{}throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(t)=>o.write(t),resize:(t,c)=>o.resize(t,c),kill:()=>{try{n.kill()}catch{}},exited:n.exited.then((t)=>typeof t==="number"?t:null,()=>null)}},Nr=(e,n)=>n===void 0?new WebSocket(e):new WebSocket(e,{proxy:n}),v=new Set;function te(e){if(v.size>=Or||v.has(e))return null;v.add(e);let n=!1;return()=>{if(n)return;n=!0,v.delete(e)}}async function Un(e,n={}){let o=n.now??Date.now,t=Z(e.payload,o()),c=te(e.operationId);if(!c)throw new r("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let m=o(),g,d,p;try{let a=t.workspace?ie(e.root,t.workspace):void 0;g=a?q(D(a.boundary)?z(a.boundary):a.boundary,a.path):q(e.root,t.cwd),d=n.environment??process.env,p=n.shellPath??ds(d)}catch(a){throw c(),a}return await new Promise((a,b)=>{let w=null,i=null,S=!1,x=!1,y=!1,T=null,B=0,O=0,E=[],R=0,A=null,l=(s)=>{if(y)return;if(y=!0,A)clearTimeout(A);e.signal.removeEventListener("abort",L);try{w?.kill()}catch{}try{i?.close(1000,"pty_session_over")}catch{}if(c(),s.kind==="rejected"){b(s.error);return}let u={reason:s.reason,exit_code:T,output_bytes:B,input_bytes:O,duration_ms:Math.max(0,o()-m)};e.emitEvent("pty.stopped",{...u}).catch(()=>{return}),a({...u})},L=()=>{let s=e.signal.reason;l({kind:"rejected",error:s instanceof r?s:new r("cancelled","Reason closed the terminal session.")})};if(e.signal.aborted){L();return}e.signal.addEventListener("abort",L,{once:!0}),A=setTimeout(()=>l({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(t.expires_at)-o()));let H=(s)=>{if(B+=s.byteLength,!S||!i){if(E.push(s),R+=s.byteLength,R>Vt)l({kind:"resolved",reason:"output_backpressure"});return}try{i.send(s)}catch{l({kind:"resolved",reason:"relay_closed"});return}if(i.bufferedAmount>Vt)l({kind:"resolved",reason:"output_backpressure"})};try{w=(n.spawnPty??re)({shell:p,args:["-i","-l"],cwd:g,cols:t.cols,rows:t.rows,environment:d,onData:(s)=>{if(!y)H(s)}})}catch(s){l({kind:"rejected",error:s instanceof r?s:new r("pty_spawn_failed","Reason could not start the terminal shell.")});return}w.exited.then((s)=>{if(y)return;if(T=s,S&&i)try{i.send(JSON.stringify({t:"exit",code:s}))}catch{}l({kind:"resolved",reason:"shell_exited"})});let J=(n.loadProxy??j)()?.url;try{i=(n.connect??Nr)(t.relay_url,J)}catch{l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}i.binaryType="arraybuffer",i.onopen=()=>{if(y||!i)return;S=!0;try{i.send(JSON.stringify({t:"open",cols:t.cols,rows:t.rows}));for(let s of E.splice(0))i.send(s);R=0}catch{l({kind:"resolved",reason:"relay_closed"});return}x=!0,e.emitEvent("pty.ready",{session_id:t.session_id,cols:t.cols,rows:t.rows}).catch(()=>{return})},i.onmessage=(s)=>{if(y||!w)return;let u=s.data;if(typeof u==="string"){let f;try{f=JSON.parse(u)}catch{return}if(!F(f))return;if(f.t==="resize"){try{w.resize(P(f.cols,t.cols),P(f.rows,t.rows))}catch{}return}if(f.t==="close")l({kind:"resolved",reason:"client_closed"});return}let _=u instanceof ArrayBuffer?new Uint8Array(u):ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):null;if(!_||_.byteLength===0)return;O+=_.byteLength;try{w.write(_)}catch{}},i.onclose=()=>{if(y)return;if(!x){l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}l({kind:"resolved",reason:"relay_closed"})},i.onerror=()=>{if(y||x)return;l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
3
+ export{Dr,Vt,Or,ds,Hn,Nr,Un};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{de,et,O}from"./vm-hands-entry-lite-39qv4sqt.js";import{execFileSync as l}from"child_process";import{existsSync as c,realpathSync as s}from"fs";import{userInfo as f}from"os";import{isAbsolute as u,join as t,normalize as d,parse as p}from"path";function a(){let r=d(f().homedir);if(!u(r)||r===p(r).root)throw Error("Could not resolve the canonical user home.");return r}function Ho(r){return p(r).root===r}var zo=(r)=>`Reason can't work in ${r}, the top of a drive: use a folder inside it, such as a project folder`;function ie(r,n,e=a()){let i=O(n);if(n.kind==="managed"&&n.base){let o=s(e);return{anchor:o,boundary:t(o,n.base),path:t(o,i)}}if(n.kind==="root"&&et(n.path)){let o=s(e);return{anchor:o,boundary:t(o,de),path:t(o,i)}}return{anchor:r,boundary:r,path:t(r,i)}}function nr(r=a()){return t(r,".config")}function qo(){if(process.platform!=="darwin")return null;try{let r=l("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return u(r)?s(r):null}catch{return null}}function Wo(r=a()){let n=t(r,"Library","Application Support","Ara"),e=t(r,"Library","Application Support","Reason");return c(n)&&!c(e)?n:e}
3
- export{a,Ho,zo,ie,nr,qo,Wo};
2
+ import{de,et,I}from"./vm-hands-entry-lite-a0g6c3wr.js";import{execFileSync as l}from"child_process";import{existsSync as c,realpathSync as s}from"fs";import{userInfo as f}from"os";import{isAbsolute as u,join as t,normalize as d,parse as p}from"path";function a(){let r=d(f().homedir);if(!u(r)||r===p(r).root)throw Error("Could not resolve the canonical user home.");return r}function zo(r){return p(r).root===r}var qo=(r)=>`Reason can't work in ${r}, the top of a drive: use a folder inside it, such as a project folder`;function ie(r,n,e=a()){let i=I(n);if(n.kind==="managed"&&n.base){let o=s(e);return{anchor:o,boundary:t(o,n.base),path:t(o,i)}}if(n.kind==="root"&&et(n.path)){let o=s(e);return{anchor:o,boundary:t(o,de),path:t(o,i)}}return{anchor:r,boundary:r,path:t(r,i)}}function nr(r=a()){return t(r,".config")}function Wo(){if(process.platform!=="darwin")return null;try{let r=l("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return u(r)?s(r):null}catch{return null}}function Vo(r=a()){let n=t(r,"Library","Application Support","Ara"),e=t(r,"Library","Application Support","Reason");return c(n)&&!c(e)?n:e}
3
+ export{a,zo,qo,ie,nr,Wo,Vo};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as se,spawn as E}from"child_process";var bo="h264_ws_v1",vo="video",dt=["smooth","sharp","data_saver","balanced"];var So="video_presets";var M=8388608,S=65536,Eo="control",xo="v1",X=200;function Mn(t){if(!t||typeof t!=="object"||Array.isArray(t))return null;let e=t,n=(i)=>typeof i==="string"&&i.length>0&&i.length<=X;if(Object.keys(e).length!==2||!n(e.user_id)||!n(e.name))return null;return{user_id:e.user_id,name:e.name}}var ko="windows",Co="v1",Ao="look",Po="v1",J=["reason","grok"];function $n(t){return typeof t==="string"&&J.includes(t)?t:null}var D=200,Z=(t)=>typeof t==="string"&&dt.includes(t);function Ro(t){if(!t||typeof t!=="object"||Array.isArray(t))return null;let e=t;if(Object.keys(e).length!==2||e.format!=="h264_ws_v1"||!Z(e.preset))return null;return{format:"h264_ws_v1",preset:e.preset}}var o={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23,resize:24};class l extends Error{constructor(t){super(t);this.name="DisplayVideoProtocolError"}}var Q=new TextEncoder,ee=new TextDecoder("utf-8",{fatal:!0});function p(t,e){if(e.byteLength+1>M)throw new l("message_too_large");let n=new Uint8Array(5+e.byteLength),i=new DataView(n.buffer);return i.setUint32(0,e.byteLength+1),i.setUint8(4,t),n.set(e,5),n}function w(t){let e=Q.encode(t);if(e.byteLength>S)throw new l("text_too_large");return e}function _(t,e){if(!Number.isInteger(t)||t<0||t>65535)throw new l(`invalid_${e}`);return t}function te(t){if(!Number.isFinite(t))throw new l("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(t)))}function Wt(t){switch(t.type){case"hello":{let e=w(t.codec),n=new Uint8Array(6+e.byteLength),i=new DataView(n.buffer);return i.setUint16(0,_(t.width,"width")),i.setUint16(2,_(t.height,"height")),i.setUint8(4,Math.max(1,Math.min(240,Math.round(t.fps)))),i.setUint8(5,dt.indexOf(t.preset)),n.set(e,6),p(o.hello,n)}case"frame":{let e=new Uint8Array(13+t.data.byteLength),n=new DataView(e.buffer);return n.setUint8(0,t.key?1:0),n.setUint32(1,t.seq>>>0),n.setBigUint64(5,BigInt(Math.max(0,Math.floor(t.captureMicros)))),e.set(t.data,13),p(o.frame,e)}case"stats":return p(o.stats,w(JSON.stringify(t.stats)));case"pong":case"ping":{let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t.token),p(t.type==="ping"?o.ping:o.pong,e)}case"serverClipboard":return p(o.serverClipboard,w(t.text));case"clientClipboard":return p(o.clientClipboard,w(t.text));case"error":return p(o.error,w(t.code));case"pointer":{let e=new Uint8Array(5),n=new DataView(e.buffer);return n.setUint16(0,_(t.x,"x")),n.setUint16(2,_(t.y,"y")),n.setUint8(4,t.buttons&255),p(o.pointer,e)}case"key":{let e=new Uint8Array(5),n=new DataView(e.buffer);return n.setUint8(0,t.down?1:0),n.setUint32(1,t.keysym>>>0),p(o.key,e)}case"config":return p(o.config,Uint8Array.of(dt.indexOf(t.preset)));case"keyframeRequest":return p(o.keyframeRequest,new Uint8Array(0));case"audioHello":{let e=w(t.codec),n=new Uint8Array(5+e.byteLength),i=new DataView(n.buffer);return i.setUint32(0,t.sampleRate>>>0),i.setUint8(4,t.channels&255),n.set(e,5),p(o.audioHello,n)}case"audio":{let e=new Uint8Array(8+t.data.byteLength);return new DataView(e.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(t.captureMicros)))),e.set(t.data,8),p(o.audio,e)}case"control":return p(o.control,w(JSON.stringify(t.control)));case"windows":{let e=t.bounds.slice(0,D),n=new Uint8Array(e.length*16),i=new DataView(n.buffer);return e.forEach((s,a)=>{[s.x,s.y,s.width,s.height].forEach((c,d)=>i.setInt32(a*16+d*4,te(c)))}),p(o.windows,n)}case"audioEnable":return p(o.audioEnable,Uint8Array.of(t.on?1:0));case"resize":{let e=new Uint8Array(4),n=new DataView(e.buffer);return n.setUint16(0,_(t.width,"width")),n.setUint16(2,_(t.height,"height")),p(o.resize,e)}case"ack":{let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t.seq>>>0),p(o.ack,e)}}}function L(t){let e=dt[t];if(!e)throw new l("invalid_preset");return e}function y(t,e){if(t.byteLength!==e)throw new l("invalid_length")}function x(t){if(t.byteLength>S)throw new l("text_too_large");try{return ee.decode(t)}catch{throw new l("invalid_text")}}function ne(t){let e;try{e=JSON.parse(x(t))}catch{throw new l("invalid_stats")}let n=e;if(!n||typeof n!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((s)=>typeof n[s]!=="number"||!Number.isFinite(n[s])))throw new l("invalid_stats");return{fps:n.fps,kbps:n.kbps,dropped:n.dropped,restarts:n.restarts,queued_bytes:n.queued_bytes}}function re(t){let e;try{e=JSON.parse(x(t))}catch{throw new l("invalid_control")}let n=e;if(!n||typeof n!=="object"||typeof n.you!=="boolean"||typeof n.same_user!=="boolean")throw new l("invalid_control");let i=n.holder===null?null:Mn(n.holder);if(i===null&&n.holder!==null)throw new l("invalid_control");return{holder:i,you:n.you,same_user:n.same_user}}function ie(t,e){let n=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(t){case o.hello:if(e.byteLength<6)throw new l("invalid_length");return{type:"hello",width:n.getUint16(0),height:n.getUint16(2),fps:n.getUint8(4),preset:L(n.getUint8(5)),codec:x(e.subarray(6))};case o.frame:if(e.byteLength<14)throw new l("invalid_length");if(n.getUint8(0)>1)throw new l("invalid_frame_flags");return{type:"frame",key:n.getUint8(0)===1,seq:n.getUint32(1),captureMicros:Number(n.getBigUint64(5)),data:e.subarray(13)};case o.stats:return{type:"stats",stats:ne(e)};case o.ping:case o.pong:return y(e,8),{type:t===o.ping?"ping":"pong",token:n.getFloat64(0)};case o.serverClipboard:return{type:"serverClipboard",text:x(e)};case o.clientClipboard:return{type:"clientClipboard",text:x(e)};case o.error:return{type:"error",code:x(e)};case o.pointer:return y(e,5),{type:"pointer",x:n.getUint16(0),y:n.getUint16(2),buttons:n.getUint8(4)};case o.key:if(y(e,5),n.getUint8(0)>1)throw new l("invalid_key_flags");return{type:"key",down:n.getUint8(0)===1,keysym:n.getUint32(1)};case o.config:return y(e,1),{type:"config",preset:L(n.getUint8(0))};case o.keyframeRequest:return y(e,0),{type:"keyframeRequest"};case o.audioHello:if(e.byteLength<5)throw new l("invalid_length");return{type:"audioHello",sampleRate:n.getUint32(0),channels:n.getUint8(4),codec:x(e.subarray(5))};case o.audio:if(e.byteLength<9)throw new l("invalid_length");return{type:"audio",captureMicros:Number(n.getBigUint64(0)),data:e.subarray(8)};case o.audioEnable:if(y(e,1),n.getUint8(0)>1)throw new l("invalid_audio_flags");return{type:"audioEnable",on:n.getUint8(0)===1};case o.resize:return y(e,4),{type:"resize",width:n.getUint16(0),height:n.getUint16(2)};case o.control:return{type:"control",control:re(e)};case o.windows:{if(e.byteLength%16!==0||e.byteLength>D*16)throw new l("invalid_length");let i=[];for(let s=0;s<e.byteLength;s+=16)i.push({x:n.getInt32(s),y:n.getInt32(s+4),width:n.getInt32(s+8),height:n.getInt32(s+12)});return{type:"windows",bounds:i}}case o.ack:return y(e,4),{type:"ack",seq:n.getUint32(0)};default:return null}}class Bn{buffer=new Uint8Array(0);push(t){let e=new Uint8Array(this.buffer.byteLength+t.byteLength);e.set(this.buffer),e.set(t,this.buffer.byteLength);let n=[],i=0;while(e.byteLength-i>=4){let s=new DataView(e.buffer,e.byteOffset+i,4).getUint32(0);if(s<1||s>M)throw new l("invalid_message_length");if(e.byteLength-i-4<s)break;let a=e[i+4],c=e.slice(i+5,i+4+s),d=ie(a,c);if(d)n.push(d);i+=4+s}return this.buffer=e.slice(i),n}}var j="/usr/bin/osascript",oe=5000,ae=1048576,ce=String.raw`
2
+ import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as se,spawn as E}from"child_process";var vo="h264_ws_v1",So="video",dt=["smooth","sharp","data_saver","balanced"];var Eo="video_presets";var M=8388608,S=65536,xo="control",ko="v1",X=200;function $n(t){if(!t||typeof t!=="object"||Array.isArray(t))return null;let e=t,n=(i)=>typeof i==="string"&&i.length>0&&i.length<=X;if(Object.keys(e).length!==2||!n(e.user_id)||!n(e.name))return null;return{user_id:e.user_id,name:e.name}}var Co="windows",Ao="v1",Po="look",Ro="v1",J=["reason","grok"];function Mn(t){return typeof t==="string"&&J.includes(t)?t:null}var D=200,Z=(t)=>typeof t==="string"&&dt.includes(t);function To(t){if(!t||typeof t!=="object"||Array.isArray(t))return null;let e=t;if(Object.keys(e).length!==2||e.format!=="h264_ws_v1"||!Z(e.preset))return null;return{format:"h264_ws_v1",preset:e.preset}}var o={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23,resize:24};class l extends Error{constructor(t){super(t);this.name="DisplayVideoProtocolError"}}var Q=new TextEncoder,ee=new TextDecoder("utf-8",{fatal:!0});function p(t,e){if(e.byteLength+1>M)throw new l("message_too_large");let n=new Uint8Array(5+e.byteLength),i=new DataView(n.buffer);return i.setUint32(0,e.byteLength+1),i.setUint8(4,t),n.set(e,5),n}function w(t){let e=Q.encode(t);if(e.byteLength>S)throw new l("text_too_large");return e}function _(t,e){if(!Number.isInteger(t)||t<0||t>65535)throw new l(`invalid_${e}`);return t}function te(t){if(!Number.isFinite(t))throw new l("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(t)))}function Wt(t){switch(t.type){case"hello":{let e=w(t.codec),n=new Uint8Array(6+e.byteLength),i=new DataView(n.buffer);return i.setUint16(0,_(t.width,"width")),i.setUint16(2,_(t.height,"height")),i.setUint8(4,Math.max(1,Math.min(240,Math.round(t.fps)))),i.setUint8(5,dt.indexOf(t.preset)),n.set(e,6),p(o.hello,n)}case"frame":{let e=new Uint8Array(13+t.data.byteLength),n=new DataView(e.buffer);return n.setUint8(0,t.key?1:0),n.setUint32(1,t.seq>>>0),n.setBigUint64(5,BigInt(Math.max(0,Math.floor(t.captureMicros)))),e.set(t.data,13),p(o.frame,e)}case"stats":return p(o.stats,w(JSON.stringify(t.stats)));case"pong":case"ping":{let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t.token),p(t.type==="ping"?o.ping:o.pong,e)}case"serverClipboard":return p(o.serverClipboard,w(t.text));case"clientClipboard":return p(o.clientClipboard,w(t.text));case"error":return p(o.error,w(t.code));case"pointer":{let e=new Uint8Array(5),n=new DataView(e.buffer);return n.setUint16(0,_(t.x,"x")),n.setUint16(2,_(t.y,"y")),n.setUint8(4,t.buttons&255),p(o.pointer,e)}case"key":{let e=new Uint8Array(5),n=new DataView(e.buffer);return n.setUint8(0,t.down?1:0),n.setUint32(1,t.keysym>>>0),p(o.key,e)}case"config":return p(o.config,Uint8Array.of(dt.indexOf(t.preset)));case"keyframeRequest":return p(o.keyframeRequest,new Uint8Array(0));case"audioHello":{let e=w(t.codec),n=new Uint8Array(5+e.byteLength),i=new DataView(n.buffer);return i.setUint32(0,t.sampleRate>>>0),i.setUint8(4,t.channels&255),n.set(e,5),p(o.audioHello,n)}case"audio":{let e=new Uint8Array(8+t.data.byteLength);return new DataView(e.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(t.captureMicros)))),e.set(t.data,8),p(o.audio,e)}case"control":return p(o.control,w(JSON.stringify(t.control)));case"windows":{let e=t.bounds.slice(0,D),n=new Uint8Array(e.length*16),i=new DataView(n.buffer);return e.forEach((s,a)=>{[s.x,s.y,s.width,s.height].forEach((c,d)=>i.setInt32(a*16+d*4,te(c)))}),p(o.windows,n)}case"audioEnable":return p(o.audioEnable,Uint8Array.of(t.on?1:0));case"resize":{let e=new Uint8Array(4),n=new DataView(e.buffer);return n.setUint16(0,_(t.width,"width")),n.setUint16(2,_(t.height,"height")),p(o.resize,e)}case"ack":{let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t.seq>>>0),p(o.ack,e)}}}function L(t){let e=dt[t];if(!e)throw new l("invalid_preset");return e}function y(t,e){if(t.byteLength!==e)throw new l("invalid_length")}function x(t){if(t.byteLength>S)throw new l("text_too_large");try{return ee.decode(t)}catch{throw new l("invalid_text")}}function ne(t){let e;try{e=JSON.parse(x(t))}catch{throw new l("invalid_stats")}let n=e;if(!n||typeof n!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((s)=>typeof n[s]!=="number"||!Number.isFinite(n[s])))throw new l("invalid_stats");return{fps:n.fps,kbps:n.kbps,dropped:n.dropped,restarts:n.restarts,queued_bytes:n.queued_bytes}}function re(t){let e;try{e=JSON.parse(x(t))}catch{throw new l("invalid_control")}let n=e;if(!n||typeof n!=="object"||typeof n.you!=="boolean"||typeof n.same_user!=="boolean")throw new l("invalid_control");let i=n.holder===null?null:$n(n.holder);if(i===null&&n.holder!==null)throw new l("invalid_control");return{holder:i,you:n.you,same_user:n.same_user}}function ie(t,e){let n=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(t){case o.hello:if(e.byteLength<6)throw new l("invalid_length");return{type:"hello",width:n.getUint16(0),height:n.getUint16(2),fps:n.getUint8(4),preset:L(n.getUint8(5)),codec:x(e.subarray(6))};case o.frame:if(e.byteLength<14)throw new l("invalid_length");if(n.getUint8(0)>1)throw new l("invalid_frame_flags");return{type:"frame",key:n.getUint8(0)===1,seq:n.getUint32(1),captureMicros:Number(n.getBigUint64(5)),data:e.subarray(13)};case o.stats:return{type:"stats",stats:ne(e)};case o.ping:case o.pong:return y(e,8),{type:t===o.ping?"ping":"pong",token:n.getFloat64(0)};case o.serverClipboard:return{type:"serverClipboard",text:x(e)};case o.clientClipboard:return{type:"clientClipboard",text:x(e)};case o.error:return{type:"error",code:x(e)};case o.pointer:return y(e,5),{type:"pointer",x:n.getUint16(0),y:n.getUint16(2),buttons:n.getUint8(4)};case o.key:if(y(e,5),n.getUint8(0)>1)throw new l("invalid_key_flags");return{type:"key",down:n.getUint8(0)===1,keysym:n.getUint32(1)};case o.config:return y(e,1),{type:"config",preset:L(n.getUint8(0))};case o.keyframeRequest:return y(e,0),{type:"keyframeRequest"};case o.audioHello:if(e.byteLength<5)throw new l("invalid_length");return{type:"audioHello",sampleRate:n.getUint32(0),channels:n.getUint8(4),codec:x(e.subarray(5))};case o.audio:if(e.byteLength<9)throw new l("invalid_length");return{type:"audio",captureMicros:Number(n.getBigUint64(0)),data:e.subarray(8)};case o.audioEnable:if(y(e,1),n.getUint8(0)>1)throw new l("invalid_audio_flags");return{type:"audioEnable",on:n.getUint8(0)===1};case o.resize:return y(e,4),{type:"resize",width:n.getUint16(0),height:n.getUint16(2)};case o.control:return{type:"control",control:re(e)};case o.windows:{if(e.byteLength%16!==0||e.byteLength>D*16)throw new l("invalid_length");let i=[];for(let s=0;s<e.byteLength;s+=16)i.push({x:n.getInt32(s),y:n.getInt32(s+4),width:n.getInt32(s+8),height:n.getInt32(s+12)});return{type:"windows",bounds:i}}case o.ack:return y(e,4),{type:"ack",seq:n.getUint32(0)};default:return null}}class Bn{buffer=new Uint8Array(0);push(t){let e=new Uint8Array(this.buffer.byteLength+t.byteLength);e.set(this.buffer),e.set(t,this.buffer.byteLength);let n=[],i=0;while(e.byteLength-i>=4){let s=new DataView(e.buffer,e.byteOffset+i,4).getUint32(0);if(s<1||s>M)throw new l("invalid_message_length");if(e.byteLength-i-4<s)break;let a=e[i+4],c=e.slice(i+5,i+4+s),d=ie(a,c);if(d)n.push(d);i+=4+s}return this.buffer=e.slice(i),n}}var j="/usr/bin/osascript",oe=5000,ae=1048576,ce=String.raw`
3
3
  ObjC.import("CoreGraphics");
4
4
  ObjC.import("ApplicationServices");
5
5
  ObjC.import("AppKit");
@@ -109,4 +109,4 @@ function run() {
109
109
  `);h>=0;h=f.indexOf(`
110
110
  `)){let U=f.slice(0,h);if(f=f.slice(h+1),!U.startsWith("c "))continue;let A=U.slice(2);if(A.length>Math.ceil(S/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(A)){u({reason:"display_protocol"});return}let C=Buffer.from(A,"base64");if(C.byteLength<=S)t.clipboard(C.toString("utf8"));if(a)return}if(f.length>Math.ceil(S/3)*4+2)u({reason:"display_protocol"})}),c.once("error",()=>b("Reason could not watch this Mac's desktop clipboard.")),c.once("exit",()=>{if(!a)b("Reason could not watch this Mac's desktop clipboard.")})};return n.stdout.on("data",(f)=>{if(a||s===null)return;s+=f.toString("utf8");let g=s.indexOf(`
111
111
  `);if(g<0){if(s.length>4096)u({reason:"display_protocol"});return}let h=q(s.slice(0,g));if(s=null,!h)u({reason:"display_protocol"});else if(!h.screen||!h.accessibility)b(e.length>0?"Reason's background worker needs Screen Recording and Accessibility on this Mac (its own Reason entry in System Settings > Privacy & Security, not the Reason app's): run `reason permissions allow` on this Mac.":"Allow Screen Recording and Accessibility for this Mac's Reason worker, then restart it.");else z(),t.ready({width:h.width,height:h.height})}),n.stdin.on("error",()=>{return}),n.once("error",()=>b("Reason could not start this Mac's desktop input.")),n.once("exit",()=>{if(s!==null)b("Reason could not start this Mac's desktop input.");else u({reason:"display_closed"})}),{pointer:(f,g,h)=>m(i.pointer(f,g,h)),key:(f,g)=>m(i.key(f,g)),clipboard:(f)=>m([`c ${Buffer.from(f,"utf8").toString("base64")}`]),close(){a=!0,d()}}}
112
- export{bo,vo,dt,So,S,Eo,xo,Mn,ko,Co,Ao,Po,$n,Ro,Wt,Bn,Ge,pt,Fn,jn};
112
+ export{vo,So,dt,Eo,S,xo,ko,$n,Co,Ao,Po,Ro,Mn,To,Wt,Bn,Ge,pt,Fn,jn};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{ot,I}from"./vm-hands-entry-lite-9knf91et.js";import{R}from"./vm-hands-entry-lite-a3p6xz53.js";import{_,rr}from"./vm-hands-entry-lite-t82dzcxb.js";import{be}from"./vm-hands-entry-lite-yretc2th.js";function Hi(e,i){let t=R(e,"REASON_API_URL")?.trim();if(!t)return rr(i);let n=new URL(t);if(n.protocol!=="https:"&&!(n.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(n.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return n.origin}function es(e){return R(e,"REASON_API_URL")?.trim()?Hi(e,"production"):void 0}function ts(e){return R(e,"REASON_API_KEY")?.trim()||void 0}async function As(e,i){let t=e.env??process.env,n=ts(t);if(!n)return(e.getCredentials??ot)({apiOrigin:es(t),signal:i});let a=Hi(t,e.channel??_({env:t})),o=await(e.fetchImpl??fetch)(a+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+n,accept:"application/json"},signal:i}),p=await o.json().catch(()=>({})),r=be(p)?p:{};if(!o.ok){let s=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:"API key authentication failed ("+o.status+")";throw new I(o.status,typeof r.error==="string"?r.error:"api_key_auth_failed",s)}if(typeof r.org_id!=="string"||!r.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let l=Array.isArray(r.scopes)?r.scopes.filter((s)=>typeof s==="string"):[];return{credentialKind:"api_key",apiOrigin:a,accessToken:n,orgId:r.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:l}}export{Hi,es,ts,As};
2
+ import{ot,D}from"./vm-hands-entry-lite-mzj7j4hp.js";import{R}from"./vm-hands-entry-lite-a3p6xz53.js";import{_,rr}from"./vm-hands-entry-lite-4anjdcth.js";import{be}from"./vm-hands-entry-lite-yretc2th.js";function zi(e,i){let t=R(e,"REASON_API_URL")?.trim();if(!t)return rr(i);let n=new URL(t);if(n.protocol!=="https:"&&!(n.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(n.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return n.origin}function es(e){return R(e,"REASON_API_URL")?.trim()?zi(e,"production"):void 0}function ts(e){return R(e,"REASON_API_KEY")?.trim()||void 0}async function As(e,i){let t=e.env??process.env,n=ts(t);if(!n)return(e.getCredentials??ot)({apiOrigin:es(t),signal:i});let a=zi(t,e.channel??_({env:t})),o=await(e.fetchImpl??fetch)(a+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+n,accept:"application/json"},signal:i}),p=await o.json().catch(()=>({})),r=be(p)?p:{};if(!o.ok){let s=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:"API key authentication failed ("+o.status+")";throw new D(o.status,typeof r.error==="string"?r.error:"api_key_auth_failed",s)}if(typeof r.org_id!=="string"||!r.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let l=Array.isArray(r.scopes)?r.scopes.filter((s)=>typeof s==="string"):[];return{credentialKind:"api_key",apiOrigin:a,accessToken:n,orgId:r.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:l}}export{zi,es,ts,As};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{R}from"./vm-hands-entry-lite-a3p6xz53.js";import{Fo}from"./vm-hands-entry-lite-t82dzcxb.js";import{Fe,un,It,dn}from"./vm-hands-entry-lite-krnvgf71.js";import{Qn}from"./vm-hands-entry-lite-9y3dvyfj.js";import{t,o,d,u,i,gs,W,g,s,n}from"./vm-hands-entry-lite-4cdn822w.js";var q=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function v(e){let r=typeof e==="string"?q.exec(e):null;return r?{major:Number(r[1]),minor:Number(r[2])}:null}var j=25,x=1e5,L=/^[0-9a-f]{64}$/,N=i({day:t().regex(/^\d{4}-\d{2}-\d{2}$/),sent:o().int().min(0).max(x),received:o().int().min(0).max(x)}),Ue=i({machine:t().min(1).max(200),person:t().min(1).max(200),team:t().min(1).max(200),team_id:t().min(1).max(200).optional(),workspace:d().optional(),version:t().max(64).optional(),wait_seconds:o().int().min(0).max(j).optional(),message_counts:u(N).max(14).optional().catch(void 0),endpoint:t().regex(L).optional().catch(void 0)}),D=g("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:D.nullable(),retry_after_seconds:o().optional()}),H=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()}),F=i({person:t(),machine:t(),online:d()}),B=i({team:t().nullable(),sessions:u(H).max(2000),machines:u(F).max(500),all:d().optional()}),G=i({address:t().max(300),state:t().max(40),note:t().max(500)}),Oe=W([i({who:B}),i({sent:i({ids:u(t().max(100)).max(500),recipients:u(t().max(300)).max(500),from:t().max(300),deliveries:u(G).max(500).optional()})}),i({error:t().min(1).max(2000)})]),J=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()}),Me=i({messages:u(J).max(100),team:t().min(1).max(200).optional(),team_id:t().min(1).max(200).optional(),workspace:d().optional()});var C=["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 Ve=C.filter((e)=>e!=="network:read"&&e!=="network:write");class b extends Error{oauthCode;constructor(e,r=null){super(e);this.oauthCode=r;this.name="LoginError"}}function K(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 b(l,a)}async function Q(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 K(m,`OAuth token request failed (${c.status})`);return m}var V=1e4;async function Y(e,r={}){let a=r.fetchImpl??fetch,l=await Q(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),a,AbortSignal.timeout(V)).catch((m)=>{if(m instanceof Error&&m.name==="TimeoutError")throw new b("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 b("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 un(c,r.path??Fe()),c}var w=new Map,X=2000,Z=100;function A(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 ot(e={}){let r=e.path??Fe(),a=It(r);if(!a)return null;let l=e.apiOrigin??R(process.env,"REASON_API_URL")?.trim();if(l&&!Fo(a.apiOrigin,new URL(l).origin))return null;if(!(Date.parse(a.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&a.accessToken!==e.refused))return a;let m=[r,a.apiOrigin,a.clientId,a.refreshToken].join("\x00"),p=w.get(m);if(p)return A(p,e.signal);let f;return f=Y(a,{fetchImpl:e.fetchImpl,path:r}).catch(async(y)=>{if(!(y instanceof b)||y.oauthCode!=="invalid_grant"&&y.oauthCode!=="invalid_client")throw y;let k=(_)=>_!==null&&(y.oauthCode==="invalid_client"?_.clientId!==a.clientId:_.refreshToken!==a.refreshToken),E=Date.now()+X;while(!k(It(r))&&Date.now()<E)await new Promise((_)=>setTimeout(_,Z));if(k(It(r)))return ot({fetchImpl:e.fetchImpl,path:r});return dn(r),null}).finally(()=>{if(w.get(m)===f)w.delete(m)}),w.set(m,f),A(f,e.signal)}var ee=i({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:d().nullable()}),ne=i({groups:u(i({selectable:d().optional(),accounts:u(i({source_id:t().min(1),model_ids:u(t().min(1)).optional()}))}))});function te(e){let r=ne.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;refusal;constructor(e,r,a,l,c,m,p){super(a);this.status=e;this.code=r;this.suggestedModel=l;this.retryAfterMs=c;this.resolutionReason=m;this.refusal=p;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 se=["minimal","low","medium","high","xhigh","max"],oe=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()}))}),re=i({devices:u(oe),end_cursor:t().nullish(),has_next_page:d().optional()}),ie=i({id:t().min(1),name:t()}),ae=i({items:u(ie)}),le=i({id:t().min(1),name:t(),main:d(),mine:d(),session_id:t().nullish(),appearance:i({color:t().nullish()}).nullish().catch(null)}),ce=i({items:u(le)}),de=i({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:u(t()).default([]),is_enabled:d().default(!0)}),me=i({items:u(de).default([])}),ue=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()}),U=i({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:d(),triggers:u(ue).default([])}),ge=i({items:u(U).default([]),end_cursor:t().nullish(),has_next_page:d().optional()}),he=i({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:d()}),pe=i({items:u(he).default([])}),fe=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()}),T=i({tags:u(t()).default([])}),ye=s(["linux","macos"]),O=i({id:t().min(1),name:t().min(1),platform:ye.nullable(),workers:i({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:i({queued:o().int(),running:o().int()})}),_e=i({machines:u(O)}),Re=i({machine:O}),be=i({deleted:n(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),we=i({token:i({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),M=gs({machine_id:t().min(1),machine_name:t().min(1)}),Se=M.extend({organization_id:t().min(1)}),an=i({id:t().min(1),name:t().min(1),state:s(["waiting","placed"]),queue_position:o().int().nullable()});var ln=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 ke=i({error:i({type:t(),message:t()})});function S(e,r,a){let l=ke.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,typeof r.code==="string"?{code:r.code,...typeof r.billing_path==="string"&&/^\/(?![/\\])/.test(r.billing_path)?{billingPath:r.billing_path}:{}}:void 0)}async function Ps(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 S(r.status,a,r.headers.get("retry-after"));return h(Se,a,"invalid_machine_ticket")}var ve=i({items:u(i({name:t()}))}),xe=i({name:t(),scope:t(),result:s(["created","updated"]).optional(),warning:i({message:t()}).optional()});class rs{options;credentials;constructor(e,r={}){this.options=r;this.credentials=e}trackEvent(e,r={}){}async request(e,r={}){let{status:a,headers:l,json:c}=await this.exchange(e,r);if(a<200||a>299)throw S(a,c,l.get("retry-after"));return c}async exchange(e,r={},a=!1){let l=this.options.fetchImpl??fetch;if(!a&&r.retryUnauthorized!==!1)await this.renewBeforeExpiry(l,r.signal);let c=await l(`${this.credentials.apiOrigin}/v3${e}`,{method:r.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Qn,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...r.raw?{"content-type":r.raw.contentType}:r.body===void 0?{}:{"content-type":"application/json"},...r.headers,...r.ifNoneMatch?{"if-none-match":r.ifNoneMatch}:{}},body:r.raw?r.raw.bytes:r.body===void 0?void 0:JSON.stringify(r.body),signal:r.signal,redirect:r.ifNoneMatch?"manual":"error"}),m=await c.json().catch(()=>({}));if(c.status===401&&!a&&r.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let p=await ot({fetchImpl:l,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:r.signal});if(p)return this.credentials=p,this.exchange(e,r,!0)}return{status:c.status,headers:c.headers,json:m}}async renewBeforeExpiry(e,r){let a=this.credentials;if(a.credentialKind==="api_key"||!(Date.parse(a.expiresAt)<=Date.now()+60000))return;let l=await ot({fetchImpl:e,path:this.options.credentialsPath,signal:r}).catch(()=>null);if(l&&l.apiOrigin===a.apiOrigin&&l.orgId===a.orgId&&l.clientId===a.clientId)this.credentials=l}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(_e,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(Re,r,"invalid_machine").machine}async deleteMachine(e){let r=await this.request(this.machinePath(e),{method:"DELETE"});return h(be,r,"invalid_machine_deletion")}async listSecretNames(e){let r=await this.request(`${this.secretsPath()}?scope=${e}`);return h(ve,r,"invalid_secret_list").items.map((a)=>a.name)}async setSecret(e){let r=await this.request(this.secretsPath(),{method:"POST",body:e});return h(xe,r,"invalid_secret_write")}secretsPath(){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/secrets`}async createMachineToken(e){let r=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return h(we,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(M,a,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(e=AbortSignal.timeout(30000)){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:e})}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: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=ae.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(ce,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(me,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=re.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:se.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=ee.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let r;try{r=te(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 listSessionFields(e){let r=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)r.set("origin",e.origin);r.set("fields",e.fields.join(","));let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${r.toString()}`,{status:l,headers:c,json:m}=await this.exchange(a,e.etag?{ifNoneMatch:e.etag}:{});if(l===304)return null;if(l<200||l>299)throw S(l,m,c.get("retry-after"));return{items:Array.isArray(m.items)?m.items:[],etag:c.get("etag")}}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(T,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(T,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(fe,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(ge,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(U,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(pe,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}})}}
3
- export{ot,I,Ps,rs};
2
+ import{R}from"./vm-hands-entry-lite-a3p6xz53.js";import{jo}from"./vm-hands-entry-lite-4anjdcth.js";import{Fe,un,Dt,dn}from"./vm-hands-entry-lite-04x5xjt6.js";import{Qn}from"./vm-hands-entry-lite-a64cxaqn.js";import{t,o,d,u,i,gs,W,g,s,n}from"./vm-hands-entry-lite-ztsp4gs8.js";var E=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function v(e){let r=typeof e==="string"?E.exec(e):null;return r?{major:Number(r[1]),minor:Number(r[2])}:null}var z=25,x=1e5,j=/^[0-9a-f]{64}$/,L=i({day:t().regex(/^\d{4}-\d{2}-\d{2}$/),sent:o().int().min(0).max(x),received:o().int().min(0).max(x)}),Ue=i({machine:t().min(1).max(200),person:t().min(1).max(200),team:t().min(1).max(200),team_id:t().min(1).max(200).optional(),workspace:d().optional(),version:t().max(64).optional(),wait_seconds:o().int().min(0).max(z).optional(),message_counts:u(L).max(14).optional().catch(void 0),endpoint:t().regex(j).optional().catch(void 0)}),N=g("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:N.nullable(),retry_after_seconds:o().optional()}),H=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()}),F=i({person:t(),machine:t(),online:d()}),B=i({team:t().nullable(),sessions:u(H).max(2000),machines:u(F).max(500),all:d().optional()}),G=i({address:t().max(300),state:t().max(40),note:t().max(500)}),Oe=W([i({who:B}),i({sent:i({ids:u(t().max(100)).max(500),recipients:u(t().max(300)).max(500),from:t().max(300),deliveries:u(G).max(500).optional()})}),i({error:t().min(1).max(2000)})]),J=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()}),Me=i({messages:u(J).max(100),team:t().min(1).max(200).optional(),team_id:t().min(1).max(200).optional(),workspace:d().optional()});var I=["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 Ve=I.filter((e)=>e!=="network:read"&&e!=="network:write");class b extends Error{oauthCode;constructor(e,r=null){super(e);this.oauthCode=r;this.name="LoginError"}}function K(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 b(l,a)}async function Q(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 K(m,`OAuth token request failed (${c.status})`);return m}var V=1e4;async function Y(e,r={}){let a=r.fetchImpl??fetch,l=await Q(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),a,AbortSignal.timeout(V)).catch((m)=>{if(m instanceof Error&&m.name==="TimeoutError")throw new b("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 b("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 un(c,r.path??Fe()),c}var w=new Map,X=2000,Z=100;function C(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 ot(e={}){let r=e.path??Fe(),a=Dt(r);if(!a)return null;let l=e.apiOrigin??R(process.env,"REASON_API_URL")?.trim();if(l&&!jo(a.apiOrigin,new URL(l).origin))return null;if(!(Date.parse(a.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&a.accessToken!==e.refused))return a;let m=[r,a.apiOrigin,a.clientId,a.refreshToken].join("\x00"),p=w.get(m);if(p)return C(p,e.signal);let f;return f=Y(a,{fetchImpl:e.fetchImpl,path:r}).catch(async(y)=>{if(!(y instanceof b)||y.oauthCode!=="invalid_grant"&&y.oauthCode!=="invalid_client")throw y;let k=(_)=>_!==null&&(y.oauthCode==="invalid_client"?_.clientId!==a.clientId:_.refreshToken!==a.refreshToken),M=Date.now()+X;while(!k(Dt(r))&&Date.now()<M)await new Promise((_)=>setTimeout(_,Z));if(k(Dt(r)))return ot({fetchImpl:e.fetchImpl,path:r});return dn(r),null}).finally(()=>{if(w.get(m)===f)w.delete(m)}),w.set(m,f),C(f,e.signal)}var ee=i({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:d().nullable()}),ne=i({groups:u(i({selectable:d().optional(),accounts:u(i({source_id:t().min(1),model_ids:u(t().min(1)).optional()}))}))});function te(e){let r=ne.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 D extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;refusal;constructor(e,r,a,l,c,m,p){super(a);this.status=e;this.code=r;this.suggestedModel=l;this.retryAfterMs=c;this.resolutionReason=m;this.refusal=p;this.name="ApiError"}static rateLimitDelayMs(e,r){if(!(e instanceof D)||e.status!==429)return null;return Math.min(60000,Math.max(r,e.retryAfterMs??0))}}var se=["minimal","low","medium","high","xhigh","max"],oe=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()}))}),re=i({devices:u(oe),end_cursor:t().nullish(),has_next_page:d().optional()}),ie=i({id:t().min(1),name:t()}),ae=i({items:u(ie)}),le=i({id:t().min(1),name:t(),main:d(),mine:d(),session_id:t().nullish(),appearance:i({color:t().nullish()}).nullish().catch(null)}),ce=i({items:u(le)}),de=i({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:u(t()).default([]),is_enabled:d().default(!0)}),me=i({items:u(de).default([])}),ue=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()}),T=i({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:d(),triggers:u(ue).default([])}),ge=i({items:u(T).default([]),end_cursor:t().nullish(),has_next_page:d().optional()}),he=i({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:d()}),pe=i({items:u(he).default([])}),fe=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()}),A=i({tags:u(t()).default([])}),ye=s(["linux","macos"]),U=i({id:t().min(1),name:t().min(1),platform:ye.nullable(),workers:i({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:i({queued:o().int(),running:o().int()})}),_e=i({machines:u(U)}),Re=i({machine:U}),be=i({deleted:n(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),we=i({token:i({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),O=gs({machine_id:t().min(1),machine_name:t().min(1)}),Se=O.extend({organization_id:t().min(1)}),an=i({id:t().min(1),name:t().min(1),state:s(["waiting","placed"]),queue_position:o().int().nullable()});var ln=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 D(502,a,"Reason returned an unexpected response.");return l.data}var ke=i({error:i({type:t(),message:t()})});function S(e,r,a){let l=ke.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 D(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,typeof r.code==="string"?{code:r.code,...typeof r.billing_path==="string"&&/^\/(?![/\\])/.test(r.billing_path)?{billingPath:r.billing_path}:{}}:void 0)}async function Ps(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 S(r.status,a,r.headers.get("retry-after"));return h(Se,a,"invalid_machine_ticket")}var ve=i({items:u(i({name:t()}))}),xe=i({name:t(),scope:t(),result:s(["created","updated"]).optional(),warning:i({message:t()}).optional()});class rs{options;credentials;constructor(e,r={}){this.options=r;this.credentials=e}trackEvent(e,r={}){}async request(e,r={}){let{status:a,headers:l,json:c}=await this.exchange(e,r);if(a<200||a>299)throw S(a,c,l.get("retry-after"));return c}async exchange(e,r={},a=!1){let l=this.options.fetchImpl??fetch;if(!a&&r.retryUnauthorized!==!1)await this.renewBeforeExpiry(l,r.signal);let c=await l(`${this.credentials.apiOrigin}/v3${e}`,{method:r.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Qn,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...r.raw?{"content-type":r.raw.contentType}:r.body===void 0?{}:{"content-type":"application/json"},...r.headers,...r.ifNoneMatch?{"if-none-match":r.ifNoneMatch}:{}},body:r.raw?r.raw.bytes:r.body===void 0?void 0:JSON.stringify(r.body),signal:r.signal,redirect:r.ifNoneMatch?"manual":"error"}),m=await c.json().catch(()=>({}));if(c.status===401&&!a&&r.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let p=await ot({fetchImpl:l,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:r.signal});if(p)return this.credentials=p,this.exchange(e,r,!0)}return{status:c.status,headers:c.headers,json:m}}async renewBeforeExpiry(e,r){let a=this.credentials;if(a.credentialKind==="api_key"||!(Date.parse(a.expiresAt)<=Date.now()+60000))return;let l=await ot({fetchImpl:e,path:this.options.credentialsPath,signal:r}).catch(()=>null);if(l&&l.apiOrigin===a.apiOrigin&&l.orgId===a.orgId&&l.clientId===a.clientId)this.credentials=l}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 D&&(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(_e,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(Re,r,"invalid_machine").machine}async deleteMachine(e){let r=await this.request(this.machinePath(e),{method:"DELETE"});return h(be,r,"invalid_machine_deletion")}async listSecretNames(e){let r=await this.request(`${this.secretsPath()}?scope=${e}`);return h(ve,r,"invalid_secret_list").items.map((a)=>a.name)}async setSecret(e){let r=await this.request(this.secretsPath(),{method:"POST",body:e});return h(xe,r,"invalid_secret_write")}secretsPath(){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/secrets`}async createMachineToken(e){let r=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return h(we,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(O,a,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(e=AbortSignal.timeout(30000)){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:e})}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: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=ae.safeParse(e);if(!r.success)throw new D(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(ce,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(me,e,"invalid_skill_list").items}catch(e){if(e instanceof D&&(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=re.safeParse(l);if(!c.success)throw new D(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:se.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 D&&(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=ee.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let r;try{r=te(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:r}}catch(e){if(e instanceof D&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let r=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)r.set("origin",e.origin);r.set("fields",e.fields.join(","));let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${r.toString()}`,{status:l,headers:c,json:m}=await this.exchange(a,e.etag?{ifNoneMatch:e.etag}:{});if(l===304)return null;if(l<200||l>299)throw S(l,m,c.get("retry-after"));return{items:Array.isArray(m.items)?m.items:[],etag:c.get("etag")}}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 D)||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 D&&(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(A,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(A,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(fe,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(ge,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(T,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(pe,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}})}}
3
+ export{ot,D,Ps,rs};