@reason-machines/cli-linux-x64 0.2.527 → 0.2.529

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 (86) hide show
  1. package/bin/reason +1 -1
  2. package/bin/vm-hands/api-5ewaw0vr.js +2 -0
  3. package/bin/vm-hands/api-credentials-cdz9mw03.js +2 -0
  4. package/bin/vm-hands/connect-cli-ekfj4bg7.js +2 -0
  5. package/bin/vm-hands/credentials-ts56n6gk.js +2 -0
  6. package/bin/vm-hands/{custom-endpoint-device-6d759gkr.js → custom-endpoint-device-7tgcmhbz.js} +1 -1
  7. package/bin/vm-hands/desktop-account-jdqya1ff.js +2 -0
  8. package/bin/vm-hands/{hands-worker-source-hytk3v4n.js → hands-worker-source-hkjndq4w.js} +1 -1
  9. package/bin/vm-hands/{install-receipt-g15a9v84.js → install-receipt-8tpfepde.js} +1 -1
  10. package/bin/vm-hands/local-automation-zzbppk8c.js +2 -0
  11. package/bin/vm-hands/local-capabilities-mzt7ndkf.js +2 -0
  12. package/bin/vm-hands/{local-desktop-users-wkvb4dpg.js → local-desktop-users-tjcpyakd.js} +1 -1
  13. package/bin/vm-hands/{local-display-mac-d1t1qve5.js → local-display-mac-gtp439kc.js} +1 -1
  14. package/bin/vm-hands/local-display-session-hgh7wgdm.js +2 -0
  15. package/bin/vm-hands/local-display-video-xmwveqz7.js +2 -0
  16. package/bin/vm-hands/local-managed-process-wjan7e28.js +2 -0
  17. package/bin/vm-hands/local-pty-session-tnz6jwtt.js +2 -0
  18. package/bin/vm-hands/{managed-runtime-533929j6.js → managed-runtime-4vb4ve3j.js} +1 -1
  19. package/bin/vm-hands/{network-contract-84vs9gfz.js → network-contract-e98v6mwd.js} +1 -1
  20. package/bin/vm-hands/permissions-k58an38w.js +2 -0
  21. package/bin/vm-hands/{reason-hands-protocol-t51p2jgn.js → reason-hands-protocol-39wqa1xa.js} +1 -1
  22. package/bin/vm-hands/{serve-service-mjnye8vs.js → serve-service-9h4h44zs.js} +1 -1
  23. package/bin/vm-hands/{status-m8cfgr58.js → status-m04nbybr.js} +1 -1
  24. package/bin/vm-hands/version-feand7cf.js +2 -0
  25. package/bin/vm-hands/{vm-hands-entry-lite-jzmrhjkz.js → vm-hands-entry-lite-04x5xjt6.js} +1 -1
  26. package/bin/vm-hands/{vm-hands-entry-lite-yfc1w62e.js → vm-hands-entry-lite-13s0mfpr.js} +1 -1
  27. package/bin/vm-hands/{vm-hands-entry-lite-yj9hbtm1.js → vm-hands-entry-lite-2hfrcr50.js} +3 -3
  28. package/bin/vm-hands/{vm-hands-entry-lite-x342zztg.js → vm-hands-entry-lite-37b5045h.js} +1 -1
  29. package/bin/vm-hands/{vm-hands-entry-lite-mc5y3xr9.js → vm-hands-entry-lite-4anjdcth.js} +2 -2
  30. package/bin/vm-hands/{vm-hands-entry-lite-c6m5n5gh.js → vm-hands-entry-lite-4dqpcyk4.js} +4 -4
  31. package/bin/vm-hands/{vm-hands-entry-lite-06e9xm3v.js → vm-hands-entry-lite-4r1yn35v.js} +3 -3
  32. package/bin/vm-hands/{vm-hands-entry-lite-c5pyaaax.js → vm-hands-entry-lite-5tnma5qb.js} +3 -3
  33. package/bin/vm-hands/{vm-hands-entry-lite-tns12zqc.js → vm-hands-entry-lite-73f4cgkf.js} +2 -2
  34. package/bin/vm-hands/{vm-hands-entry-lite-ep1bq0xq.js → vm-hands-entry-lite-7tc69m74.js} +2 -2
  35. package/bin/vm-hands/{vm-hands-entry-lite-7mntg1rq.js → vm-hands-entry-lite-8dgbw34a.js} +2 -2
  36. package/bin/vm-hands/{vm-hands-entry-lite-msb3z9nq.js → vm-hands-entry-lite-9azmqs47.js} +3 -3
  37. package/bin/vm-hands/{vm-hands-entry-lite-8n2hetqw.js → vm-hands-entry-lite-anc8wmfd.js} +1 -1
  38. package/bin/vm-hands/{vm-hands-entry-lite-q13ekwev.js → vm-hands-entry-lite-b6gsggvp.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-zwnevt4c.js → vm-hands-entry-lite-cgddp0y3.js} +1 -1
  40. package/bin/vm-hands/{vm-hands-entry-lite-yfvz7s4m.js → vm-hands-entry-lite-ct4mtq1m.js} +1 -1
  41. package/bin/vm-hands/{vm-hands-entry-lite-zea60aw2.js → vm-hands-entry-lite-d5m4pfrm.js} +2 -2
  42. package/bin/vm-hands/{vm-hands-entry-lite-r2100wsz.js → vm-hands-entry-lite-gqw0sj34.js} +3 -3
  43. package/bin/vm-hands/{vm-hands-entry-lite-k2kx2ex0.js → vm-hands-entry-lite-hfx1q0b0.js} +2 -2
  44. package/bin/vm-hands/{vm-hands-entry-lite-mhw459y7.js → vm-hands-entry-lite-hr8wmzyh.js} +3 -3
  45. package/bin/vm-hands/{vm-hands-entry-lite-mpy0j95a.js → vm-hands-entry-lite-hv3dxd5k.js} +1 -1
  46. package/bin/vm-hands/{vm-hands-entry-lite-4pm82ns4.js → vm-hands-entry-lite-j5t2pj4v.js} +1 -1
  47. package/bin/vm-hands/{vm-hands-entry-lite-8b6qfv1c.js → vm-hands-entry-lite-jhbeh0qy.js} +3 -3
  48. package/bin/vm-hands/{vm-hands-entry-lite-2egd9wr5.js → vm-hands-entry-lite-jhq35va0.js} +1 -1
  49. package/bin/vm-hands/{vm-hands-entry-lite-gmxfz6k2.js → vm-hands-entry-lite-jvszqt0z.js} +2 -2
  50. package/bin/vm-hands/{vm-hands-entry-lite-5nhmye0y.js → vm-hands-entry-lite-k9vk84wa.js} +2 -2
  51. package/bin/vm-hands/{vm-hands-entry-lite-q9spnspj.js → vm-hands-entry-lite-mnwfn7zv.js} +17 -17
  52. package/bin/vm-hands/{vm-hands-entry-lite-ygymhgk8.js → vm-hands-entry-lite-p83pttx8.js} +4 -4
  53. package/bin/vm-hands/{vm-hands-entry-lite-rxfxd2hs.js → vm-hands-entry-lite-q8rj7vmp.js} +1 -1
  54. package/bin/vm-hands/{vm-hands-entry-lite-5n4ay2gs.js → vm-hands-entry-lite-qc6gxqgs.js} +2 -2
  55. package/bin/vm-hands/{vm-hands-entry-lite-kpahnwm7.js → vm-hands-entry-lite-r2msq3z0.js} +21 -21
  56. package/bin/vm-hands/{vm-hands-entry-lite-dxaa88rs.js → vm-hands-entry-lite-vj7xzb3y.js} +1 -1
  57. package/bin/vm-hands/vm-hands-entry-lite-wgsdpq31.js +2 -0
  58. package/bin/vm-hands/{vm-hands-entry-lite-jvvk1gjx.js → vm-hands-entry-lite-x2bv0n2g.js} +1 -1
  59. package/bin/vm-hands/{vm-hands-entry-lite-3thdz953.js → vm-hands-entry-lite-xe0benev.js} +1 -1
  60. package/bin/vm-hands/vm-hands-entry-lite-y5hv1gjv.js +3 -0
  61. package/bin/vm-hands/{vm-hands-entry-lite-pd34mbnm.js → vm-hands-entry-lite-yxp1k8qm.js} +1 -1
  62. package/bin/vm-hands/{vm-hands-entry-lite-bjtcy8n6.js → vm-hands-entry-lite-ztsp4gs8.js} +3 -3
  63. package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
  64. package/bin/vm-hands/{vm-hands-executor-mx3j751y.js → vm-hands-executor-6jaxxp69.js} +2 -2
  65. package/bin/vm-hands/{vm-hands-op-runner-bpv5sz6e.js → vm-hands-op-runner-jjd51571.js} +1 -1
  66. package/bin/vm-hands/{vm-hands-runtime-z81qbpbr.js → vm-hands-runtime-h58h37am.js} +3 -3
  67. package/bin/vm-hands/worker-preview-readiness-84stxabw.js +2 -0
  68. package/bin/vm-hands/worker-sandbox-563c5g2f.js +2 -0
  69. package/package.json +1 -1
  70. package/bin/vm-hands/api-credentials-rwy5ys03.js +0 -2
  71. package/bin/vm-hands/api-rjgpedvk.js +0 -2
  72. package/bin/vm-hands/connect-cli-p72wek72.js +0 -2
  73. package/bin/vm-hands/credentials-6mbx2mke.js +0 -2
  74. package/bin/vm-hands/desktop-account-fpf13hm4.js +0 -2
  75. package/bin/vm-hands/local-automation-pdhkw5de.js +0 -2
  76. package/bin/vm-hands/local-capabilities-pmks6jpv.js +0 -2
  77. package/bin/vm-hands/local-display-session-m8469h63.js +0 -2
  78. package/bin/vm-hands/local-display-video-6xq6fjtm.js +0 -2
  79. package/bin/vm-hands/local-managed-process-2tx1h7cb.js +0 -2
  80. package/bin/vm-hands/local-pty-session-p60ha91y.js +0 -2
  81. package/bin/vm-hands/permissions-4myxznfs.js +0 -2
  82. package/bin/vm-hands/version-gszhe6py.js +0 -2
  83. package/bin/vm-hands/vm-hands-entry-lite-b48eyd09.js +0 -3
  84. package/bin/vm-hands/vm-hands-entry-lite-j1hddtjs.js +0 -2
  85. package/bin/vm-hands/worker-preview-readiness-afw3ezwg.js +0 -2
  86. package/bin/vm-hands/worker-sandbox-egdjwgcp.js +0 -2
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import{Qe}from"./vm-hands-entry-lite-j1hddtjs.js";import{a}from"./vm-hands-entry-lite-gmxfz6k2.js";import{randomUUID as L}from"crypto";import{spawnSync as b}from"child_process";import{chmodSync as ee,cpSync as te,existsSync as x,lstatSync as A,mkdirSync as Y,readdirSync as ne,readFileSync as w,readlinkSync as re,realpathSync as T,renameSync as E,rmdirSync as ie,rmSync as g,symlinkSync as M,writeFileSync as oe}from"fs";import{dirname as I,join as u,relative as se,resolve as ce}from"path";var Yn="so.ara.cli",k=[Yn,"com.reasonmachines.cli"],F="5LJFSBRY2F";function Gr(e){return`(${e.map((t)=>`identifier "${t}"`).join(" or ")}) and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = "${F}"`}var G="ReasonBackgroundIdentity",Lo="Contents/Helpers/ReasonPermissionTile",ae="so.ara.cli.permission-tile",Ne=Gr([ae,"com.reasonmachines.cli.permission-tile"]),v="AraBackgroundIdentity",ue="Reason",Ce=Gr(k),de=`anchor apple generic and (${k.map((e)=>`identifier "${e}"`).join(" or ")}) and certificate leaf[subject.OU] = "${F}"`;class h extends Error{code;constructor(e,t){super(t);this.code=e;this.name="MacOSBackgroundIdentityError"}}var R="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";function le(e=a()){return u(e,"Library","Application Support","Reason","Background","Reason.app")}function O(e=a()){return u(e,"Library","Application Support","Ara","Background","Ara.app")}function fe(e){try{return A(e).isFile()}catch{return!1}}function D(e){return[G,v].map((t)=>u(e,"Contents","MacOS",t)).find(fe)??null}function d(e){try{if(!A(e).isDirectory())return!1;let t=w(u(e,"Contents","Info.plist"),"utf8");return k.some((n)=>t.includes(`<string>${n}</string>`))&&(t.includes(`<string>${ue}</string>`)||t.includes("<string>Ara</string>"))&&D(e)!==null}catch{return!1}}function Kr(e=a()){let t=le(e);if(!d(t))return null;try{let n=w(u(t,"Contents","Info.plist"),"utf8");return/<key>CFBundleVersion<\/key>\s*<string>(\d+\.\d+\.\d+)<\/string>/.exec(n)?.[1]??null}catch{return null}}function pe(e,t=a()){let n=Kr(t);return n===null||j(N(n.split(".")),N(e.split(/[.-]/).slice(0,3)))}var ge=1e4;function K(e,t){return b(e,[...t],{stdio:"ignore",timeout:ge}).status??1}var W=new Set;function H(e){if(process.env.REASON_TEST_REFUSE_REAL_IDENTITY!=="1")return;let t=(n)=>{try{return T(n)}catch{return ce(n)}};if(e!==void 0&&t(e)!==t(a()))return;throw Error("A test tried to change this computer's real Reason background identity; pass a temporary home. Refused by scripts/test-env.ts.")}var V=/\/(?:runtime|CLI)\/versions\/(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$|\/\.(?:ara|reason)(?:-staging)?-worker-(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$/,J=new Set(["ara","ara.exe","reason","reason.exe"]);function N(e){return e.map((t)=>Number(t))}function j(e,t){for(let n=0;n<3;n+=1)if(e[n]!==t[n])return e[n]<t[n];return!1}var ye=[0,2,161];function me(e){if(e===null)return!0;let t=ye,n=null;try{n=T(process.execPath)}catch{}return e.some((r)=>{let i=V.exec(r);if(i){let f=i[1]===void 0?i.slice(4,7):i.slice(1,4);return j(N(f),t)}let o=r.slice(r.lastIndexOf("/")+1);return J.has(o)&&r!==n&&r!==process.execPath})}function Ee(){let e=b("/bin/ps",["-xo","pid=,comm="],{encoding:"utf8",timeout:5000});if(e.status!==0)return null;let t=[];for(let n of e.stdout.split(`
2
+ import{Qe}from"./vm-hands-entry-lite-wgsdpq31.js";import{a}from"./vm-hands-entry-lite-jvszqt0z.js";import{randomUUID as L}from"crypto";import{spawnSync as b}from"child_process";import{chmodSync as ee,cpSync as te,existsSync as x,lstatSync as A,mkdirSync as Y,readdirSync as ne,readFileSync as w,readlinkSync as re,realpathSync as T,renameSync as E,rmdirSync as ie,rmSync as g,symlinkSync as M,writeFileSync as oe}from"fs";import{dirname as I,join as u,relative as se,resolve as ce}from"path";var Yn="so.ara.cli",k=[Yn,"com.reasonmachines.cli"],F="5LJFSBRY2F";function Gr(e){return`(${e.map((t)=>`identifier "${t}"`).join(" or ")}) and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = "${F}"`}var G="ReasonBackgroundIdentity",$o="Contents/Helpers/ReasonPermissionTile",ae="so.ara.cli.permission-tile",Ne=Gr([ae,"com.reasonmachines.cli.permission-tile"]),v="AraBackgroundIdentity",ue="Reason",Ce=Gr(k),de=`anchor apple generic and (${k.map((e)=>`identifier "${e}"`).join(" or ")}) and certificate leaf[subject.OU] = "${F}"`;class h extends Error{code;constructor(e,t){super(t);this.code=e;this.name="MacOSBackgroundIdentityError"}}var R="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";function le(e=a()){return u(e,"Library","Application Support","Reason","Background","Reason.app")}function O(e=a()){return u(e,"Library","Application Support","Ara","Background","Ara.app")}function fe(e){try{return A(e).isFile()}catch{return!1}}function D(e){return[G,v].map((t)=>u(e,"Contents","MacOS",t)).find(fe)??null}function d(e){try{if(!A(e).isDirectory())return!1;let t=w(u(e,"Contents","Info.plist"),"utf8");return k.some((n)=>t.includes(`<string>${n}</string>`))&&(t.includes(`<string>${ue}</string>`)||t.includes("<string>Ara</string>"))&&D(e)!==null}catch{return!1}}function Kr(e=a()){let t=le(e);if(!d(t))return null;try{let n=w(u(t,"Contents","Info.plist"),"utf8");return/<key>CFBundleVersion<\/key>\s*<string>(\d+\.\d+\.\d+)<\/string>/.exec(n)?.[1]??null}catch{return null}}function pe(e,t=a()){let n=Kr(t);return n===null||j(N(n.split(".")),N(e.split(/[.-]/).slice(0,3)))}var ge=1e4;function K(e,t){return b(e,[...t],{stdio:"ignore",timeout:ge}).status??1}var W=new Set;function H(e){if(process.env.REASON_TEST_REFUSE_REAL_IDENTITY!=="1")return;let t=(n)=>{try{return T(n)}catch{return ce(n)}};if(e!==void 0&&t(e)!==t(a()))return;throw Error("A test tried to change this computer's real Reason background identity; pass a temporary home. Refused by scripts/test-env.ts.")}var V=/\/(?:runtime|CLI)\/versions\/(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$|\/\.(?:ara|reason)(?:-staging)?-worker-(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$/,J=new Set(["ara","ara.exe","reason","reason.exe"]);function N(e){return e.map((t)=>Number(t))}function j(e,t){for(let n=0;n<3;n+=1)if(e[n]!==t[n])return e[n]<t[n];return!1}var ye=[0,2,161];function me(e){if(e===null)return!0;let t=ye,n=null;try{n=T(process.execPath)}catch{}return e.some((r)=>{let i=V.exec(r);if(i){let f=i[1]===void 0?i.slice(4,7):i.slice(1,4);return j(N(f),t)}let o=r.slice(r.lastIndexOf("/")+1);return J.has(o)&&r!==n&&r!==process.execPath})}function Ee(){let e=b("/bin/ps",["-xo","pid=,comm="],{encoding:"utf8",timeout:5000});if(e.status!==0)return null;let t=[];for(let n of e.stdout.split(`
3
3
  `)){let r=/^\s*(\d+)\s+(\S.*)$/.exec(n);if(!r||Number(r[1])===process.pid)continue;let i=r[2].trimEnd(),o=i.slice(i.lastIndexOf("/")+1);if(!V.test(i)&&J.has(o)){let c=b("/usr/sbin/lsof",["-a","-p",r[1],"-d","txt","-Fn"],{encoding:"utf8",timeout:5000}).stdout?.split(`
4
4
  `).find((l)=>l.startsWith("n/"));if(c)i=c.slice(1)}t.push(i)}return t}function _e(e){if(H(e.home),!d(e.sourceApp))throw new h("identity_invalid","The packaged Reason background identity is missing or invalid.");let t=e.command??K,n=le(e.home),r=I(n);Y(r,{recursive:!0,mode:448}),ee(r,448);let i=T(e.sourceApp),o=null;try{o=T(n)}catch{}if(i!==o){let f=`${process.pid}.${L()}`,c=u(r,`.Reason.app.${f}.tmp`),l=u(r,`.Reason.app.${f}.old`),y=!1;try{if(te(i,c,{recursive:!0,errorOnExist:!0,preserveTimestamps:!0}),!d(c))throw new h("identity_invalid","The copied Reason background identity is invalid.");let _=e.releaseSigned?["--test-requirement",`=${de}`]:[];if(t("/usr/bin/codesign",["--verify","--strict",..._,c])!==0)throw new h("identity_invalid_signature","The installed Reason background identity has an invalid signature.");let S=!1;for(let p=0;p<4;p+=1){let m=!1;try{E(n,l),m=!0,y=!0}catch(s){if(s.code!=="ENOENT")throw s}if(p===0)e.beforePublish?.();try{E(c,n),S=!0}catch(s){let Z=s.code;if(!["EEXIST","ENOTEMPTY"].includes(Z??""))throw s;if(m)g(l,{recursive:!0,force:!0}),y=!1;if(p===3)throw s;continue}if(m)g(l,{recursive:!0,force:!0}),y=!1;break}if(!S)throw Error("Could not publish Reason's background identity.")}catch(_){if(y&&!x(n)&&x(l))E(l,n);throw _}finally{g(c,{recursive:!0,force:!0}),g(l,{recursive:!0,force:!0})}}return z(n,e,{verified:i!==o}),n}function X(e){return u(I(e),".Reason.app.registered")}function q(e){try{let t=A(e);return t.isDirectory()?`${t.ino}:${t.birthtimeMs}`:null}catch{return null}}function C(e){let t=q(e);try{return t!==null&&w(X(e),"utf8")===t}catch{return!1}}function Q(e){if(d(e))return"bundle";try{if(A(u(e,"Contents","Info.plist"),{throwIfNoEntry:!1}))return null;return A(u(e,"Contents","MacOS",v)).isSymbolicLink()?"retired":null}catch{return null}}function z(e,t,n={}){let r=t.command??K;if(!n.verified&&r("/usr/bin/codesign",["--verify","--strict",e])!==0)throw new h("identity_invalid_signature","The installed Reason background identity has an invalid signature.");if(r(R,["-f",e])!==0)throw new h("identity_register_failed","Could not register Reason's macOS background identity.");let i=q(e);try{if(i)oe(X(e),i,{mode:384})}catch{}try{Se(e,t.home,r,t.runningExecutables??Ee)}catch(o){let f=o.code??"unknown";process.stderr.write(`Reason background identity: legacy_identity_retire_failed (${f})
5
5
  `)}}function Se(e,t,n,r){let i=D(e);if(!i)return;let o=O(t),f=I(o),c=(s)=>u(s,"Contents","MacOS",v),l=se(I(c(o)),i),y=`${process.pid}.${L()}`,_=Q(o);if(_===null)return;let S=_==="bundle";if(S)n(R,["-u",o]);let p=u(f,`.Ara.app.${y}.old`);if(!W.has(o)&&!me(r())){if(!S)n(R,["-u",o]);try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}g(p,{recursive:!0,force:!0}),Ie(f);return}if(!S){if(re(c(o))===l)return;let s=`${c(o)}.${y}`;M(l,s);try{E(s,c(o))}finally{g(s,{force:!0})}return}let m=u(f,`.Ara.app.${y}.shim`);Y(I(c(m)),{recursive:!0}),M(l,c(m));try{try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}try{E(m,o)}catch(s){if(x(o))return;throw E(p,o),s}}finally{g(m,{recursive:!0,force:!0}),g(p,{recursive:!0,force:!0})}}function Ie(e){try{if(ne(e).some((n)=>n!==".DS_Store"))return;g(u(e,".DS_Store"),{force:!0}),ie(e)}catch{}}var B=new Map;function Zn(e=a()){let t=B.get(e);if(t)return t;if(process.platform!=="darwin")return[];let n=U(e);if(n===null&&x(I(le(e))))Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100),n=U(e);if(n===null)return[];return B.set(e,n),n}function U(e){let t=le(e),n=O(e);if(!d(t)||!C(t))try{he({home:e,skipWhenSettled:!0})}catch{}let r=d(t)&&(C(t)||!d(n))?t:d(n)?n:null,i=r?D(r):null;if(!i)return null;if(r===n)W.add(n);let o=b(i,["--can-spawn"],{env:{},timeout:2000,encoding:"utf8"});return o.status===0&&o.stdout===`spawn
6
6
  `?[i,"--spawn"]:[]}var P=new Map;function gt(e=a()){let t=Zn(e),n=t[0];if(!n)return[];let r=P.get(n);if(r===void 0){let i=b(n,["--can-spawn-computer-use"],{env:{},timeout:2000,encoding:"utf8"});r=i.status===0&&i.stdout===`spawn
7
- `,P.set(n,r)}return r?t:[]}function $o(e=gt(),t=a()){if(e.length>0)return null;if(Kr(t)===null)return"computer_use_identity_missing";return pe(Qe,t)?"computer_use_identity_outdated":"computer_use_identity_unavailable"}function he(e={}){H(e.home);let t=le(e.home);if(e.skipWhenSettled&&d(t)&&C(t)&&Q(O(e.home))===null)return!0;if(!d(t)){let n=O(e.home);if(!d(n))return!1;try{return _e({...e,sourceApp:n}),!0}catch(r){if(!d(t))throw r}}return z(t,e),!0}var er="REASON_WORKER_IDENTITY_APP";function Mo(e,t=process.env,n=a()){let r=t[er];return r&&r===le(n)?r:e}function Bo(e,t){if(process.platform!=="darwin")return null;let n=le(e),r=u(n,"Contents","MacOS",G),i=b(r,["--can-run-worker",t],{env:{},timeout:2000,encoding:"utf8"});return i.status===0&&i.stdout===`run-worker
7
+ `,P.set(n,r)}return r?t:[]}function Mo(e=gt(),t=a()){if(e.length>0)return null;if(Kr(t)===null)return"computer_use_identity_missing";return pe(Qe,t)?"computer_use_identity_outdated":"computer_use_identity_unavailable"}function he(e={}){H(e.home);let t=le(e.home);if(e.skipWhenSettled&&d(t)&&C(t)&&Q(O(e.home))===null)return!0;if(!d(t)){let n=O(e.home);if(!d(n))return!1;try{return _e({...e,sourceApp:n}),!0}catch(r){if(!d(t))throw r}}return z(t,e),!0}var er="REASON_WORKER_IDENTITY_APP";function Bo(e,t=process.env,n=a()){let r=t[er];return r&&r===le(n)?r:e}function Fo(e,t){if(process.platform!=="darwin")return null;let n=le(e),r=u(n,"Contents","MacOS",G),i=b(r,["--can-run-worker",t],{env:{},timeout:2000,encoding:"utf8"});return i.status===0&&i.stdout===`run-worker
8
8
  `?{app:n,executable:r}:null}
9
- export{Yn,Gr,Lo,le,Kr,Zn,gt,$o,er,Mo,Bo};
9
+ export{Yn,Gr,$o,le,Kr,Zn,gt,Mo,er,Bo,Fo};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{U}from"./vm-hands-entry-lite-a0g6c3wr.js";var To=32;var Io="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",Do=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{To,Io,Do,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};
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{U}from"./vm-hands-entry-lite-a0g6c3wr.js";import{ft}from"./vm-hands-entry-lite-mpy0j95a.js";import{Xt}from"./vm-hands-entry-lite-y9jarm7q.js";import{j}from"./vm-hands-entry-lite-zwnevt4c.js";import{ie}from"./vm-hands-entry-lite-gmxfz6k2.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.")})}})}
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
3
  export{Dr,Vt,Or,ds,Hn,Nr,Un};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{S,Wt,Bn,Ge,Fn,jn}from"./vm-hands-entry-lite-5nhmye0y.js";import{Zn}from"./vm-hands-entry-lite-mhw459y7.js";import{Ln}from"./vm-hands-entry-lite-yfvz7s4m.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as ys,spawn as qe}from"child_process";import{existsSync as ws}from"fs";import{connect as xs}from"net";function pn(){let e=new Set,t=null,n=(s)=>({holder:t?.viewer??null,you:t===s,same_user:Boolean(t?.viewer&&s.viewer&&t.viewer.user_id===s.viewer.user_id)}),o=()=>{for(let s of e)s.notify(n(s))};return{join(s){return e.add(s),s.notify(n(s)),()=>{if(!e.delete(s))return;if(t!==s)return;t=null,o()}},claim(s){if(t===s||!e.has(s))return;t=s,o()}}}var ut=pn();import{createHash as St}from"crypto";import{once as Sn}from"events";import{createWriteStream as vn,existsSync as mr,mkdirSync as gr,mkdtempSync as hr,readFileSync as le,readdirSync as br,renameSync as yr,realpathSync as En,rmSync as Pn,statSync as Ne,writeFileSync as wr}from"fs";import{delimiter as _r,dirname as vt,join as b}from"path";import{finished as Cn}from"stream/promises";var We="omljlfpmafedpplnpkkahegadhkimdje",mo="https://chromewebstore.google.com/detail/reason/omljlfpmafedpplnpkkahegadhkimdje";var O={ocu:{repository:"https://github.com/iFurySt/open-codex-computer-use.git",revision:"386a260d1ab8b690adbbb27f7471595cf0c2b752",version:"0.3.5"},obu:{repository:"https://github.com/iFurySt/open-browser-use.git",revision:"ac015846df75928fbcf0f3a0f3ba3a210ce1a507",version:"0.1.42"}},H={version:"155.0.8059.84",macArm64Sha256:"13b9e98ce56f5ce18e100a009f455c9285f399e7c9dc8a76fdf2f3a9755bb5f2",linux64Sha256:"cf0f049892dea22e6a6db26d47ed0d7776b7158edcbec4634086633df8bafcbc",win64Sha256:"507f2a031441d10c62b5e3d4e863f09ac1198a571c1419976cbd8387f639afde"};var J={ocu:{url:`https://registry.npmjs.org/open-computer-use/-/open-computer-use-${O.ocu.version}.tgz`,sha256:"7c16a87c8cd357787b02c0ebd040dd5f93880c1fb51c1901caa2e0c05d063130",size_bytes:5844280},obu:{url:`https://registry.npmjs.org/open-browser-use/-/open-browser-use-${O.obu.version}.tgz`,sha256:"9386d8ce0a147b3f55e1807b68edf736836378807541c457c9b5f6ca2cabaa4e",size_bytes:21372018},extension:{url:`https://github.com/iFurySt/open-browser-use/releases/download/v${O.obu.version}/open-browser-use-chrome-extension-${O.obu.version}.zip`,sha256:"c9c07bec1175e12ea6985b0e7784a5ef01fd03f014b958224a1e17dcd838a241",size_bytes:31070}},F="pnbmoicbkopffjjgfgfglopechaiemkp";import{spawn as Me}from"child_process";import{createRequire as fn}from"module";import{join as mn}from"path";var gn=30000,hn=1048576;function Te(){return process.env.SystemRoot??"C:\\Windows"}function bn(){return mn(Te(),"System32","WindowsPowerShell","v1.0","powershell.exe")}var yn=String.raw`
2
+ import{S,Wt,Bn,Ge,Fn,jn}from"./vm-hands-entry-lite-k9vk84wa.js";import{Zn}from"./vm-hands-entry-lite-hr8wmzyh.js";import{Ln}from"./vm-hands-entry-lite-ct4mtq1m.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as ys,spawn as qe}from"child_process";import{existsSync as ws}from"fs";import{connect as xs}from"net";function pn(){let e=new Set,t=null,n=(s)=>({holder:t?.viewer??null,you:t===s,same_user:Boolean(t?.viewer&&s.viewer&&t.viewer.user_id===s.viewer.user_id)}),o=()=>{for(let s of e)s.notify(n(s))};return{join(s){return e.add(s),s.notify(n(s)),()=>{if(!e.delete(s))return;if(t!==s)return;t=null,o()}},claim(s){if(t===s||!e.has(s))return;t=s,o()}}}var ut=pn();import{createHash as St}from"crypto";import{once as Sn}from"events";import{createWriteStream as vn,existsSync as mr,mkdirSync as gr,mkdtempSync as hr,readFileSync as le,readdirSync as br,renameSync as yr,realpathSync as En,rmSync as Pn,statSync as Ne,writeFileSync as wr}from"fs";import{delimiter as _r,dirname as vt,join as b}from"path";import{finished as Cn}from"stream/promises";var We="omljlfpmafedpplnpkkahegadhkimdje",go="https://chromewebstore.google.com/detail/reason/omljlfpmafedpplnpkkahegadhkimdje";var O={ocu:{repository:"https://github.com/iFurySt/open-codex-computer-use.git",revision:"386a260d1ab8b690adbbb27f7471595cf0c2b752",version:"0.3.5"},obu:{repository:"https://github.com/iFurySt/open-browser-use.git",revision:"ac015846df75928fbcf0f3a0f3ba3a210ce1a507",version:"0.1.42"}},H={version:"155.0.8059.84",macArm64Sha256:"13b9e98ce56f5ce18e100a009f455c9285f399e7c9dc8a76fdf2f3a9755bb5f2",linux64Sha256:"cf0f049892dea22e6a6db26d47ed0d7776b7158edcbec4634086633df8bafcbc",win64Sha256:"507f2a031441d10c62b5e3d4e863f09ac1198a571c1419976cbd8387f639afde"};var J={ocu:{url:`https://registry.npmjs.org/open-computer-use/-/open-computer-use-${O.ocu.version}.tgz`,sha256:"7c16a87c8cd357787b02c0ebd040dd5f93880c1fb51c1901caa2e0c05d063130",size_bytes:5844280},obu:{url:`https://registry.npmjs.org/open-browser-use/-/open-browser-use-${O.obu.version}.tgz`,sha256:"9386d8ce0a147b3f55e1807b68edf736836378807541c457c9b5f6ca2cabaa4e",size_bytes:21372018},extension:{url:`https://github.com/iFurySt/open-browser-use/releases/download/v${O.obu.version}/open-browser-use-chrome-extension-${O.obu.version}.zip`,sha256:"c9c07bec1175e12ea6985b0e7784a5ef01fd03f014b958224a1e17dcd838a241",size_bytes:31070}},F="pnbmoicbkopffjjgfgfglopechaiemkp";import{spawn as Me}from"child_process";import{createRequire as fn}from"module";import{join as mn}from"path";var gn=30000,hn=1048576;function Te(){return process.env.SystemRoot??"C:\\Windows"}function bn(){return mn(Te(),"System32","WindowsPowerShell","v1.0","powershell.exe")}var yn=String.raw`
3
3
  $ErrorActionPreference = "Stop"
4
4
  Add-Type -TypeDefinition @"
5
5
  using System;
@@ -77,7 +77,7 @@ case "$1" in
77
77
  mcp) shift; exec "$obu" mcp --socket-dir ${Ht} "$@" ;;
78
78
  esac
79
79
  exec "$obu" "$@"
80
- `}function ns(e){let t=He(e),n=t?.allowed_origins;return t!==null&&t.name===It&&t.type==="stdio"&&Array.isArray(n)&&n.includes(`chrome-extension://${We}/`)&&typeof t.path==="string"&&Tt(t.path)}function ss(e,t){if(!e.userChromeHost||!e.userChromeRegistration)return null;if(!t||Kn(e.userChromeHost)!==ts(e.nativeHost)||!Tt(e.userChromeHost))return{code:"user_chrome_browser_use_missing"};return ns(e.userChromeRegistration)?{host:e.userChromeHost}:{code:"user_chrome_native_host_unregistered"}}var rs={display:["display","desktop_session","desktop_video"],computer:["display","desktop_session","system_packages","node","open_computer_use"],browser:["display","desktop_session","system_packages","node","open_computer_use","open_browser_use","browser_extension","browser","chrome_for_testing"]};function x(e={}){let t=e.platform===void 0?Gn():e.platform;if(!t)return null;let n=Tr(t,e.home),o=Wn(n.receipt),s=Vn(t),i=o!==null&&o.platform===t&&JSON.stringify(Object.entries(o.pins).sort())===JSON.stringify(Object.entries(s).sort()),a=[],d=de(t);for(let c of["node","open_computer_use","open_browser_use","chrome_for_testing"]){let _=d[c];if(!_)continue;let v=qn(c,b(n.root,c,_.version),t),D=o?.pins[c],L=v&&D===s[c]?"ready":D!==void 0&&D!==s[c]?"outdated":"missing";a.push({name:c,state:L,detail:_.version})}let y=o?.pins.extension===F&&es(n);a.push({name:"browser_extension",state:y?"ready":"missing",detail:F});let h=U("Xvfb"),g=U("x11vnc"),p=U("openbox");if(K(t))a.push(yt()?{name:"desktop_session",state:"ready",detail:"signed-in desktop session"}:{name:"desktop_session",state:"missing",detail:"run the worker in the signed-in desktop session, not as a service"}),a.push(n.ffmpeg&&A(n.ffmpeg)?{name:"desktop_video",state:"ready",detail:n.ffmpeg}:{name:"desktop_video",state:"missing",detail:"run `reason desktop install` for desktop video"});else if(t!=="darwin-arm64"){a.push(A(ce)?{name:"browser",state:"ready",detail:ce}:{name:"browser",state:"missing",detail:`non-snap Chromium at ${ce}`});let c=h!==null&&g!==null&&p!==null;a.push({name:"display",state:c?"ready":"missing",detail:"Xvfb + openbox + x11vnc"});let _=Hn.filter((P)=>U(P)===null),v=(o?.missing_system_packages??kt).filter((P)=>kt.includes(P)),D=_.length===0&&v.length===0;a.push(D?{name:"system_packages",state:"ready"}:{name:"system_packages",state:"missing",detail:[...new Set([...v,..._])].join(" ")});let L=Ue.filter((P)=>U(P)===null);a.push(L.length===0?{name:"desktop_look",state:"ready"}:{name:"desktop_look",state:"missing",detail:L.join(" ")})}let w=n.ffmpeg&&A(n.ffmpeg)?n.ffmpeg:U("ffmpeg"),f=!w?null:w===n.ffmpeg?n.ffprobe:b(vt(En(w)),"ffprobe"),M=i&&a.every((c)=>c.state==="ready"),E=(c)=>i&&a.every((_)=>!rs[c].includes(_.name)||_.state==="ready");return{platform:t,root:n.root,automation:n.automation,ready:M,features:{display:E("display"),computer:E("computer"),browser:E("browser")},node:n.node,ocu:n.ocu,obu:n.obu,nativeHost:n.nativeHost,extensionDir:n.extensionDir,browser:n.browser,ffmpeg:w,ffprobe:f&&A(f)?f:null,userChrome:ss(n,i&&["node","open_browser_use"].every((c)=>a.find((_)=>_.name===c)?.state==="ready")),pulseaudio:U("pulseaudio"),xvnc:U("Xvnc"),xvfb:h,x11vnc:g,openbox:p,components:a}}function Ot(e){return os(e)?Zn():[]}function os(e){return e?.platform==="darwin-arm64"&&e.ffmpeg===b(e.root,"ffmpeg",W.version,"ffmpeg")}async function _o(e,t,n,o=fetch){try{let s=await o(e,{redirect:"follow"});if(!s.ok||!s.body)throw Error(`download failed (HTTP ${s.status}): ${e}`);let i=St("sha256"),a=vn(n,{mode:384});try{let y=s.body.getReader();for(let h=await y.read();!h.done;h=await y.read())if(i.update(h.value),!a.write(h.value))await Sn(a,"drain")}finally{a.end(),await Cn(a)}let d=i.digest("hex");if(d!==t)throw Error(`digest mismatch for ${e}: expected ${t}, got ${d}`)}catch(s){throw Pn(n,{force:!0}),s}}function is(e){return b(Mt(e),"minimal.json")}import{spawn as as}from"child_process";import{existsSync as cs}from"fs";import{connect as us}from"net";import{join as pe}from"path";var $t="reason_desktop",Q={sampleRate:48000,channels:2,codec:"opus"},ls=5000,ds=107,ps=262144,Tn=(e)=>pe(e,"native"),Ve=(e)=>`unix:${e}`;function Fe(e,t=1000){if(!cs(e))return Promise.resolve(!1);return new Promise((n)=>{let o=us({path:e}),s=(i)=>{o.destroy(),n(i)};o.setTimeout(t,()=>s(!1)),o.once("error",()=>s(!1)),o.once("close",()=>s(!1)),o.once("connect",()=>s(!0))})}async function go(e,t){if(!t)return null;let n=Tn(e);if(Buffer.byteLength(n)>ds||/["'\\\s]/.test(n))return null;try{if(await Fe(n))return n;let o=as(t,["--daemonize=no","--system=no","--use-pid-file=no","--exit-idle-time=-1","--disallow-exit=yes","--realtime=no","--high-priority=no","--disallow-module-loading=yes","--log-level=warning",`--log-target=file:${pe(e,"pulseaudio.log")}`,"-n",`--load=module-native-protocol-unix socket="${n}" auth-anonymous=1 auth-cookie-enabled=0`,`--load=module-null-sink sink_name=${$t} rate=${Q.sampleRate} channels=${Q.channels} sink_properties=device.description=Reason_desktop`],{detached:!0,stdio:"ignore",env:{HOME:e,PATH:"/usr/bin:/bin",XDG_RUNTIME_DIR:e,PULSE_RUNTIME_PATH:pe(e,"runtime"),PULSE_STATE_PATH:pe(e,"state")}}),s=!1;o.once("error",()=>{s=!0}),o.once("exit",()=>{s=!0}),o.unref();let i=Date.now()+ls;while(Date.now()<i){if(await Fe(n))return n;if(s)return await Fe(n)?n:null;await new Promise((a)=>setTimeout(a,50))}if(!s)o.kill("SIGKILL");return null}catch{return null}}function Lt(){let{sampleRate:e,channels:t}=Q;return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer","-f","pulse","-sample_rate",String(e),"-channels",String(t),"-fragment_size",String(e*t*2/50),"-i",`${$t}.monitor`,"-vn","-ac",String(t),"-ar",String(e),"-c:a","libopus","-b:a","64k","-application","lowdelay","-frame_duration","20","-flush_packets","1","-page_duration","20000","-f","ogg","pipe:1"]}var fs=[79,103,103,83],ms=Buffer.from("OpusHead"),gs=Buffer.from("OpusTags"),At=(e,t)=>e.byteLength>=t.byteLength&&t.every((n,o)=>e[o]===n);class ze extends Error{constructor(e){super(e);this.name="OggProtocolError"}}class je{buffer=new Uint8Array(0);partial=[];partialBytes=0;push(e){let t=new Uint8Array(this.buffer.byteLength+e.byteLength);t.set(this.buffer),t.set(e,this.buffer.byteLength);let n=[],o=0;while(t.byteLength-o>=27){if(fs.some((w,f)=>t[o+f]!==w)||t[o+4]!==0)throw new ze("invalid_page");let s=(t[o+5]&1)!==0,i=t[o+26];if(t.byteLength-o<27+i)break;let a=t.subarray(o+27,o+27+i),d=a.reduce((w,f)=>w+f,0),y=27+i+d;if(t.byteLength-o<y)break;if(!s&&this.partialBytes>0)this.resetPartial();let h=s&&this.partialBytes===0,g=o+27+i,p=g;for(let w of a){if(g+=w,w===255)continue;if(this.appendPartial(t.subarray(p,g),h),p=g,!h){let f=this.takePartial();if(f.byteLength>0&&!At(f,ms)&&!At(f,gs))n.push(f)}h=!1,this.resetPartial()}if(p<g)this.appendPartial(t.subarray(p,g),h);o+=y}return this.buffer=t.slice(o),n}appendPartial(e,t){if(t||e.byteLength===0)return;if(this.partialBytes+=e.byteLength,this.partialBytes>ps)throw new ze("packet_too_large");this.partial.push(e.slice())}takePartial(){if(this.partial.length===1)return this.partial[0];let e=new Uint8Array(this.partialBytes),t=0;for(let n of this.partial)e.set(n,t),t+=n.byteLength;return e}resetPartial(){this.partial=[],this.partialBytes=0}}import{spawn as hs}from"child_process";var Nt=1048576,bs=String.raw`
80
+ `}function ns(e){let t=He(e),n=t?.allowed_origins;return t!==null&&t.name===It&&t.type==="stdio"&&Array.isArray(n)&&n.includes(`chrome-extension://${We}/`)&&typeof t.path==="string"&&Tt(t.path)}function ss(e,t){if(!e.userChromeHost||!e.userChromeRegistration)return null;if(!t||Kn(e.userChromeHost)!==ts(e.nativeHost)||!Tt(e.userChromeHost))return{code:"user_chrome_browser_use_missing"};return ns(e.userChromeRegistration)?{host:e.userChromeHost}:{code:"user_chrome_native_host_unregistered"}}var rs={display:["display","desktop_session","desktop_video"],computer:["display","desktop_session","system_packages","node","open_computer_use"],browser:["display","desktop_session","system_packages","node","open_computer_use","open_browser_use","browser_extension","browser","chrome_for_testing"]};function x(e={}){let t=e.platform===void 0?Gn():e.platform;if(!t)return null;let n=Tr(t,e.home),o=Wn(n.receipt),s=Vn(t),i=o!==null&&o.platform===t&&JSON.stringify(Object.entries(o.pins).sort())===JSON.stringify(Object.entries(s).sort()),a=[],d=de(t);for(let c of["node","open_computer_use","open_browser_use","chrome_for_testing"]){let _=d[c];if(!_)continue;let v=qn(c,b(n.root,c,_.version),t),D=o?.pins[c],L=v&&D===s[c]?"ready":D!==void 0&&D!==s[c]?"outdated":"missing";a.push({name:c,state:L,detail:_.version})}let y=o?.pins.extension===F&&es(n);a.push({name:"browser_extension",state:y?"ready":"missing",detail:F});let h=U("Xvfb"),g=U("x11vnc"),p=U("openbox");if(K(t))a.push(yt()?{name:"desktop_session",state:"ready",detail:"signed-in desktop session"}:{name:"desktop_session",state:"missing",detail:"run the worker in the signed-in desktop session, not as a service"}),a.push(n.ffmpeg&&A(n.ffmpeg)?{name:"desktop_video",state:"ready",detail:n.ffmpeg}:{name:"desktop_video",state:"missing",detail:"run `reason desktop install` for desktop video"});else if(t!=="darwin-arm64"){a.push(A(ce)?{name:"browser",state:"ready",detail:ce}:{name:"browser",state:"missing",detail:`non-snap Chromium at ${ce}`});let c=h!==null&&g!==null&&p!==null;a.push({name:"display",state:c?"ready":"missing",detail:"Xvfb + openbox + x11vnc"});let _=Hn.filter((P)=>U(P)===null),v=(o?.missing_system_packages??kt).filter((P)=>kt.includes(P)),D=_.length===0&&v.length===0;a.push(D?{name:"system_packages",state:"ready"}:{name:"system_packages",state:"missing",detail:[...new Set([...v,..._])].join(" ")});let L=Ue.filter((P)=>U(P)===null);a.push(L.length===0?{name:"desktop_look",state:"ready"}:{name:"desktop_look",state:"missing",detail:L.join(" ")})}let w=n.ffmpeg&&A(n.ffmpeg)?n.ffmpeg:U("ffmpeg"),f=!w?null:w===n.ffmpeg?n.ffprobe:b(vt(En(w)),"ffprobe"),M=i&&a.every((c)=>c.state==="ready"),E=(c)=>i&&a.every((_)=>!rs[c].includes(_.name)||_.state==="ready");return{platform:t,root:n.root,automation:n.automation,ready:M,features:{display:E("display"),computer:E("computer"),browser:E("browser")},node:n.node,ocu:n.ocu,obu:n.obu,nativeHost:n.nativeHost,extensionDir:n.extensionDir,browser:n.browser,ffmpeg:w,ffprobe:f&&A(f)?f:null,userChrome:ss(n,i&&["node","open_browser_use"].every((c)=>a.find((_)=>_.name===c)?.state==="ready")),pulseaudio:U("pulseaudio"),xvnc:U("Xvnc"),xvfb:h,x11vnc:g,openbox:p,components:a}}function Ot(e){return os(e)?Zn():[]}function os(e){return e?.platform==="darwin-arm64"&&e.ffmpeg===b(e.root,"ffmpeg",W.version,"ffmpeg")}async function yo(e,t,n,o=fetch){try{let s=await o(e,{redirect:"follow"});if(!s.ok||!s.body)throw Error(`download failed (HTTP ${s.status}): ${e}`);let i=St("sha256"),a=vn(n,{mode:384});try{let y=s.body.getReader();for(let h=await y.read();!h.done;h=await y.read())if(i.update(h.value),!a.write(h.value))await Sn(a,"drain")}finally{a.end(),await Cn(a)}let d=i.digest("hex");if(d!==t)throw Error(`digest mismatch for ${e}: expected ${t}, got ${d}`)}catch(s){throw Pn(n,{force:!0}),s}}function is(e){return b(Mt(e),"minimal.json")}import{spawn as as}from"child_process";import{existsSync as cs}from"fs";import{connect as us}from"net";import{join as pe}from"path";var $t="reason_desktop",Q={sampleRate:48000,channels:2,codec:"opus"},ls=5000,ds=107,ps=262144,Tn=(e)=>pe(e,"native"),Ve=(e)=>`unix:${e}`;function Fe(e,t=1000){if(!cs(e))return Promise.resolve(!1);return new Promise((n)=>{let o=us({path:e}),s=(i)=>{o.destroy(),n(i)};o.setTimeout(t,()=>s(!1)),o.once("error",()=>s(!1)),o.once("close",()=>s(!1)),o.once("connect",()=>s(!0))})}async function _o(e,t){if(!t)return null;let n=Tn(e);if(Buffer.byteLength(n)>ds||/["'\\\s]/.test(n))return null;try{if(await Fe(n))return n;let o=as(t,["--daemonize=no","--system=no","--use-pid-file=no","--exit-idle-time=-1","--disallow-exit=yes","--realtime=no","--high-priority=no","--disallow-module-loading=yes","--log-level=warning",`--log-target=file:${pe(e,"pulseaudio.log")}`,"-n",`--load=module-native-protocol-unix socket="${n}" auth-anonymous=1 auth-cookie-enabled=0`,`--load=module-null-sink sink_name=${$t} rate=${Q.sampleRate} channels=${Q.channels} sink_properties=device.description=Reason_desktop`],{detached:!0,stdio:"ignore",env:{HOME:e,PATH:"/usr/bin:/bin",XDG_RUNTIME_DIR:e,PULSE_RUNTIME_PATH:pe(e,"runtime"),PULSE_STATE_PATH:pe(e,"state")}}),s=!1;o.once("error",()=>{s=!0}),o.once("exit",()=>{s=!0}),o.unref();let i=Date.now()+ls;while(Date.now()<i){if(await Fe(n))return n;if(s)return await Fe(n)?n:null;await new Promise((a)=>setTimeout(a,50))}if(!s)o.kill("SIGKILL");return null}catch{return null}}function Lt(){let{sampleRate:e,channels:t}=Q;return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer","-f","pulse","-sample_rate",String(e),"-channels",String(t),"-fragment_size",String(e*t*2/50),"-i",`${$t}.monitor`,"-vn","-ac",String(t),"-ar",String(e),"-c:a","libopus","-b:a","64k","-application","lowdelay","-frame_duration","20","-flush_packets","1","-page_duration","20000","-f","ogg","pipe:1"]}var fs=[79,103,103,83],ms=Buffer.from("OpusHead"),gs=Buffer.from("OpusTags"),At=(e,t)=>e.byteLength>=t.byteLength&&t.every((n,o)=>e[o]===n);class ze extends Error{constructor(e){super(e);this.name="OggProtocolError"}}class je{buffer=new Uint8Array(0);partial=[];partialBytes=0;push(e){let t=new Uint8Array(this.buffer.byteLength+e.byteLength);t.set(this.buffer),t.set(e,this.buffer.byteLength);let n=[],o=0;while(t.byteLength-o>=27){if(fs.some((w,f)=>t[o+f]!==w)||t[o+4]!==0)throw new ze("invalid_page");let s=(t[o+5]&1)!==0,i=t[o+26];if(t.byteLength-o<27+i)break;let a=t.subarray(o+27,o+27+i),d=a.reduce((w,f)=>w+f,0),y=27+i+d;if(t.byteLength-o<y)break;if(!s&&this.partialBytes>0)this.resetPartial();let h=s&&this.partialBytes===0,g=o+27+i,p=g;for(let w of a){if(g+=w,w===255)continue;if(this.appendPartial(t.subarray(p,g),h),p=g,!h){let f=this.takePartial();if(f.byteLength>0&&!At(f,ms)&&!At(f,gs))n.push(f)}h=!1,this.resetPartial()}if(p<g)this.appendPartial(t.subarray(p,g),h);o+=y}return this.buffer=t.slice(o),n}appendPartial(e,t){if(t||e.byteLength===0)return;if(this.partialBytes+=e.byteLength,this.partialBytes>ps)throw new ze("packet_too_large");this.partial.push(e.slice())}takePartial(){if(this.partial.length===1)return this.partial[0];let e=new Uint8Array(this.partialBytes),t=0;for(let n of this.partial)e.set(n,t),t+=n.byteLength;return e}resetPartial(){this.partial=[],this.partialBytes=0}}import{spawn as hs}from"child_process";var Nt=1048576,bs=String.raw`
81
81
  import gi, json, os, sys
82
82
  gi.require_version("Gtk", "3.0")
83
83
  from gi.repository import Gtk, Gdk, GLib
@@ -123,4 +123,4 @@ Gtk.main()
123
123
  `)){let M=i.slice(0,f);i=i.slice(f+1);let E;try{E=JSON.parse(M)}catch{g();return}if(E==="ready"||E==="ack"){clearTimeout(y),s=!1;while(!s&&!o&&d.length){let c=d.shift();a-=c.bytes,c.apply()}}else if(E&&typeof E==="object"&&"text"in E&&typeof E.text==="string"&&Buffer.byteLength(E.text)<=S)t.clipboard(E.text);else{g();return}if(o)return}if(i.length>S*6+32)g()}),n.stdin.on("error",g),n.once("error",g),n.once("exit",g),{apply:p,write(w){if(Buffer.byteLength(w)>S||w.includes("\x00")){g();return}let f=`${JSON.stringify(w)}
124
124
  `;p(()=>{if(s=!0,y=setTimeout(()=>g(),5000),n.stdin.write(f),n.stdin.writableLength>Nt)h(),t.end({reason:"input_backpressure"})},Buffer.byteLength(f))},close:h}}var X={smooth:{fps:60,crf:23,kbps:8000,x264Preset:"ultrafast",threads:2,scale:1},sharp:{fps:30,crf:19,kbps:1e4,x264Preset:"superfast",scale:1},data_saver:{fps:20,crf:28,kbps:2000,x264Preset:"ultrafast",scale:0.75},balanced:{fps:30,crf:23,kbps:4000,x264Preset:"ultrafast",threads:2,scale:1}},_s="avc1.4D002A",Bt={width:1920,height:1080},ks=262144,Ss=0.2,vs=250,Es=1e4,Ds=1024,Ke=1e4,Is=500,Ps=60,Cs=1e4,Rs=1000,Ft=1048576,Ms=-223,Ts=-308,In={kind:"mac_screen",sound:null},Dn={kind:"windows_screen",sound:null},Os,zt=()=>Os??=x()?.ffmpeg??null,me=(e,t,n)=>qe(e,t,{env:n,stdio:["ignore","pipe","ignore"],windowsHide:!0}),As,Ye=()=>As??=Ot(x()),jt=(e,t,n)=>{let[o,...s]=[...Ye(),e];return me(o,[...s,...t],n)},Gt=()=>nn?.videotoolbox?"h264_videotoolbox":"libx264",$s=()=>Math.round(performance.now()*1000),Xe=new Set,Vt=!1;function Jt(e){if(Xe.add(e),e.once("exit",()=>Xe.delete(e)),Vt)return;Vt=!0,process.once("exit",()=>{for(let t of Xe)try{t.kill("SIGKILL")}catch{}})}function Zt(e){try{e.stdout?.destroy()}catch{}if(e.exitCode!==null||e.signalCode!==null)return;try{e.kill("SIGTERM")}catch{return}let t=setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{e.kill("SIGKILL")}catch{}},Is);e.once("exit",()=>clearTimeout(t))}function Ls(e,t,n){return{args:["-f","x11grab","-draw_mouse","1","-framerate",String(e),"-video_size",`${t.width}x${t.height}`,"-i",n],size:t}}function Ns(e){return{args:["-f","avfoundation","-capture_cursor","1","-pixel_format","nv12","-framerate",String(e),"-i","Capture screen 0:none"],size:null}}function Us(e,t){return{args:["-f","gdigrab","-draw_mouse","1","-framerate",String(e),"-offset_x","0","-offset_y","0","-video_size",`${t.width}x${t.height}`,"-i","desktop"],size:t}}function Bs(e){return{args:["-probesize","32","-analyzeduration","0","-f","image2pipe","-c:v","mjpeg","-framerate",String(e),"-i","pipe:0"],size:null}}var Qt=1700000;function en(e){return Math.min(1,Math.round(Math.sqrt(Qt/(e.width*e.height))*100)/100)}function Hs(e,t,n){let o=qe(n.axe,["stream-video","--udid",n.udid,"--format","ffmpeg","--fps","30","--quality","85","--scale",String(Math.min(0.99,en(n.size)))],{stdio:["ignore","pipe","ignore"]}),s=qe(e,t,{env:{},stdio:["pipe","pipe","ignore"]});o.stdout.pipe(s.stdin),s.stdin.on("error",()=>{});let i=()=>{if(o.exitCode===null&&o.signalCode===null)o.kill("SIGTERM")};return s.once("exit",i),s.once("error",i),o.once("exit",()=>{if(s.exitCode===null&&s.signalCode===null)s.kill("SIGTERM")}),o.once("error",()=>{if(s.exitCode===null&&s.signalCode===null)s.kill("SIGTERM")}),s}function Kt(e){let t=Math.min(1,Bt.width/e.width,Bt.height/e.height);return{width:Math.round(e.width*t),height:Math.round(e.height*t)}}function fe(e,t,n,o="libx264"){let s=X[e],i=(p)=>Math.max(2,Math.floor(p/2)*2),a={width:i(n.width*s.scale),height:i(n.height*s.scale)},d=a.width!==t.size?.width||a.height!==t.size.height,y=Math.max(1,Math.round(s.kbps*2/s.fps)),h=["-g",String(s.fps*Ps)],g=o==="h264_videotoolbox"?["-c:v","h264_videotoolbox","-realtime","1","-prio_speed","1","-allow_sw","1","-profile:v","main","-level","4.2","-bf","0","-pix_fmt","nv12",...h,"-b:v",`${s.kbps}k`,"-maxrate",`${s.kbps}k`,"-bufsize",`${y}k`,"-bsf:v","h264_metadata=aud=insert"]:["-c:v","libx264","-preset",s.x264Preset,"-tune","zerolatency","-profile:v","main","-level","4.2","-bf","0","-pix_fmt","yuv420p",...s.threads?["-threads",String(s.threads)]:[],"-x264-params","aud=1:repeat-headers=1",...h,"-crf",String(s.crf),"-maxrate",`${s.kbps}k`,"-bufsize",`${y}k`];return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer",...t.args,"-an",...d?["-vf",`scale=${a.width}:${a.height}:flags=fast_bilinear`]:[],...g,"-flush_packets","1","-f","h264","pipe:1"]}class tn{buffer=new Uint8Array(0);scanned=0;key=!1;micros=0;push(e,t){if(this.buffer.byteLength===0)this.micros=t;let n=new Uint8Array(this.buffer.byteLength+e.byteLength);n.set(this.buffer),n.set(e,this.buffer.byteLength),this.buffer=n;let o=[],s=this.scanned;while(s+3<this.buffer.byteLength){if(this.buffer[s]!==0||this.buffer[s+1]!==0||this.buffer[s+2]!==1){s++;continue}let i=this.buffer[s+3]&31,a=s>0&&this.buffer[s-1]===0?s-1:s;if(i===9&&a>0)o.push({data:this.buffer.slice(0,a),key:this.key,micros:this.micros}),this.buffer=this.buffer.subarray(a),this.key=!1,this.micros=t,s-=a;if(i===5)this.key=!0;s+=3}return this.scanned=s,o}}function Fs(e,t){let n=xs({path:e}),o=Buffer.alloc(0),s="version",i=0,a=!1,d=[],y=0,h=!1,g=(c)=>{if(h)return;h=!0,n.destroy(),t.end(c)},p=()=>g({reason:"display_protocol"}),w=(c)=>{if(h)return;if(!a){if(y+=c.byteLength,y>Ft)g({reason:"input_backpressure"});else d.push(c);return}if(n.write(c),n.writableLength>Ft)g({reason:"input_backpressure"})},f=(c)=>{o=o.subarray(c)},M=()=>{switch(s){case"version":{if(o.byteLength<12)return!1;let c=/^RFB (\d{3})\.(\d{3})\n$/.exec(o.subarray(0,12).toString("latin1"));if(!c||Number(c[1])*1000+Number(c[2])<3007)return p(),!1;return f(12),n.write(`RFB 003.007
125
125
  `),s="security",!0}case"security":{if(o.byteLength<1)return!1;let c=o[0];if(c===0)return p(),!1;if(o.byteLength<1+c)return!1;if(!o.subarray(1,1+c).includes(1))return p(),!1;return f(1+c),n.write(Buffer.from([1,1])),s="init",!0}case"init":{if(o.byteLength<24)return!1;let c=o.readUInt32BE(20);if(c>65536)return p(),!1;if(o.byteLength<24+c)return!1;let _={width:o.readUInt16BE(0),height:o.readUInt16BE(2)};if(f(24+c),_.width===0||_.height===0)return p(),!1;s="messages";let v=Buffer.alloc(12);v.writeUInt8(2,0),v.writeUInt16BE(2,2),v.writeInt32BE(Ts,4),v.writeInt32BE(Ms,8),n.write(v),a=!0;for(let D of d)n.write(D);return d=[],y=0,t.ready(_),!h}case"skip":{let c=Math.min(i,o.byteLength);if(f(c),i-=c,i>0)return!1;return s="messages",!0}case"messages":{if(o.byteLength<1)return!1;switch(o[0]){case 1:{if(o.byteLength<6)return!1;let c=6+o.readUInt16BE(4)*6;if(o.byteLength<c)return!1;return f(c),!0}case 2:return f(1),!0;case 3:{if(o.byteLength<8)return!1;let c=o.readUInt32BE(4);if(c>S/2)return f(8),s="skip",i=c,!0;if(o.byteLength<8+c)return!1;let _=o.subarray(8,8+c).toString("latin1");return f(8+c),t.clipboard(_),!h}default:return p(),!1}}}},E=!1;return n.once("connect",()=>{E=!0}),n.on("data",(c)=>{if(h)return;o=o.byteLength?Buffer.concat([o,c]):c;while(!h&&M());}),n.once("error",()=>{if(!E)g({error:new r("display_unavailable","Reason could not reach this machine's desktop server.")})}),n.once("close",()=>g({reason:"display_closed"})),{pointer(c,_,v){let D=Buffer.alloc(6);D.writeUInt8(5,0),D.writeUInt8(v&255,1),D.writeUInt16BE(c,2),D.writeUInt16BE(_,4),w(D)},key(c,_){let v=Buffer.alloc(8);v.writeUInt8(4,0),v.writeUInt8(c?1:0,1),v.writeUInt32BE(_>>>0,4),w(v)},clipboard(c){if(Array.from(c).some((D)=>D.codePointAt(0)>255)){g({reason:"clipboard_unicode_unsupported"});return}let _=Buffer.from(c,"latin1"),v=Buffer.alloc(8);v.writeUInt8(6,0),v.writeUInt32BE(_.byteLength,4),w(Buffer.concat([v,_]))},close(){h=!0,n.destroy()}}}class Je{run=null;viewers=new Set;get running(){return this.run!==null}start(e,t,n,o){this.viewers.add(e),this.stop();let s;try{s=n()}catch{this.fail();return}Jt(s);let i={child:s,splitter:new tn};this.run=i;for(let d of[...this.viewers])d.started(t);s.stdout?.on("data",(d)=>{if(this.run!==i)return;for(let y of i.splitter.push(d,o()))for(let h of[...this.viewers])h.unit(y)});let a=()=>{if(this.run!==i)return;this.run=null,this.fail()};s.once("exit",a),s.once("error",a)}leave(e){if(!this.viewers.delete(e))return;if(this.viewers.size===0)this.stop()}stop(){if(!this.run)return;Zt(this.run.child),this.run=null}fail(){for(let e of[...this.viewers])e.failed()}}var Xt=new WeakMap;function zs(e){let t=Xt.get(e);if(!t)Xt.set(e,t=new Je);return t}var ee=new Map;function On(e,t,n={}){let o=n.micros??$s,s=new Bn,i=t.request.preset,a=null,d=null,y=null,h=!1,g=null,p=!1,w=!1,f=null,M=0,E=0,c=!1,_=null,v=null,D=0,L=null,P=[],te=0,N=[],Ze=new Uint32Array(Ke+1),ge=0,he=null,be=0,q=0,ye=0,Qe=0,et=0,ne=null,we=0,j={frames:0,bytes:0,since:o()},G=[],Y=0,xe,_e=!1,rn=o(),R={},V=()=>Math.round((o()-rn)/1000),tt=n.control??ut,ke=null,Se=null,nt=0,ve=!1,st={pause(){if(!g?.running)return;g.stop(),ve=!0},adopt(u){let l=u!==null&&(u.width!==d?.width||u.height!==d?.height);if(l)d=u;if(!l&&!ve)return;if(ve=!1,g)ae();else Ie()}},on=(u)=>{if(!n.resizeDesktop||!a||"kind"in a||e.done)return;let l=a.display,m=()=>[...ee.get(l)??[]];nt++,n.resizeDesktop(a,u,()=>{for(let k of m())k.pause()}).then((k)=>{for(let I of m())I.adopt(k)})},T=(u)=>{let l=Wt(u);return e.send(l),Qe+=l.byteLength,l.byteLength},se=(u)=>{if(e.done)return;if(e.open)T({type:"error",code:u});e.end({reason:u})},re=()=>Math.max(ks,X[i].kbps*1000/8*Ss),oe=()=>o()/1000,an=()=>{while(N.length>1&&N[0].atMs<oe()-Es)N.shift();return N[0]?.rttMs??null},rt=(u)=>{let l=an();if(l===null||P.length===0)return!1;let m=(l+vs)*u;return oe()-P[0].sentMs>m||te>m/1000*X[i].kbps*1000/8},cn=(u)=>{if(D===0)return;let l=Math.min(u,D-1);if(L!==null&&l<=L)return;L=l;let m=oe();while(P.length&&P[0].seq<=l){let k=P.shift();if(te-=k.bytes,k.seq!==l)continue;let I=Math.max(0,m-k.sentMs);while(N.length&&N.at(-1).rttMs>=I)N.pop();N.push({atMs:m,rttMs:I}),Ze[Math.min(Ke,Math.round(I))]++,ge++,he=Math.min(he??I,I)}},un=()=>{let u=0;for(let l=0;l<=Ke;l++)if(u+=Ze[l],u*2>=ge)return l;return 0},ln=()=>e.bufferedAmount<=re()/2&&!rt(0.5),ot=()=>{_e=!0,G=[],Y=0,g?.leave(Ee),g=null},it=(u)=>{if(e.done)return;if(u.key)R.first_key_ms??=V();if(!h){if(!g||G.length===0&&!u.key)return;if(G.push(u),Y+=u.data.byteLength,Y>re())ot();return}if(c){q++;return}if(e.bufferedAmount>re()||rt(1)){c=!0,q++,_=setInterval(()=>{if(e.done||!ln())return;if(_)clearInterval(_);_=null,c=!1,ae()},n.drainPollMs??25);return}if(!p){if(!u.key){q++;return}if(T({type:"hello",width:d.width,height:d.height,fps:X[i].fps,preset:i,codec:_s}),p=!0,R.first_frame_ms??=V(),!w&&a?.sound)T({type:"audioHello",...Q}),w=!0}let l=T({type:"frame",key:u.key,seq:D,captureMicros:u.micros,data:u.data});if(P.push({seq:D,sentMs:oe(),bytes:l}),te+=l,P.length>Ds)te-=P.shift().bytes;D++,be++,ne??=u.micros,we=u.micros,j.frames++,j.bytes+=l},Ee={started(u){i=u,p=!1,G=[],Y=0},unit:it,failed:()=>se("encoder_failed")},De=()=>{let u=(n.ffmpeg??zt)();if(!a||!d){se("encoder_failed");return}let[l,m]=[a,d],k="kind"in l&&l.kind==="simulator"?l.stream:null;if(!u&&!k){se("encoder_failed");return}if(g??="kind"in l&&l.kind==="mac_screen"?zs(n.spawn??jt):new Je,R.encoder_ms===void 0)R.encoder_ms=V(),R.encoder_shared=g.running;g.start(Ee,i,()=>{let I=X[i].fps;if(k)return k(I,X[i].kbps,Qt);if("kind"in l&&l.kind==="simulator"){let C=Math.min(0.99,en(l.size)),B={width:l.size.width*C,height:l.size.height*C};return Hs(u,fe(i,Bs(Math.min(I,30)),B,(n.macEncoder??Gt)()),l)}if("kind"in l&&l.kind==="windows_screen")return(n.spawn??me)(u,fe(i,Us(I,m),Kt(m)),{SystemRoot:process.env.SystemRoot??"C:\\Windows"});return"kind"in l?(n.spawn??jt)(u,fe(i,Ns(I),Kt(m),(n.macEncoder??Gt)()),{}):(n.spawn??me)(u,fe(i,Ls(I,m,l.display),m),{DISPLAY:l.display,XAUTHORITY:l.xauthority})},o)},ie=()=>{if(!f)return;Zt(f.child),f=null},dn=()=>{let u=(n.ffmpeg??zt)();if(f||e.done||!w||!a?.sound||!u)return;let l;try{l=(n.spawn??me)(u,Lt(),{PULSE_SERVER:Ve(a.sound)})}catch{return}Jt(l);let m={child:l,reader:new je};f=m,l.stdout?.on("data",(I)=>{if(f!==m||e.done)return;let C;try{C=m.reader.push(I)}catch{ie();return}let B=o();for(let Ce of C){if(e.bufferedAmount>re()){E++;continue}T({type:"audio",captureMicros:B,data:Ce}),M++}});let k=()=>{if(f===m)ie()};l.once("exit",k),l.once("error",k)},ae=()=>{if(!g||e.done)return;ye++,De()},Ie=()=>{if(e.done||!d)return;if(!h){if(g||_e)return;De(),xe=setTimeout(()=>{if(!h)ot()},Cs);return}if(clearTimeout(xe),R.encoder_early===void 0){if(R.encoder_early=g!==null,_e)R.hold_lapsed=!0}if(!g)De();let u=G;G=[],Y=0;for(let l of u)it(l);v??=setInterval(()=>{let l=o(),m=Math.max(0.001,(l-j.since)/1e6);T({type:"stats",stats:{fps:Math.round(j.frames/m*10)/10,kbps:Math.round(j.bytes*8/1000/m),dropped:q,restarts:ye,queued_bytes:e.bufferedAmount}}),j={frames:0,bytes:0,since:l}},Rs)};t.desktop.then((u)=>{if(e.done)return;a=u;let l={ready(m){d=m,R.desktop_ms??=V(),Ie()},clipboard(m){if(e.open&&Buffer.byteLength(m)<=S)T({type:"serverClipboard",text:m})},end(m){if("reason"in m&&e.open)T({type:"error",code:m.reason});e.end(m)}};if("kind"in u&&u.kind==="simulator")y=u.input,l.ready(u.points);else if("kind"in u&&u.kind==="windows_screen")y=(n.windowsInput??xt)(l);else if("kind"in u)y=(n.macInput??((m)=>jn(m,Ye())))(l);else{let m=ee.get(u.display);if(!m)ee.set(u.display,m=new Set);m.add(st);let k=(n.linuxClipboard??Ut)(u,l),I=Fs(u.rfbSocket,{...l,clipboard:(C)=>{if(!k)l.clipboard(C)}});y=k?{pointer:(C,B,Ce)=>k.apply(()=>I.pointer(C,B,Ce)),key:(C,B)=>k.apply(()=>I.key(C,B)),clipboard:(C)=>k.write(C),close(){k.close(),I.close()}}:I}at()},(u)=>e.end({error:u}));function at(){if(Se||!t.viewerSameNetwork||!h||e.done||!a||!("kind"in a)||a.kind!=="mac_screen")return;Se=(n.macWindows??Fn)((u)=>{if(e.open)T({type:"windows",bounds:u})})}let ct={viewer:t.viewer??null,notify(u){if(e.open)T({type:"control",control:u})}},Pe=(u)=>{if(!y)return;if(!a||!("kind"in a)||a.kind!=="simulator")tt.claim(ct);u(y)};return{opened(){R.relay_ms??=V()},received(u){et+=u.byteLength;let l;try{l=s.push(u)}catch{se("viewer_protocol");return}for(let m of l){if(e.done)return;switch(m.type){case"ping":T({type:"pong",token:m.token});break;case"pointer":Pe((k)=>k.pointer(m.x,m.y,m.buttons));break;case"key":Pe((k)=>k.key(m.down,m.keysym));break;case"clientClipboard":Pe((k)=>k.clipboard(m.text));break;case"config":if(m.preset!==i)i=m.preset,ae();break;case"keyframeRequest":if(p&&!c)ae();break;case"ack":cn(m.seq);break;case"audioEnable":if(m.on)dn();else ie();break;case"resize":on({width:m.width,height:m.height});break;default:break}}if(!h&&!e.done){if(h=!0,R.viewer_ms=V(),t.viewer)ke=tt.join(ct);Ie(),at()}},close(){if(a&&!("kind"in a)){let u=ee.get(a.display);if(u?.delete(st),u?.size===0)ee.delete(a.display)}if(ke?.(),ke=null,Se?.close(),_)clearInterval(_);if(v)clearInterval(v);clearTimeout(xe),g?.leave(Ee),ie(),y?.close()},summary:()=>({output_bytes:Qe,input_bytes:et,video:{preset:i,frames:be,dropped:q,restarts:ye,avg_fps:ne!==null&&we>ne?Math.round((be-1)/((we-ne)/1e6)*10)/10:0,min_rtt_ms:Math.round(he??0),p50_rtt_ms:ge?un():0,audio_packets:M,audio_dropped:E,resizes:nt,connect:R}})}}var qt=null,nn=null,js=null,Gs=null;function Vs(){let e=x();return e?.features.display?e.ffmpeg:null}function sn(e){return qt??=new Promise((t)=>{ys(e,["-hide_banner","-encoders"],{env:{},timeout:5000,killSignal:"SIGKILL",maxBuffer:1048576,encoding:"utf8"},(n,o)=>{let s=(i)=>!n&&new RegExp(`^\\s*V\\S*\\s+${i}\\s`,"m").test(o);t(nn={x264:s("libx264"),videotoolbox:s("h264_videotoolbox")})})}),qt}var Yt=null;function Nn(){return Yt??=(async()=>{let e=[x()?.ffmpeg,"/opt/homebrew/bin/ffmpeg","/usr/local/bin/ffmpeg"].find((n)=>Boolean(n&&ws(n)));if(!e)return null;let t=await sn(e);return t.videotoolbox||t.x264?e:null})(),Yt}function Rr(e=process.platform,t={}){if(e!=="linux"&&e!=="darwin"&&e!=="win32")return Promise.resolve(!1);let n=(t.ffmpeg??Vs)();if(!n)return Promise.resolve(!1);let o=(t.encoders??sn)(n);if(e==="linux")return o.then((i)=>i.x264);if(e==="win32"){let i=t.windowsScreen?t.windowsScreen():Gs??=bt();return Promise.all([o,i]).then(([a,d])=>a.x264&&(d?.session??0)>0)}let s=t.macScreen?t.macScreen():js??=Ge(Ye());return Promise.all([o,s]).then(([i,a])=>(i.x264||i.videotoolbox)&&a?.screen===!0&&a.accessibility)}
126
- export{We,mo,F,Tn,Ve,go,In,Dn,On,Nn,Rr,Ht,Tr,x,_o};
126
+ export{We,go,F,Tn,Ve,_o,In,Dn,On,Nn,Rr,Ht,Tr,x,yo};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{R}from"./vm-hands-entry-lite-a3p6xz53.js";import{Fo}from"./vm-hands-entry-lite-mc5y3xr9.js";import{Fe,un,Dt,dn}from"./vm-hands-entry-lite-jzmrhjkz.js";import{Qn}from"./vm-hands-entry-lite-j1hddtjs.js";import{t,o,d,u,i,gs,W,g,s,n}from"./vm-hands-entry-lite-bjtcy8n6.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&&!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 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}})}}
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-wgsdpq31.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
3
  export{ot,D,Ps,rs};
@@ -1,3 +1,3 @@
1
1
  // @bun
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 Uo(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=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 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,Uo,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 $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 ko="windows",Co="v1",Ao="look",Po="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 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:$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`
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,$n,ko,Co,Ao,Po,Mn,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};