@reason-machines/cli-linux-x64 0.2.520 → 0.2.522

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 (106) hide show
  1. package/bin/reason +2 -2
  2. package/bin/vm-hands/api-credentials-4q4j6kx0.js +2 -0
  3. package/bin/vm-hands/api-jbq4mscd.js +2 -0
  4. package/bin/vm-hands/connect-cli-4g0wanfs.js +2 -0
  5. package/bin/vm-hands/credentials-md79hkqh.js +2 -0
  6. package/bin/vm-hands/custom-endpoint-device-hzgdnyx2.js +2 -0
  7. package/bin/vm-hands/desktop-account-gm7m5bwr.js +2 -0
  8. package/bin/vm-hands/{fsevents-sw63c1nr.js → fsevents-fev1pxw2.js} +1 -1
  9. package/bin/vm-hands/grok-dock-browser-pzw59wnd.png +0 -0
  10. package/bin/vm-hands/grok-dock-files-eckq444x.png +0 -0
  11. package/bin/vm-hands/grok-dock-terminal-hcpz3e43.png +0 -0
  12. package/bin/vm-hands/grok-wallpaper-71zwn2pj.jpg +0 -0
  13. package/bin/vm-hands/{hands-worker-source-h0qmr1jt.js → hands-worker-source-hzkacxxz.js} +1 -1
  14. package/bin/vm-hands/{index-j4gb3cze.js → index-gmsadq51.js} +4 -4
  15. package/bin/vm-hands/install-receipt-qtwtzafq.js +2 -0
  16. package/bin/vm-hands/local-automation-6vzg71yj.js +2 -0
  17. package/bin/vm-hands/local-capabilities-47zzxtv9.js +2 -0
  18. package/bin/vm-hands/local-desktop-users-qdpbfh6s.js +2 -0
  19. package/bin/vm-hands/local-display-mac-4654wqzs.js +2 -0
  20. package/bin/vm-hands/local-display-session-n9jw5nf3.js +2 -0
  21. package/bin/vm-hands/local-display-video-80nbkta7.js +2 -0
  22. package/bin/vm-hands/local-managed-process-js1zp3c3.js +2 -0
  23. package/bin/vm-hands/local-pty-session-s60ca00y.js +2 -0
  24. package/bin/vm-hands/managed-runtime-paqtph38.js +2 -0
  25. package/bin/vm-hands/network-contract-5wc6wbn2.js +2 -0
  26. package/bin/vm-hands/package-way7qesn.js +2 -0
  27. package/bin/vm-hands/permissions-7kac0k3h.js +2 -0
  28. package/bin/vm-hands/{reason-hands-protocol-6fxcbhzd.js → reason-hands-protocol-zffy7kc8.js} +1 -1
  29. package/bin/vm-hands/serve-service-yz2zdd2x.js +2 -0
  30. package/bin/vm-hands/{status-exfqneat.js → status-5zp28s1d.js} +1 -1
  31. package/bin/vm-hands/version-tvtjsedm.js +2 -0
  32. package/bin/vm-hands/vm-hands-entry-lite-0emgrj8j.js +2 -0
  33. package/bin/vm-hands/{vm-hands-entry-lite-wzq3qsh1.js → vm-hands-entry-lite-0tavq3p4.js} +2 -2
  34. package/bin/vm-hands/{vm-hands-entry-lite-qz74j563.js → vm-hands-entry-lite-1kt82jes.js} +2 -2
  35. package/bin/vm-hands/{vm-hands-entry-lite-x39tvhjw.js → vm-hands-entry-lite-3wra0xtg.js} +1 -1
  36. package/bin/vm-hands/{vm-hands-entry-lite-70x16hkx.js → vm-hands-entry-lite-4cdn822w.js} +3 -3
  37. package/bin/vm-hands/{vm-hands-entry-lite-bp8kdega.js → vm-hands-entry-lite-59typww6.js} +3 -3
  38. package/bin/vm-hands/{vm-hands-entry-lite-qxeegp2n.js → vm-hands-entry-lite-5wsygx6n.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-ce250nr7.js → vm-hands-entry-lite-70n3bmjz.js} +4 -4
  40. package/bin/vm-hands/{vm-hands-entry-lite-7ek99e0k.js → vm-hands-entry-lite-7pne9e2e.js} +2 -2
  41. package/bin/vm-hands/{vm-hands-entry-lite-029385a5.js → vm-hands-entry-lite-82ky5wgg.js} +2 -2
  42. package/bin/vm-hands/{vm-hands-entry-lite-ydgedg8n.js → vm-hands-entry-lite-88yjxxvf.js} +5 -5
  43. package/bin/vm-hands/{vm-hands-entry-lite-q3dr2sz2.js → vm-hands-entry-lite-956sjtet.js} +4 -4
  44. package/bin/vm-hands/{vm-hands-entry-lite-148nz8be.js → vm-hands-entry-lite-9x81cr3a.js} +3 -3
  45. package/bin/vm-hands/{vm-hands-entry-lite-fcvf8md1.js → vm-hands-entry-lite-a3p6xz53.js} +2 -2
  46. package/bin/vm-hands/{vm-hands-entry-lite-dcrz19xf.js → vm-hands-entry-lite-a6w60nv9.js} +3 -3
  47. package/bin/vm-hands/{vm-hands-entry-lite-wx1fmrbs.js → vm-hands-entry-lite-bvqwsd3b.js} +3 -3
  48. package/bin/vm-hands/{vm-hands-entry-lite-fgppp6x9.js → vm-hands-entry-lite-c0t5xpzh.js} +1 -1
  49. package/bin/vm-hands/{vm-hands-entry-lite-ymqb2927.js → vm-hands-entry-lite-c4959xva.js} +2 -2
  50. package/bin/vm-hands/{vm-hands-entry-lite-dtn5wds4.js → vm-hands-entry-lite-d467t8z5.js} +1 -1
  51. package/bin/vm-hands/vm-hands-entry-lite-f8ts9y2q.js +3 -0
  52. package/bin/vm-hands/{vm-hands-entry-lite-n9rwh8vy.js → vm-hands-entry-lite-fzq1je66.js} +19 -19
  53. package/bin/vm-hands/{vm-hands-entry-lite-k0enbx0h.js → vm-hands-entry-lite-g23v6zrd.js} +42 -42
  54. package/bin/vm-hands/{vm-hands-entry-lite-0sh835na.js → vm-hands-entry-lite-haws181e.js} +2 -2
  55. package/bin/vm-hands/{vm-hands-entry-lite-gh0yjzye.js → vm-hands-entry-lite-hc11hecd.js} +1 -1
  56. package/bin/vm-hands/{vm-hands-entry-lite-8evapfhb.js → vm-hands-entry-lite-jnym8gwb.js} +5 -5
  57. package/bin/vm-hands/{vm-hands-entry-lite-v0zva5nj.js → vm-hands-entry-lite-krnvgf71.js} +1 -1
  58. package/bin/vm-hands/{vm-hands-entry-lite-90y6pf98.js → vm-hands-entry-lite-kwmjn9y3.js} +3 -3
  59. package/bin/vm-hands/{vm-hands-entry-lite-mma9qt5r.js → vm-hands-entry-lite-mfvtp7py.js} +1 -1
  60. package/bin/vm-hands/{vm-hands-entry-lite-2crj59fq.js → vm-hands-entry-lite-mq1gw5t4.js} +3 -3
  61. package/bin/vm-hands/{vm-hands-entry-lite-19dpjtpb.js → vm-hands-entry-lite-n3274tws.js} +1 -1
  62. package/bin/vm-hands/{vm-hands-entry-lite-7gzn7myq.js → vm-hands-entry-lite-nc915j4r.js} +5 -5
  63. package/bin/vm-hands/{vm-hands-entry-lite-tdpnjywj.js → vm-hands-entry-lite-p6b8e7zr.js} +2 -2
  64. package/bin/vm-hands/vm-hands-entry-lite-paryp920.js +150 -0
  65. package/bin/vm-hands/{vm-hands-entry-lite-zc8fsn2e.js → vm-hands-entry-lite-pzj5s203.js} +2 -2
  66. package/bin/vm-hands/{vm-hands-entry-lite-svd5v9dr.js → vm-hands-entry-lite-q1yvw4xz.js} +1 -1
  67. package/bin/vm-hands/{vm-hands-entry-lite-1nrxnm0y.js → vm-hands-entry-lite-sfmeafdm.js} +9 -9
  68. package/bin/vm-hands/{vm-hands-entry-lite-5eg3tgdq.js → vm-hands-entry-lite-t82dzcxb.js} +2 -2
  69. package/bin/vm-hands/{vm-hands-entry-lite-q80xmhrx.js → vm-hands-entry-lite-tash5m18.js} +14 -14
  70. package/bin/vm-hands/{vm-hands-entry-lite-ndhspax6.js → vm-hands-entry-lite-tns12zqc.js} +2 -2
  71. package/bin/vm-hands/{vm-hands-entry-lite-5np5k3wb.js → vm-hands-entry-lite-wfc0agnt.js} +3 -3
  72. package/bin/vm-hands/{vm-hands-entry-lite-ft81ht65.js → vm-hands-entry-lite-wyb2wphg.js} +7 -7
  73. package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
  74. package/bin/vm-hands/{vm-hands-executor-wdk7j5ff.js → vm-hands-executor-mm2t3341.js} +3 -3
  75. package/bin/vm-hands/vm-hands-op-runner-q7xymef5.js +2 -0
  76. package/bin/vm-hands/{vm-hands-runtime-xsm007dw.js → vm-hands-runtime-s4ptwfrm.js} +3 -3
  77. package/bin/vm-hands/worker-preview-readiness-8ftb3nbw.js +2 -0
  78. package/bin/vm-hands/worker-sandbox-k0vx97tx.js +2 -0
  79. package/package.json +1 -1
  80. package/bin/vm-hands/api-19drw8h8.js +0 -2
  81. package/bin/vm-hands/api-credentials-51jbbsb9.js +0 -2
  82. package/bin/vm-hands/connect-cli-key5zmnv.js +0 -2
  83. package/bin/vm-hands/credentials-yf556ykn.js +0 -2
  84. package/bin/vm-hands/custom-endpoint-device-vbct7bj9.js +0 -2
  85. package/bin/vm-hands/desktop-account-j6fjngt1.js +0 -2
  86. package/bin/vm-hands/install-receipt-gwv1qv2m.js +0 -2
  87. package/bin/vm-hands/local-automation-qq5sskt4.js +0 -2
  88. package/bin/vm-hands/local-capabilities-46mncb6r.js +0 -2
  89. package/bin/vm-hands/local-desktop-users-4hc6jysa.js +0 -2
  90. package/bin/vm-hands/local-display-mac-fjeyb4h9.js +0 -2
  91. package/bin/vm-hands/local-display-session-591yjg8s.js +0 -2
  92. package/bin/vm-hands/local-display-video-yjg6cj63.js +0 -2
  93. package/bin/vm-hands/local-managed-process-f2cyg1ax.js +0 -2
  94. package/bin/vm-hands/local-pty-session-4h4ekakp.js +0 -2
  95. package/bin/vm-hands/managed-runtime-yf9asm5j.js +0 -2
  96. package/bin/vm-hands/network-contract-4wew8f21.js +0 -2
  97. package/bin/vm-hands/package-sng72tm1.js +0 -2
  98. package/bin/vm-hands/permissions-pkmd26vk.js +0 -2
  99. package/bin/vm-hands/serve-service-rna11dh7.js +0 -2
  100. package/bin/vm-hands/version-gpqwzy05.js +0 -2
  101. package/bin/vm-hands/vm-hands-entry-lite-60pnam39.js +0 -3
  102. package/bin/vm-hands/vm-hands-entry-lite-krrsffbp.js +0 -2
  103. package/bin/vm-hands/vm-hands-entry-lite-nrrgwj9v.js +0 -128
  104. package/bin/vm-hands/vm-hands-op-runner-wtm4g7ec.js +0 -2
  105. package/bin/vm-hands/worker-preview-readiness-ye6cvg3k.js +0 -2
  106. package/bin/vm-hands/worker-sandbox-j6cmex8e.js +0 -2
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{de,et,O}from"./vm-hands-entry-lite-39qv4sqt.js";import{execFileSync as l}from"child_process";import{existsSync as c,realpathSync as s}from"fs";import{userInfo as f}from"os";import{isAbsolute as u,join as t,normalize as d,parse as p}from"path";function a(){let r=d(f().homedir);if(!u(r)||r===p(r).root)throw Error("Could not resolve the canonical user home.");return r}function Fo(r){return p(r).root===r}var jo=(r)=>`Reason can't work in ${r}, the top of a drive: use a folder inside it, such as a project folder`;function ie(r,n,e=a()){let i=O(n);if(n.kind==="managed"&&n.base){let o=s(e);return{anchor:o,boundary:t(o,n.base),path:t(o,i)}}if(n.kind==="root"&&et(n.path)){let o=s(e);return{anchor:o,boundary:t(o,de),path:t(o,i)}}return{anchor:r,boundary:r,path:t(r,i)}}function nr(r=a()){return t(r,".config")}function Uo(){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 Ho(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,Fo,jo,ie,nr,Uo,Ho};
2
+ import{de,et,O}from"./vm-hands-entry-lite-39qv4sqt.js";import{execFileSync as l}from"child_process";import{existsSync as c,realpathSync as s}from"fs";import{userInfo as f}from"os";import{isAbsolute as u,join as t,normalize as d,parse as p}from"path";function a(){let r=d(f().homedir);if(!u(r)||r===p(r).root)throw Error("Could not resolve the canonical user home.");return r}function Ho(r){return p(r).root===r}var zo=(r)=>`Reason can't work in ${r}, the top of a drive: use a folder inside it, such as a project folder`;function ie(r,n,e=a()){let i=O(n);if(n.kind==="managed"&&n.base){let o=s(e);return{anchor:o,boundary:t(o,n.base),path:t(o,i)}}if(n.kind==="root"&&et(n.path)){let o=s(e);return{anchor:o,boundary:t(o,de),path:t(o,i)}}return{anchor:r,boundary:r,path:t(r,i)}}function nr(r=a()){return t(r,".config")}function qo(){if(process.platform!=="darwin")return null;try{let r=l("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return u(r)?s(r):null}catch{return null}}function Wo(r=a()){let n=t(r,"Library","Application Support","Ara"),e=t(r,"Library","Application Support","Reason");return c(n)&&!c(e)?n:e}
3
+ export{a,Ho,zo,ie,nr,qo,Wo};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{_,Yr,yt,ke}from"./vm-hands-entry-lite-5eg3tgdq.js";import{Oo}from"./vm-hands-entry-lite-ndhspax6.js";import{a}from"./vm-hands-entry-lite-0sh835na.js";import{t,i,s,n}from"./vm-hands-entry-lite-70x16hkx.js";import{createHmac as _t,createPublicKey as be,randomBytes as bt,randomUUID as me,verify as he}from"crypto";import{chmodSync as L,existsSync as z,mkdirSync as Se,readFileSync as Ie,realpathSync as St,renameSync as De,statSync as It,unlinkSync as Le,writeFileSync as we}from"fs";import{basename as Dt,dirname as w,isAbsolute as Ae,join as m,resolve as Lt}from"path";var $e=[Object.freeze({family:"ara",channel:"stable",applicationId:"so.ara.desktop"}),Object.freeze({family:"ara",channel:"staging",applicationId:"so.ara.desktop.staging"}),Object.freeze({family:"reason",channel:"stable",applicationId:"com.reasonmachines.desktop"}),Object.freeze({family:"reason",channel:"staging",applicationId:"com.reasonmachines.desktop.staging"})];var Z="REASON_DESKTOP_RUNTIME",q="REASON_DESKTOP_RUNTIME_CHANNEL",Q="REASON_DESKTOP_RUNTIME_INSTANCE_ID",ee="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",We={[Z]:"ARA_DESKTOP_RUNTIME",[q]:"ARA_DESKTOP_RUNTIME_CHANNEL",[Q]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[ee]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function x(r){if(r===void 0)return;if(!/^[a-f0-9]{64}$/.test(r))throw Error("Invalid desktop workspace scope.");return r}import{chmodSync as h,existsSync as g,mkdirSync as S,readFileSync as N,realpathSync as te,renameSync as ne,unlinkSync as I,writeFileSync as k}from"fs";import{createPrivateKey as ie,createPublicKey as re,generateKeyPairSync as oe,randomUUID as ae,sign as se}from"crypto";import{createRequire as ce}from"module";import{homedir as le,platform as T}from"os";import{dirname as de,join as f}from"path";var O=1,ue=16384,y=65536,pe=128,ge=128,U=65536;class l extends Error{code;nativeStatus;constructor(r,e){super(`Reason Device proof boundary failed (${r}).${e===void 0?"":` Native status: ${e}.`}`);this.code=r;this.nativeStatus=e;this.name="LocalCredentialBoundaryError"}}var D=null;function F(){if(!D)try{D=ce(import.meta.url)("bun:ffi")}catch{throw new l("native_boundary_unavailable")}return D}function fe(r){if(typeof r!=="string")return null;try{let e=new URL(r);if(e.protocol!=="https:"&&e.hostname!=="127.0.0.1"&&e.hostname!=="localhost"&&e.hostname!=="[::1]"&&e.hostname!=="::1")return null;return e.origin}catch{return null}}function ye(r){if(!r||typeof r!=="object"||Array.isArray(r))throw new l("invalid_credential_record");let e=r,o=fe(e.apiOrigin);if(e.version!==O||!o||typeof e.orgId!=="string"||e.orgId.length<1||e.orgId.length>160||typeof e.deviceId!=="string"||e.deviceId.length<1||e.deviceId.length>160||typeof e.credential!=="string"||!/^(?:reason|ara)_dev_/.test(e.credential)||e.credential.length>4096)throw new l("invalid_credential_record");return{version:O,apiOrigin:o,orgId:e.orgId,deviceId:e.deviceId,credential:e.credential}}function Gt(r=process.execPath){let e=r;try{e=te(r)}catch{}return Oo(de(e))}function u(r){return F().ptr(r)}function ve(r){if(!g(r))throw new l("native_boundary_unavailable");let{dlopen:e,FFIType:o}=F();try{return e(r,{ara_device_configure_scope:{args:[o.ptr,o.u64],returns:o.i32},ara_device_key_load_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_create_fresh_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_sign:{args:[o.ptr,o.u64,o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_is_non_extractable:{args:[o.ptr],returns:o.i32},ara_device_key_delete:{args:[o.ptr],returns:o.i32},ara_device_binding_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_binding_create:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_update:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_delete:{args:[o.ptr],returns:o.i32},ara_device_keychain_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_keychain_delete:{args:[o.ptr],returns:o.i32}})}catch(c){if(c instanceof l)throw c;throw new l("native_boundary_unavailable")}}function K(r){return Buffer.from(r).toString("base64url")}function v(r){if(typeof r!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(r))return!1;try{let e=Buffer.from(r,"base64url");return e.byteLength===65&&e[0]===4}catch{return!1}}function M(r){if(r.byteLength<8||r.byteLength>72||r[0]!==48)return!1;let e=r[1];return e!==void 0&&e<128&&e+2===r.byteLength}class Ke{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(r=Gt(),e=T(),o){this.libraryPath=r;this.runtimePlatform=e;this.workspaceScope=o;x(o)}symbols(){if(this.runtimePlatform!=="darwin")throw new l("unsupported_platform");this.library??=ve(this.libraryPath);let r=new TextEncoder().encode(this.workspaceScope??""),e=this.library.symbols.ara_device_configure_scope(u(r.length?r:new Uint8Array(1)),BigInt(r.length));if(e!==0)throw new l("native_boundary_unavailable",e);return this.library.symbols}publicKey(r){let e=new Uint8Array(pe),o=new BigUint64Array(1),c=r==="load"?this.symbols().ara_device_key_load_public(u(e),BigInt(e.byteLength),u(o)):this.symbols().ara_device_key_create_fresh_public(u(e),BigInt(e.byteLength),u(o));if(c!==0)throw new l(r==="load"?"proof_key_read_failed":"proof_key_generation_failed",c);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d!==65)throw new l("invalid_public_key");let p=K(e.subarray(0,d));if(!v(p))throw new l("invalid_public_key");return p}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(r){if(r.byteLength<1||r.byteLength>U)throw new l("proof_sign_failed");let e=new Uint8Array(ge),o=new BigUint64Array(1),c=this.symbols().ara_device_key_sign(u(r),BigInt(r.byteLength),u(e),BigInt(e.byteLength),u(o));if(c!==0)throw new l("proof_sign_failed",c);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d<1||d>e.byteLength)throw new l("invalid_signature");let p=e.subarray(0,d);if(!M(p))throw new l("invalid_signature");return K(p)}privateKeyIsNonExtractable(){let r=new Uint8Array(1),e=this.symbols().ara_device_key_is_non_extractable(u(r));if(e!==0||r[0]!==1)throw new l("proof_key_read_failed",e);return!0}deleteKey(){let r=new Uint8Array(1),e=this.symbols().ara_device_key_delete(u(r));if(e!==0)throw new l("proof_key_delete_failed",e);return r[0]===1}loadBinding(){let r=new Uint8Array(y),e=new BigUint64Array(1),o=this.symbols().ara_device_binding_read(u(r),BigInt(r.byteLength),u(e));if(o===1)return null;if(o!==0)throw new l("binding_read_failed",o);let c=Number(e[0]);if(!Number.isSafeInteger(c)||c<1||c>r.byteLength)throw new l("invalid_binding");return r.slice(0,c)}createBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");let e=this.symbols().ara_device_binding_create(u(r),BigInt(r.byteLength));if(e!==0)throw new l("binding_create_failed",e)}updateBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");let e=this.symbols().ara_device_binding_update(u(r),BigInt(r.byteLength));if(e!==0)throw new l("binding_update_failed",e)}deleteBinding(){let r=new Uint8Array(1),e=this.symbols().ara_device_binding_delete(u(r));if(e!==0)throw new l("binding_delete_failed",e);return r[0]===1}loadLegacyCredential(){let r=new Uint8Array(ue),e=new BigUint64Array(1),o=this.symbols().ara_device_keychain_read(u(r),BigInt(r.byteLength),u(e));if(o===1)return null;if(o!==0)throw new l("legacy_credential_read_failed",o);let c=Number(e[0]);if(!Number.isSafeInteger(c)||c<1||c>r.byteLength)throw new l("invalid_credential_record");try{let d=new TextDecoder("utf-8",{fatal:!0}).decode(r.subarray(0,c));return ye(JSON.parse(d))}catch(d){if(d instanceof l)throw d;throw new l("invalid_credential_record")}}deleteLegacyCredential(){let r=new Uint8Array(1),e=this.symbols().ara_device_keychain_delete(u(r));if(e!==0)throw new l("legacy_credential_delete_failed",e);return r[0]===1}}function C(r){let e=r.export({format:"jwk"});if(e.crv!=="P-256"||typeof e.x!=="string"||typeof e.y!=="string")throw new l("invalid_public_key");let o=Buffer.from(e.x,"base64url"),c=Buffer.from(e.y,"base64url");if(o.byteLength!==32||c.byteLength!==32)throw new l("invalid_public_key");let d=Buffer.concat([Buffer.of(4),o,c]).toString("base64url");if(!v(d))throw new l("invalid_public_key");return d}function _e(){let r=process.env.XDG_CONFIG_HOME?.trim()||f(le(),".config");yt(r);let e=f(r,"ara");return Yr(e)?e:f(r,"reason")}class Lr{directory;constructor(r=_e()){this.directory=r}keyPath(){return f(this.directory,"local-device.key")}bindingPath(){return f(this.directory,"local-device.binding")}loadPrivateKeyObject(){let r=this.keyPath();if(!g(r))throw new l("proof_key_read_failed");try{let e=N(r,"utf8");return ie({key:e,format:"pem"})}catch{throw new l("proof_key_read_failed")}}loadPublicKey(){let r=this.loadPrivateKeyObject(),e=re(r);return C(e)}createFreshPublicKey(){S(this.directory,{recursive:!0,mode:448});let{privateKey:r,publicKey:e}=oe("ec",{namedCurve:"P-256"}),o=r.export({type:"pkcs8",format:"pem"}),c=this.keyPath();return k(c,o,{mode:384}),h(c,384),C(e)}sign(r){if(r.byteLength<1||r.byteLength>U)throw new l("proof_sign_failed");let e=this.loadPrivateKeyObject(),o;try{o=se("sha256",r,e)}catch{throw new l("proof_sign_failed")}if(!M(o))throw new l("invalid_signature");return o.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let r=this.keyPath();if(!g(r))return!1;return I(r),!0}loadBinding(){let r=this.bindingPath();if(!g(r))return null;try{return new Uint8Array(N(r))}catch{return null}}createBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");S(this.directory,{recursive:!0,mode:448});let e=this.bindingPath();if(g(e))throw new l("binding_create_failed");k(e,r,{mode:384}),h(e,384)}updateBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");S(this.directory,{recursive:!0,mode:448});let e=this.bindingPath();if(!g(e))throw new l("binding_update_failed");let o=`${e}.${ae()}`;try{k(o,r,{mode:384,flag:"wx"}),h(o,384),ne(o,e)}finally{if(g(o))I(o)}}deleteBinding(){let r=this.bindingPath();if(!g(r))return!1;return I(r),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function V(){return T()==="darwin"?new Ke:new Lr}var b=t().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),B=i({id:b,kind:n("permission_denied"),operation:s(["bash","read","write","edit"]),provenance:s(["sandbox_policy","os_permission_unknown"]),occurredAt:t().datetime(),expiresAt:t().datetime(),sessionId:b,deviceId:b,organizationId:b}).strict();var A=4;var P="macos-keychain-p256-v1",Pe=1,Ee=`ARA-DEVICE-BINDING-V1
2
+ import{_,Yr,yt,ke}from"./vm-hands-entry-lite-t82dzcxb.js";import{No}from"./vm-hands-entry-lite-tns12zqc.js";import{a}from"./vm-hands-entry-lite-haws181e.js";import{t,i,s,n}from"./vm-hands-entry-lite-4cdn822w.js";import{createHmac as _t,createPublicKey as be,randomBytes as bt,randomUUID as me,verify as he}from"crypto";import{chmodSync as L,existsSync as z,mkdirSync as Se,readFileSync as Ie,realpathSync as St,renameSync as De,statSync as It,unlinkSync as Le,writeFileSync as we}from"fs";import{basename as Dt,dirname as w,isAbsolute as Ae,join as m,resolve as Lt}from"path";var $e=[Object.freeze({family:"ara",channel:"stable",applicationId:"so.ara.desktop"}),Object.freeze({family:"ara",channel:"staging",applicationId:"so.ara.desktop.staging"}),Object.freeze({family:"reason",channel:"stable",applicationId:"com.reasonmachines.desktop"}),Object.freeze({family:"reason",channel:"staging",applicationId:"com.reasonmachines.desktop.staging"})];var Z="REASON_DESKTOP_RUNTIME",q="REASON_DESKTOP_RUNTIME_CHANNEL",Q="REASON_DESKTOP_RUNTIME_INSTANCE_ID",ee="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",We={[Z]:"ARA_DESKTOP_RUNTIME",[q]:"ARA_DESKTOP_RUNTIME_CHANNEL",[Q]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[ee]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function x(r){if(r===void 0)return;if(!/^[a-f0-9]{64}$/.test(r))throw Error("Invalid desktop workspace scope.");return r}import{chmodSync as h,existsSync as g,mkdirSync as S,readFileSync as N,realpathSync as te,renameSync as ne,unlinkSync as I,writeFileSync as k}from"fs";import{createPrivateKey as ie,createPublicKey as re,generateKeyPairSync as oe,randomUUID as ae,sign as se}from"crypto";import{createRequire as ce}from"module";import{homedir as le,platform as T}from"os";import{dirname as de,join as f}from"path";var O=1,ue=16384,y=65536,pe=128,ge=128,U=65536;class l extends Error{code;nativeStatus;constructor(r,e){super(`Reason Device proof boundary failed (${r}).${e===void 0?"":` Native status: ${e}.`}`);this.code=r;this.nativeStatus=e;this.name="LocalCredentialBoundaryError"}}var D=null;function F(){if(!D)try{D=ce(import.meta.url)("bun:ffi")}catch{throw new l("native_boundary_unavailable")}return D}function fe(r){if(typeof r!=="string")return null;try{let e=new URL(r);if(e.protocol!=="https:"&&e.hostname!=="127.0.0.1"&&e.hostname!=="localhost"&&e.hostname!=="[::1]"&&e.hostname!=="::1")return null;return e.origin}catch{return null}}function ye(r){if(!r||typeof r!=="object"||Array.isArray(r))throw new l("invalid_credential_record");let e=r,o=fe(e.apiOrigin);if(e.version!==O||!o||typeof e.orgId!=="string"||e.orgId.length<1||e.orgId.length>160||typeof e.deviceId!=="string"||e.deviceId.length<1||e.deviceId.length>160||typeof e.credential!=="string"||!/^(?:reason|ara)_dev_/.test(e.credential)||e.credential.length>4096)throw new l("invalid_credential_record");return{version:O,apiOrigin:o,orgId:e.orgId,deviceId:e.deviceId,credential:e.credential}}function Gt(r=process.execPath){let e=r;try{e=te(r)}catch{}return No(de(e))}function u(r){return F().ptr(r)}function ve(r){if(!g(r))throw new l("native_boundary_unavailable");let{dlopen:e,FFIType:o}=F();try{return e(r,{ara_device_configure_scope:{args:[o.ptr,o.u64],returns:o.i32},ara_device_key_load_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_create_fresh_public:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_sign:{args:[o.ptr,o.u64,o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_key_is_non_extractable:{args:[o.ptr],returns:o.i32},ara_device_key_delete:{args:[o.ptr],returns:o.i32},ara_device_binding_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_binding_create:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_update:{args:[o.ptr,o.u64],returns:o.i32},ara_device_binding_delete:{args:[o.ptr],returns:o.i32},ara_device_keychain_read:{args:[o.ptr,o.u64,o.ptr],returns:o.i32},ara_device_keychain_delete:{args:[o.ptr],returns:o.i32}})}catch(c){if(c instanceof l)throw c;throw new l("native_boundary_unavailable")}}function K(r){return Buffer.from(r).toString("base64url")}function v(r){if(typeof r!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(r))return!1;try{let e=Buffer.from(r,"base64url");return e.byteLength===65&&e[0]===4}catch{return!1}}function M(r){if(r.byteLength<8||r.byteLength>72||r[0]!==48)return!1;let e=r[1];return e!==void 0&&e<128&&e+2===r.byteLength}class Ke{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(r=Gt(),e=T(),o){this.libraryPath=r;this.runtimePlatform=e;this.workspaceScope=o;x(o)}symbols(){if(this.runtimePlatform!=="darwin")throw new l("unsupported_platform");this.library??=ve(this.libraryPath);let r=new TextEncoder().encode(this.workspaceScope??""),e=this.library.symbols.ara_device_configure_scope(u(r.length?r:new Uint8Array(1)),BigInt(r.length));if(e!==0)throw new l("native_boundary_unavailable",e);return this.library.symbols}publicKey(r){let e=new Uint8Array(pe),o=new BigUint64Array(1),c=r==="load"?this.symbols().ara_device_key_load_public(u(e),BigInt(e.byteLength),u(o)):this.symbols().ara_device_key_create_fresh_public(u(e),BigInt(e.byteLength),u(o));if(c!==0)throw new l(r==="load"?"proof_key_read_failed":"proof_key_generation_failed",c);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d!==65)throw new l("invalid_public_key");let p=K(e.subarray(0,d));if(!v(p))throw new l("invalid_public_key");return p}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(r){if(r.byteLength<1||r.byteLength>U)throw new l("proof_sign_failed");let e=new Uint8Array(ge),o=new BigUint64Array(1),c=this.symbols().ara_device_key_sign(u(r),BigInt(r.byteLength),u(e),BigInt(e.byteLength),u(o));if(c!==0)throw new l("proof_sign_failed",c);let d=Number(o[0]);if(!Number.isSafeInteger(d)||d<1||d>e.byteLength)throw new l("invalid_signature");let p=e.subarray(0,d);if(!M(p))throw new l("invalid_signature");return K(p)}privateKeyIsNonExtractable(){let r=new Uint8Array(1),e=this.symbols().ara_device_key_is_non_extractable(u(r));if(e!==0||r[0]!==1)throw new l("proof_key_read_failed",e);return!0}deleteKey(){let r=new Uint8Array(1),e=this.symbols().ara_device_key_delete(u(r));if(e!==0)throw new l("proof_key_delete_failed",e);return r[0]===1}loadBinding(){let r=new Uint8Array(y),e=new BigUint64Array(1),o=this.symbols().ara_device_binding_read(u(r),BigInt(r.byteLength),u(e));if(o===1)return null;if(o!==0)throw new l("binding_read_failed",o);let c=Number(e[0]);if(!Number.isSafeInteger(c)||c<1||c>r.byteLength)throw new l("invalid_binding");return r.slice(0,c)}createBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");let e=this.symbols().ara_device_binding_create(u(r),BigInt(r.byteLength));if(e!==0)throw new l("binding_create_failed",e)}updateBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");let e=this.symbols().ara_device_binding_update(u(r),BigInt(r.byteLength));if(e!==0)throw new l("binding_update_failed",e)}deleteBinding(){let r=new Uint8Array(1),e=this.symbols().ara_device_binding_delete(u(r));if(e!==0)throw new l("binding_delete_failed",e);return r[0]===1}loadLegacyCredential(){let r=new Uint8Array(ue),e=new BigUint64Array(1),o=this.symbols().ara_device_keychain_read(u(r),BigInt(r.byteLength),u(e));if(o===1)return null;if(o!==0)throw new l("legacy_credential_read_failed",o);let c=Number(e[0]);if(!Number.isSafeInteger(c)||c<1||c>r.byteLength)throw new l("invalid_credential_record");try{let d=new TextDecoder("utf-8",{fatal:!0}).decode(r.subarray(0,c));return ye(JSON.parse(d))}catch(d){if(d instanceof l)throw d;throw new l("invalid_credential_record")}}deleteLegacyCredential(){let r=new Uint8Array(1),e=this.symbols().ara_device_keychain_delete(u(r));if(e!==0)throw new l("legacy_credential_delete_failed",e);return r[0]===1}}function C(r){let e=r.export({format:"jwk"});if(e.crv!=="P-256"||typeof e.x!=="string"||typeof e.y!=="string")throw new l("invalid_public_key");let o=Buffer.from(e.x,"base64url"),c=Buffer.from(e.y,"base64url");if(o.byteLength!==32||c.byteLength!==32)throw new l("invalid_public_key");let d=Buffer.concat([Buffer.of(4),o,c]).toString("base64url");if(!v(d))throw new l("invalid_public_key");return d}function _e(){let r=process.env.XDG_CONFIG_HOME?.trim()||f(le(),".config");yt(r);let e=f(r,"ara");return Yr(e)?e:f(r,"reason")}class Lr{directory;constructor(r=_e()){this.directory=r}keyPath(){return f(this.directory,"local-device.key")}bindingPath(){return f(this.directory,"local-device.binding")}loadPrivateKeyObject(){let r=this.keyPath();if(!g(r))throw new l("proof_key_read_failed");try{let e=N(r,"utf8");return ie({key:e,format:"pem"})}catch{throw new l("proof_key_read_failed")}}loadPublicKey(){let r=this.loadPrivateKeyObject(),e=re(r);return C(e)}createFreshPublicKey(){S(this.directory,{recursive:!0,mode:448});let{privateKey:r,publicKey:e}=oe("ec",{namedCurve:"P-256"}),o=r.export({type:"pkcs8",format:"pem"}),c=this.keyPath();return k(c,o,{mode:384}),h(c,384),C(e)}sign(r){if(r.byteLength<1||r.byteLength>U)throw new l("proof_sign_failed");let e=this.loadPrivateKeyObject(),o;try{o=se("sha256",r,e)}catch{throw new l("proof_sign_failed")}if(!M(o))throw new l("invalid_signature");return o.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let r=this.keyPath();if(!g(r))return!1;return I(r),!0}loadBinding(){let r=this.bindingPath();if(!g(r))return null;try{return new Uint8Array(N(r))}catch{return null}}createBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");S(this.directory,{recursive:!0,mode:448});let e=this.bindingPath();if(g(e))throw new l("binding_create_failed");k(e,r,{mode:384}),h(e,384)}updateBinding(r){if(r.byteLength<1||r.byteLength>y)throw new l("invalid_binding");S(this.directory,{recursive:!0,mode:448});let e=this.bindingPath();if(!g(e))throw new l("binding_update_failed");let o=`${e}.${ae()}`;try{k(o,r,{mode:384,flag:"wx"}),h(o,384),ne(o,e)}finally{if(g(o))I(o)}}deleteBinding(){let r=this.bindingPath();if(!g(r))return!1;return I(r),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function V(){return T()==="darwin"?new Ke:new Lr}var b=t().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),B=i({id:b,kind:n("permission_denied"),operation:s(["bash","read","write","edit"]),provenance:s(["sandbox_policy","os_permission_unknown"]),occurredAt:t().datetime(),expiresAt:t().datetime(),sessionId:b,deviceId:b,organizationId:b}).strict();var A=4;var P="macos-keychain-p256-v1",Pe=1,Ee=`ARA-DEVICE-BINDING-V1
3
3
  `;function Re(r){return r===void 0||typeof r==="number"&&Number.isInteger(r)&&r>=1&&r<=4}function G(r,e=Date.now()){let o=B.safeParse(r);if(!o.success)return!1;let c=o.data,d=typeof c.occurredAt==="string"?Date.parse(c.occurredAt):NaN,p=typeof c.expiresAt==="string"?Date.parse(c.expiresAt):NaN;return c.kind==="permission_denied"&&["bash","read","write","edit"].includes(c.operation)&&["sandbox_policy","os_permission_unknown"].includes(c.provenance)&&Number.isFinite(d)&&d<=e&&p>e&&p>d&&p-d<=600000}function Kt(r,e,o=Date.now()){if(!r||!e||r.state!=="connected"||r.deviceId!==e.deviceId)return null;let c=Date.parse(r.lastHeartbeatAt??""),d=r.permissionRecovery;if(!(o-c>=0&&o-c<30000)||!G(d,o)||d.deviceId!==e.deviceId||d.organizationId!==e.orgId)return null;try{process.kill(r.pid,0)}catch{return null}return d}function H(r={},e=a()){let o=_({env:{...process.env,...r}}),c=r.XDG_CONFIG_HOME?.trim()||m(e,".config");return ke(c,...o==="staging"?["staging"]:[])}function Mr(r={},e=a()){return m(H(r,e),"local-device.json")}function xe(r={},e=a()){return m(H(r,e),"local-daemon.json")}function Ne(r,e){Se(w(r),{recursive:!0,mode:448}),L(w(r),448);let o=`${r}.${process.pid}.${me()}.tmp`;try{we(o,`${JSON.stringify(e,null,2)}
4
4
  `,{mode:384,flag:"wx"}),L(o,384),De(o,r),L(r,384)}finally{if(z(o))Le(o)}return r}function E(r){if(!z(r))return null;try{return JSON.parse(Ie(r,"utf8"))}catch{return null}}function Oe(r){if(!Array.isArray(r))return null;let e=[];for(let o of r){if(!o||typeof o!=="object")return null;let c=o;if(typeof c.id!=="string"||typeof c.label!=="string"||typeof c.path!=="string"||typeof c.pathFingerprint!=="string"||!c.permissions||typeof c.permissions.read!=="boolean"||typeof c.permissions.write!=="boolean"||typeof c.permissions.execute!=="boolean"||typeof c.permissions.discover_environment!=="boolean"||typeof c.permissions.expose_mcp!=="boolean")return null;e.push({id:c.id,label:c.label,path:c.path,pathFingerprint:c.pathFingerprint,permissions:c.permissions})}return e}function J(r,e,o=[]){let c=Object.keys(r);return e.every((d)=>Object.hasOwn(r,d))&&c.every((d)=>e.includes(d)||o.includes(d))}function Ce(r){if(typeof r!=="string")return null;try{let e=new URL(r);if(e.protocol!=="https:"&&e.hostname!=="127.0.0.1"&&e.hostname!=="localhost")return null;return e.origin}catch{return null}}function Y(r){if(!r||typeof r!=="object"||Array.isArray(r))return null;let e=r,o=Oe(e.roots),c=Ce(e.apiOrigin);if(!c||typeof e.orgId!=="string"||typeof e.deviceId!=="string"||typeof e.displayName!=="string"||typeof e.registeredAt!=="string"||!Re(e.handsSlots)||e.worker!==void 0&&(!e.worker||!/^[a-f0-9]{64}$/.test(e.worker.configDigest)||!["persistent","ephemeral"].includes(e.worker.lifetime)||!Number.isFinite(Date.parse(e.worker.expiresAt)))||!o)return null;return{apiOrigin:c,orgId:e.orgId,deviceId:e.deviceId,displayName:e.displayName,registeredAt:e.registeredAt,...e.handsSlots!==void 0?{handsSlots:e.handsSlots}:{},...e.worker!==void 0?{worker:e.worker}:{},roots:o}}function Te(r){return{version:A,apiOrigin:r.apiOrigin,orgId:r.orgId,deviceId:r.deviceId,devicePublicKey:r.devicePublicKey,displayName:r.displayName,registeredAt:r.registeredAt,...r.handsSlots!==void 0?{handsSlots:r.handsSlots}:{},...r.worker!==void 0?{worker:r.worker}:{},roots:r.roots.map((e)=>({id:e.id,label:e.label,path:e.path,pathFingerprint:e.pathFingerprint,permissions:{read:e.permissions.read,write:e.permissions.write,execute:e.permissions.execute,discover_environment:e.permissions.discover_environment,expose_mcp:e.permissions.expose_mcp}})),credentialStorage:P}}function X(r){if(!r||typeof r!=="object"||Array.isArray(r))return null;let e=r;if(!J(e,["version","apiOrigin","orgId","deviceId","devicePublicKey","displayName","registeredAt","roots","credentialStorage"],["handsSlots","worker"]))return null;let o=Y(e);if(!o||e.version!==A||e.credentialStorage!==P||!v(e.devicePublicKey))return null;return{version:A,...o,devicePublicKey:e.devicePublicKey,credentialStorage:P}}function Ue(r){return new TextEncoder().encode(`${Ee}${JSON.stringify(Te(r))}`)}function Fe(r){let e=Buffer.from(r,"base64url");return be({format:"jwk",key:{kty:"EC",crv:"P-256",x:e.subarray(1,33).toString("base64url"),y:e.subarray(33,65).toString("base64url")}})}function Me(r){let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new l("invalid_binding")}if(!e||typeof e!=="object"||Array.isArray(e))throw new l("invalid_binding");let o=e;if(!J(o,["version","state","signature"])||o.version!==Pe||typeof o.signature!=="string"||!/^[A-Za-z0-9_-]{10,128}$/.test(o.signature))throw new l("invalid_binding");let c=X(o.state);if(!c)throw new l("invalid_binding");let d=!1;try{d=he("sha256",Ue(c),Fe(c.devicePublicKey),Buffer.from(o.signature,"base64url"))}catch{d=!1}if(!d)throw new l("invalid_binding");return c}function je(r){let{credentialStorage:e,...o}=r;return o}function $r(r=Mr(),e={}){let o=E(r),c=e.proofStore??e.credentialStore??V(),d=c.loadBinding();if(!d){if(o&&typeof o==="object"&&!Array.isArray(o)&&Ve(o))return null;if(o!==null)throw new l("invalid_binding");return null}let p=Me(d),W=c.loadPublicKey();if(c.privateKeyIsNonExtractable(),W!==p.devicePublicKey)throw new l("invalid_public_key");let R=X(o);if(e.repair!==!1&&(!R||JSON.stringify(R)!==JSON.stringify(p)))Ne(r,p);return je(p)}function Ve(r){let e=r,o=Y(r);if(!o)return null;if(e.version===2){if(typeof e.deviceCredential!=="string"||!/^(?:reason|ara)_dev_/.test(e.deviceCredential)||e.deviceCredential.length>4096)return null;return{state:o,credentialSource:"plaintext-v2"}}if(e.version!==3||e.credentialStorage!=="macos-keychain-v1"||"deviceCredential"in e)return null;return{state:o,credentialSource:"keychain-v3"}}function ht(r=xe()){let e=E(r);if(!e||typeof e!=="object")return null;let o=e;if(o.version!==1||typeof o.pid!=="number"||!Number.isInteger(o.pid)||!["starting","connected","stopped","error"].includes(o.state??"")||typeof o.startedAt!=="string"||o.lastHeartbeatAt!==void 0&&typeof o.lastHeartbeatAt!=="string"||o.lastUsedAt!==void 0&&typeof o.lastUsedAt!=="string"||o.organizationId!==void 0&&typeof o.organizationId!=="string"||o.organizationName!==void 0&&typeof o.organizationName!=="string"||o.organizationSlug!==void 0&&typeof o.organizationSlug!=="string"||o.error!==void 0&&typeof o.error!=="string"||o.reconnectingSince!==void 0&&typeof o.reconnectingSince!=="string"||o.workspace!==void 0&&typeof o.workspace!=="string")return null;if(o.permissionRecovery!==void 0&&!G(o.permissionRecovery))delete o.permissionRecovery;return o}var Jt=1;function Be(r=Mr()){return m(w(r),"local-device.proxy.json")}function j(r=Be()){let e=E(r);if(!e||typeof e!=="object"||Array.isArray(e))return null;let o=e;if(o.version!==Jt||typeof o.url!=="string"||o.url.length===0||o.caFile!==void 0&&(typeof o.caFile!=="string"||!Ae(o.caFile)))return null;return{version:Jt,url:o.url,...o.caFile?{caFile:o.caFile}:{}}}
5
5
  export{l,Gt,Ke,Lr,Kt,Mr,$r,ht,Jt,j};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{S,Wt,$n,Ge,Bn,Fn}from"./vm-hands-entry-lite-1nrxnm0y.js";import{Xn}from"./vm-hands-entry-lite-7gzn7myq.js";import{Ln}from"./vm-hands-entry-lite-wx1fmrbs.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",fo="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-sfmeafdm.js";import{Yn}from"./vm-hands-entry-lite-nc915j4r.js";import{Ln}from"./vm-hands-entry-lite-bvqwsd3b.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`
3
3
  $ErrorActionPreference = "Stop"
4
4
  Add-Type -TypeDefinition @"
5
5
  using System;
@@ -69,7 +69,7 @@ while ($null -ne ($line = [Console]::In.ReadLine())) {
69
69
  `).join("")),t.stdin.writableLength>hn)d({reason:"input_backpressure"})},g=()=>{i=Me(...Oe("clipboard"),{env:Ae(),stdio:["ignore","pipe","ignore"],windowsHide:!0});let p="";i.stdout?.on("data",(w)=>{if(s)return;p+=w.toString("ascii");for(let f=p.indexOf(`
70
70
  `);f>=0;f=p.indexOf(`
71
71
  `)){let M=p.slice(0,f).replace(/\r$/,"");if(p=p.slice(f+1),!M.startsWith("c "))continue;let E=M.slice(2);if(E.length>Math.ceil(S/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(E)){d({reason:"display_protocol"});return}let c=Buffer.from(E,"base64");if(c.byteLength<=S)e.clipboard(c.toString("utf8"));if(s)return}if(p.length>Math.ceil(S/3)*4+4)d({reason:"display_protocol"})}),i.once("error",()=>y("Reason could not watch this computer's desktop clipboard.")),i.once("exit",()=>{if(!s)y("Reason could not watch this computer's desktop clipboard.")})};return t.stdout.on("data",(p)=>{if(s||o===null)return;o+=p.toString("utf8");let w=o.indexOf(`
72
- `);if(w<0){if(o.length>4096)d({reason:"display_protocol"});return}let f=ht(o.slice(0,w).trim());if(o=null,!f)d({reason:"display_protocol"});else if(f.session===0)y("This Windows worker runs as a service, which has no desktop: run it in the signed-in desktop session.");else g(),e.ready({width:f.width,height:f.height})}),t.stdin.on("error",()=>{return}),t.once("error",()=>y("Reason could not start this computer's desktop input.")),t.once("exit",()=>{if(o!==null)y("Reason could not start this computer's desktop input.");else d({reason:"display_closed"})}),{pointer:(p,w,f)=>h(n.pointer(p,w,f)),key:(p,w)=>h(n.key(p,w)),clipboard:(p)=>h([`c ${Buffer.from(p,"utf8").toString("base64")}`]),close(){s=!0,a()}}}var Mn=["none","standard","all"],ue="22.23.3",Tn={"linux-x64":"1084aa36196bba4c3a5e69a1ee388a6e4ff729dad09445fbcd434b28fe3c24af","linux-arm64":"5ced2d48d1d7198739b7f86804de0171aefb6823b684b12341d3321afc3cb0b2","darwin-arm64":"23b25245dcfb9af7262f8ff142e9e2e0af025368117329e7a7458a51e5922f53","win32-x64":"2b0ff57b049cda1bbcea2240eec20467018713c1efe1f7360c2681859b90ed71","win32-arm64":"33dad22e4cef5ee8f9fbb1b0d037fdacd0e56d12a4580f0d63f68b894deab535"},$e={"linux-x64":{ocu:"dist/linux/amd64/open-computer-use",obu:"native/linux-amd64/open-browser-use"},"linux-arm64":{ocu:"dist/linux/arm64/open-computer-use",obu:"native/linux-arm64/open-browser-use"},"darwin-arm64":{ocu:"dist/Open Computer Use.app/Contents/MacOS/OpenComputerUse",obu:"native/darwin-arm64/open-browser-use"},"win32-x64":{ocu:"dist/windows/amd64/open-computer-use.exe",obu:"native/windows-amd64/open-browser-use.exe"},"win32-arm64":{ocu:"dist/windows/arm64/open-computer-use.exe",obu:"native/windows-arm64/open-browser-use.exe"}},Et="chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",Dt="chrome-win64/chrome.exe",W={version:"9.0.2",url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffmpeg.zip",sha256:"c8ed4c4e6978a03c485edbfe4e0a5dc2380f8a30bba5150531b31b094492d924"},An={version:W.version,url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffprobe.zip",sha256:"fcbe839537485eaee7a7a8bc5cbc0f90d53617e80943e8a5b2e31cb851197ea6"},Le={version:W.version,url:`https://github.com/GyanD/codexffmpeg/releases/download/${W.version}/ffmpeg-${W.version}-essentials_build.zip`,sha256:"60f467265b1e312373dbcd92200c2618a74850f98d3d078e94296bb3fa2047ba"},_t=`ffmpeg-${Le.version}-essentials_build/bin`,z="com.ifuryst.open_browser_use.extension",It="com.reasonmachines.browser_use.extension",Ut="/tmp/reason-browser-use",Ue=["tint2","picom","xterm","pcmanfm"],Pt=["fonts-droid-fallback"],Ct=["pulseaudio"],Rt=["tigervnc-standalone-server"],Un=["xvfb","openbox","x11vnc","x11-utils","x11-xserver-utils","xdotool","dbus-x11","at-spi2-core","python3","python3-gi","gir1.2-atspi-2.0","gir1.2-gtk-3.0","fonts-dejavu-core",...Pt,"galculator","chromium","ffmpeg","tmux",...Ct,...Rt,...Ue],Hn=new Set([...Ue,...Pt,...Ct,...Rt]),kt=Un.filter((e)=>e!=="chromium"&&!Hn.has(e)),zn=["Xvfb","openbox","x11vnc","xdotool","dbus-launch","python3","ffmpeg","tmux"],ce="/usr/bin/chromium",jn=["/usr/local/bin","/usr/bin","/bin","/opt/homebrew/bin"];function Gn(e=process.platform,t=process.arch){let n=`${e}-${t}`;return n==="linux-x64"||n==="linux-arm64"||n==="darwin-arm64"||n==="win32-x64"||n==="win32-arm64"?n:null}function K(e){return e==="win32-x64"||e==="win32-arm64"}function Be(e){return K(e)?`node-v${ue}-${e.replace("win32","win")}`:`node-v${ue}-${e}`}function de(e){return{node:{version:ue,url:`https://nodejs.org/dist/v${ue}/${Be(e)}${K(e)?".zip":".tar.gz"}`,sha256:Tn[e]},open_computer_use:{version:O.ocu.version,url:J.ocu.url,sha256:J.ocu.sha256},open_browser_use:{version:O.obu.version,url:J.obu.url,sha256:J.obu.sha256},...e==="darwin-arm64"?{chrome_for_testing:{version:H.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${H.version}/mac-arm64/chrome-mac-arm64.zip`,sha256:H.macArm64Sha256}}:K(e)?{chrome_for_testing:{version:H.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${H.version}/win64/chrome-win64.zip`,sha256:H.win64Sha256}}:{}}}function Vn(e){let t={extension:F};for(let[n,o]of Object.entries(de(e)))t[n]=`${o.version}@${o.sha256}`;return t}function Mt(e){return b(e,".local","share","reason","desktop")}function Rr(e,t=Ln()){let n=Mt(t),o=(p)=>b(n,p,de(e)[p]?.version??""),s=o("open_computer_use"),i=o("open_browser_use"),a=e==="darwin-arm64",d=K(e),y=b(t,"Library","Application Support"),h=b(process.platform==="win32"&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:b(t,"AppData","Local"),"OpenBrowserUse"),g=a?b(y,"Google","Chrome","NativeMessagingHosts",`${z}.json`):d?b(h,"NativeMessagingHosts",`${z}.json`):b(t,".config","google-chrome","NativeMessagingHosts",`${z}.json`);return{root:n,automation:b(vt(n),"automation"),receipt:b(n,"receipt.json"),minimal:is(t),node:d?b(o("node"),Be(e),"node.exe"):b(o("node"),"bin","node"),ocuDir:s,ocu:b(s,$e[e].ocu),ocuApp:a?b(s,"dist","Open Computer Use.app"):null,obuDir:i,obu:b(i,"cli","open-browser-use.js"),nativeHost:b(i,$e[e].obu),extensionDir:a?b(y,"OpenBrowserUse","chrome-extension","release"):d?b(h,"chrome-extension","release"):b(t,".local","share","open-browser-use","chrome-extension","release"),setupNativeHostManifest:g,nativeHostManifests:a?[g,b(y,"Google","ChromeForTesting","NativeMessagingHosts",`${z}.json`)]:d?[g]:[b(t,".config","chromium","NativeMessagingHosts",`${z}.json`),b(t,".config","google-chrome-for-testing","NativeMessagingHosts",`${z}.json`)],browser:a?b(o("chrome_for_testing"),Et):d?b(o("chrome_for_testing"),Dt):ce,userChromeHost:a?b(n,"user-chrome","reason-browser-use"):null,userChromeRegistration:a?b(y,"Google","Chrome","NativeMessagingHosts",`${It}.json`):null,ffmpegDir:b(n,"ffmpeg"),ffmpeg:a?b(n,"ffmpeg",W.version,"ffmpeg"):d?b(n,"ffmpeg",Le.version,_t,"ffmpeg.exe"):null,ffprobe:a?b(n,"ffprobe",An.version,"ffprobe"):d?b(n,"ffmpeg",Le.version,_t,"ffprobe.exe"):null}}function Wn(e){try{let t=JSON.parse(le(e,"utf8"));if(typeof t!=="object"||t===null)return null;let n=t,o=n.pins;if(n.schema_version!==1||typeof n.platform!=="string"||typeof o!=="object"||o===null||!Object.values(o).every((s)=>typeof s==="string")||!Mn.includes(n.permissions)||!Array.isArray(n.missing_system_packages)||!n.missing_system_packages.every((s)=>typeof s==="string")||typeof n.updated_at!=="string")return null;return{schema_version:1,platform:n.platform,pins:o,permissions:n.permissions,missing_system_packages:n.missing_system_packages,updated_at:n.updated_at}}catch{return null}}function A(e){try{return Ne(e).isFile()}catch{return!1}}function Tt(e){try{let t=Ne(e);return t.isFile()&&(t.mode&73)!==0}catch{return!1}}function Kn(e){try{return le(e,"utf8")}catch{return null}}function U(e){for(let t of jn){let n=b(t,e);try{let o=Ne(n);if(o.isFile()&&(o.mode&73)!==0)return n}catch{}}return null}function qn(e){try{let t=JSON.parse(le(b(e,"package.json"),"utf8"));return typeof t==="object"&&t!==null&&typeof t.version==="string"?t.version:null}catch{return null}}function Yn(e,t,n){let o=de(n)[e];if(!o)return!1;let s=K(n);if(e==="node")return A(s?b(t,Be(n),"node.exe"):b(t,"bin","node"));if(e==="chrome_for_testing")return A(b(t,s?Dt:Et));let i=$e[n][e==="open_computer_use"?"ocu":"obu"];return qn(t)===o.version&&A(b(t,i))&&(e==="open_computer_use"||A(b(t,"cli","open-browser-use.js")))}function Jn(e){return St("sha256").update(Buffer.from(e,"base64")).digest("hex").slice(0,32).replace(/./g,(t)=>String.fromCharCode(97+Number.parseInt(t,16)))}function He(e){try{let t=JSON.parse(le(e,"utf8"));return typeof t==="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Zn(e){let t=He(b(e.extensionDir,"manifest.json"));return t!==null&&t.version===O.obu.version&&typeof t.key==="string"&&Jn(t.key)===F}function Qn(e,t){let n=e?.allowed_origins;return e!==null&&e.name===z&&Array.isArray(n)&&n.length===1&&n[0]===`chrome-extension://${F}/`&&(t===void 0||e.path===t)}function es(e){return Zn(e)&&A(e.nativeHost)&&e.nativeHostManifests.every((t)=>Qn(He(t),e.nativeHost))}function ts(e){return`#!/bin/sh
72
+ `);if(w<0){if(o.length>4096)d({reason:"display_protocol"});return}let f=ht(o.slice(0,w).trim());if(o=null,!f)d({reason:"display_protocol"});else if(f.session===0)y("This Windows worker runs as a service, which has no desktop: run it in the signed-in desktop session.");else g(),e.ready({width:f.width,height:f.height})}),t.stdin.on("error",()=>{return}),t.once("error",()=>y("Reason could not start this computer's desktop input.")),t.once("exit",()=>{if(o!==null)y("Reason could not start this computer's desktop input.");else d({reason:"display_closed"})}),{pointer:(p,w,f)=>h(n.pointer(p,w,f)),key:(p,w)=>h(n.key(p,w)),clipboard:(p)=>h([`c ${Buffer.from(p,"utf8").toString("base64")}`]),close(){s=!0,a()}}}var Rn=["none","standard","all"],ue="22.23.3",Mn={"linux-x64":"1084aa36196bba4c3a5e69a1ee388a6e4ff729dad09445fbcd434b28fe3c24af","linux-arm64":"5ced2d48d1d7198739b7f86804de0171aefb6823b684b12341d3321afc3cb0b2","darwin-arm64":"23b25245dcfb9af7262f8ff142e9e2e0af025368117329e7a7458a51e5922f53","win32-x64":"2b0ff57b049cda1bbcea2240eec20467018713c1efe1f7360c2681859b90ed71","win32-arm64":"33dad22e4cef5ee8f9fbb1b0d037fdacd0e56d12a4580f0d63f68b894deab535"},$e={"linux-x64":{ocu:"dist/linux/amd64/open-computer-use",obu:"native/linux-amd64/open-browser-use"},"linux-arm64":{ocu:"dist/linux/arm64/open-computer-use",obu:"native/linux-arm64/open-browser-use"},"darwin-arm64":{ocu:"dist/Open Computer Use.app/Contents/MacOS/OpenComputerUse",obu:"native/darwin-arm64/open-browser-use"},"win32-x64":{ocu:"dist/windows/amd64/open-computer-use.exe",obu:"native/windows-amd64/open-browser-use.exe"},"win32-arm64":{ocu:"dist/windows/arm64/open-computer-use.exe",obu:"native/windows-arm64/open-browser-use.exe"}},Et="chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",Dt="chrome-win64/chrome.exe",W={version:"9.0.2",url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffmpeg.zip",sha256:"c8ed4c4e6978a03c485edbfe4e0a5dc2380f8a30bba5150531b31b094492d924"},An={version:W.version,url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffprobe.zip",sha256:"fcbe839537485eaee7a7a8bc5cbc0f90d53617e80943e8a5b2e31cb851197ea6"},Le={version:W.version,url:`https://github.com/GyanD/codexffmpeg/releases/download/${W.version}/ffmpeg-${W.version}-essentials_build.zip`,sha256:"60f467265b1e312373dbcd92200c2618a74850f98d3d078e94296bb3fa2047ba"},_t=`ffmpeg-${Le.version}-essentials_build/bin`,z="com.ifuryst.open_browser_use.extension",It="com.reasonmachines.browser_use.extension",Ut="/tmp/reason-browser-use",Ue=["tint2","picom","xterm","pcmanfm"],Pt=["fonts-droid-fallback"],Ct=["pulseaudio"],Rt=["tigervnc-standalone-server"],$n=["xvfb","openbox","x11vnc","x11-utils","x11-xserver-utils","xdotool","dbus-x11","at-spi2-core","python3","python3-gi","gir1.2-atspi-2.0","gir1.2-gtk-3.0","fonts-dejavu-core",...Pt,"galculator","chromium","ffmpeg","tmux",...Ct,...Rt,...Ue],Un=new Set([...Ue,...Pt,...Ct,...Rt]),kt=$n.filter((e)=>e!=="chromium"&&!Un.has(e)),Hn=["Xvfb","openbox","x11vnc","xdotool","dbus-launch","python3","ffmpeg","tmux"],ce="/usr/bin/chromium",zn=["/usr/local/bin","/usr/bin","/bin","/opt/homebrew/bin"];function Gn(e=process.platform,t=process.arch){let n=`${e}-${t}`;return n==="linux-x64"||n==="linux-arm64"||n==="darwin-arm64"||n==="win32-x64"||n==="win32-arm64"?n:null}function K(e){return e==="win32-x64"||e==="win32-arm64"}function Be(e){return K(e)?`node-v${ue}-${e.replace("win32","win")}`:`node-v${ue}-${e}`}function de(e){return{node:{version:ue,url:`https://nodejs.org/dist/v${ue}/${Be(e)}${K(e)?".zip":".tar.gz"}`,sha256:Mn[e]},open_computer_use:{version:O.ocu.version,url:J.ocu.url,sha256:J.ocu.sha256},open_browser_use:{version:O.obu.version,url:J.obu.url,sha256:J.obu.sha256},...e==="darwin-arm64"?{chrome_for_testing:{version:H.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${H.version}/mac-arm64/chrome-mac-arm64.zip`,sha256:H.macArm64Sha256}}:K(e)?{chrome_for_testing:{version:H.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${H.version}/win64/chrome-win64.zip`,sha256:H.win64Sha256}}:{}}}function Vn(e){let t={extension:F};for(let[n,o]of Object.entries(de(e)))t[n]=`${o.version}@${o.sha256}`;return t}function Mt(e){return b(e,".local","share","reason","desktop")}function Tr(e,t=Ln()){let n=Mt(t),o=(p)=>b(n,p,de(e)[p]?.version??""),s=o("open_computer_use"),i=o("open_browser_use"),a=e==="darwin-arm64",d=K(e),y=b(t,"Library","Application Support"),h=b(process.platform==="win32"&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:b(t,"AppData","Local"),"OpenBrowserUse"),g=a?b(y,"Google","Chrome","NativeMessagingHosts",`${z}.json`):d?b(h,"NativeMessagingHosts",`${z}.json`):b(t,".config","google-chrome","NativeMessagingHosts",`${z}.json`);return{root:n,automation:b(vt(n),"automation"),receipt:b(n,"receipt.json"),minimal:is(t),node:d?b(o("node"),Be(e),"node.exe"):b(o("node"),"bin","node"),ocuDir:s,ocu:b(s,$e[e].ocu),ocuApp:a?b(s,"dist","Open Computer Use.app"):null,obuDir:i,obu:b(i,"cli","open-browser-use.js"),nativeHost:b(i,$e[e].obu),extensionDir:a?b(y,"OpenBrowserUse","chrome-extension","release"):d?b(h,"chrome-extension","release"):b(t,".local","share","open-browser-use","chrome-extension","release"),setupNativeHostManifest:g,nativeHostManifests:a?[g,b(y,"Google","ChromeForTesting","NativeMessagingHosts",`${z}.json`)]:d?[g]:[b(t,".config","chromium","NativeMessagingHosts",`${z}.json`),b(t,".config","google-chrome-for-testing","NativeMessagingHosts",`${z}.json`)],browser:a?b(o("chrome_for_testing"),Et):d?b(o("chrome_for_testing"),Dt):ce,userChromeHost:a?b(n,"user-chrome","reason-browser-use"):null,userChromeRegistration:a?b(y,"Google","Chrome","NativeMessagingHosts",`${It}.json`):null,ffmpegDir:b(n,"ffmpeg"),ffmpeg:a?b(n,"ffmpeg",W.version,"ffmpeg"):d?b(n,"ffmpeg",Le.version,_t,"ffmpeg.exe"):null,ffprobe:a?b(n,"ffprobe",An.version,"ffprobe"):d?b(n,"ffmpeg",Le.version,_t,"ffprobe.exe"):null}}function Wn(e){try{let t=JSON.parse(le(e,"utf8"));if(typeof t!=="object"||t===null)return null;let n=t,o=n.pins;if(n.schema_version!==1||typeof n.platform!=="string"||typeof o!=="object"||o===null||!Object.values(o).every((s)=>typeof s==="string")||!Rn.includes(n.permissions)||!Array.isArray(n.missing_system_packages)||!n.missing_system_packages.every((s)=>typeof s==="string")||typeof n.updated_at!=="string")return null;return{schema_version:1,platform:n.platform,pins:o,permissions:n.permissions,missing_system_packages:n.missing_system_packages,updated_at:n.updated_at}}catch{return null}}function A(e){try{return Ne(e).isFile()}catch{return!1}}function Tt(e){try{let t=Ne(e);return t.isFile()&&(t.mode&73)!==0}catch{return!1}}function Kn(e){try{return le(e,"utf8")}catch{return null}}function U(e){for(let t of zn){let n=b(t,e);try{let o=Ne(n);if(o.isFile()&&(o.mode&73)!==0)return n}catch{}}return null}function Xn(e){try{let t=JSON.parse(le(b(e,"package.json"),"utf8"));return typeof t==="object"&&t!==null&&typeof t.version==="string"?t.version:null}catch{return null}}function qn(e,t,n){let o=de(n)[e];if(!o)return!1;let s=K(n);if(e==="node")return A(s?b(t,Be(n),"node.exe"):b(t,"bin","node"));if(e==="chrome_for_testing")return A(b(t,s?Dt:Et));let i=$e[n][e==="open_computer_use"?"ocu":"obu"];return Xn(t)===o.version&&A(b(t,i))&&(e==="open_computer_use"||A(b(t,"cli","open-browser-use.js")))}function Jn(e){return St("sha256").update(Buffer.from(e,"base64")).digest("hex").slice(0,32).replace(/./g,(t)=>String.fromCharCode(97+Number.parseInt(t,16)))}function He(e){try{let t=JSON.parse(le(e,"utf8"));return typeof t==="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Zn(e){let t=He(b(e.extensionDir,"manifest.json"));return t!==null&&t.version===O.obu.version&&typeof t.key==="string"&&Jn(t.key)===F}function Qn(e,t){let n=e?.allowed_origins;return e!==null&&e.name===z&&Array.isArray(n)&&n.length===1&&n[0]===`chrome-extension://${F}/`&&(t===void 0||e.path===t)}function es(e){return Zn(e)&&A(e.nativeHost)&&e.nativeHostManifests.every((t)=>Qn(He(t),e.nativeHost))}function ts(e){return`#!/bin/sh
73
73
  # Reason's Chrome extension host (reason desktop install): Open Browser Use on Reason's socket directory.
74
74
  obu=${`'${e.replaceAll("'","'\\''")}'`}
75
75
  case "$1" in
@@ -77,7 +77,7 @@ case "$1" in
77
77
  mcp) shift; exec "$obu" mcp --socket-dir ${Ut} "$@" ;;
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=Rr(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=Yn(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 _=zn.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)?Xn():[]}function os(e){return e?.platform==="darwin-arm64"&&e.ffmpeg===b(e.root,"ffmpeg",W.version,"ffmpeg")}async function go(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,Rn=(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 mo(e,t){if(!t)return null;let n=Rn(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)?Yn():[]}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`
81
81
  import gi, json, os, sys
82
82
  gi.require_version("Gtk", "3.0")
83
83
  from gi.repository import Gtk, Gdk, GLib
@@ -122,5 +122,5 @@ Gtk.main()
122
122
  `);f>=0;f=i.indexOf(`
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",Ht={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,On={kind:"mac_screen",sound:null},In={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,Ht.width/e.width,Ht.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
- `),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 Dn(e,t,n={}){let o=n.micros??$s,s=new $n,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)=>Fn(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??Bt)(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??Bn)((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 Tr(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,fo,F,Rn,Ve,mo,On,In,Dn,Nn,Tr,Ut,Rr,x,go};
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 Dn(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??Bt)(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,On,In,Dn,Nn,Rr,Ut,Tr,x,_o};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{_,Xr,ke}from"./vm-hands-entry-lite-5eg3tgdq.js";import{randomBytes as f}from"crypto";import{chmodSync as c,existsSync as a,lstatSync as p,mkdirSync as u,readFileSync as g,renameSync as m,unlinkSync as l,writeFileSync as d}from"fs";import{homedir as y}from"os";import{dirname as S,join as o}from"path";function Fe(r=process.env,n=y()){let e=r.XDG_CONFIG_HOME?.trim()||o(n,".config"),t=_({env:r})==="staging"?["staging"]:[];return o(ke(e,...t),"credentials.json")}function un(r,n=Fe()){return u(S(n),{recursive:!0,mode:448}),d(n,`${JSON.stringify(r,null,2)}
2
+ import{_,Xr,ke}from"./vm-hands-entry-lite-t82dzcxb.js";import{randomBytes as f}from"crypto";import{chmodSync as c,existsSync as a,lstatSync as p,mkdirSync as u,readFileSync as g,renameSync as m,unlinkSync as l,writeFileSync as d}from"fs";import{homedir as y}from"os";import{dirname as S,join as o}from"path";function Fe(r=process.env,n=y()){let e=r.XDG_CONFIG_HOME?.trim()||o(n,".config"),t=_({env:r})==="staging"?["staging"]:[];return o(ke(e,...t),"credentials.json")}function un(r,n=Fe()){return u(S(n),{recursive:!0,mode:448}),d(n,`${JSON.stringify(r,null,2)}
3
3
  `,{mode:384}),c(n,384),n}function It(r=Fe()){if(!a(r))return null;try{let n=g(r,"utf8"),e=JSON.parse(n);if(typeof e.apiOrigin!=="string"||typeof e.clientId!=="string"||typeof e.accessToken!=="string"||typeof e.refreshToken!=="string"||typeof e.expiresAt!=="string"||typeof e.orgId!=="string"||!Array.isArray(e.scopes))return null;let i=new URL(e.apiOrigin).origin,t=Xr(i);if(t!==i)k(r,n,t);return{apiOrigin:t,clientId:e.clientId,accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,scopes:e.scopes.filter((s)=>typeof s==="string"),orgId:e.orgId}}catch{return null}}function k(r,n,e){let i=`${r}.${process.pid}.${f(6).toString("hex")}.tmp`;try{let t=p(r);if(!t.isFile()||process.platform!=="win32"&&t.uid!==process.geteuid?.())return;let s=JSON.parse(n);if(d(i,`${JSON.stringify({...s,apiOrigin:e},null,2)}
4
4
  `,{mode:384,flag:"wx"}),c(i,384),g(r,"utf8")!==n)throw Error("credentials_changed");m(i,r)}catch{try{l(i)}catch{}}}function dn(r=Fe()){if(!a(r))return!1;return l(r),!0}
5
5
  export{Fe,un,It,dn};
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{Ie,De}from"./vm-hands-entry-lite-qz74j563.js";import{request as Ce}from"http";import{pipeline as Ne}from"stream";import{constants as te,createBrotliCompress as $e,createGzip as Me}from"zlib";import{WebSocket as U}from"ws";import{randomBytes as Re,timingSafeEqual as Be}from"crypto";import{createServer as Le}from"net";var p={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000,window:8};function Z(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function L(e,t,n=Number.MAX_SAFE_INTEGER){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=t&&e<=n}function pe(e){return typeof e==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(e)}function fe(e,t){let n=Buffer.from(e,"latin1");return Buffer.concat([Buffer.from([n.length]),n,t])}function C(e){if(!Z(e)||Object.keys(e).length!==12||![e.organizationId,e.userId,e.runId,e.deviceId,e.rootId,e.jobId,e.fenceId].every(pe)||!L(e.attachmentRevision,0)||!L(e.grantRevision,1)||!L(e.generation,1)||!L(e.port,1024,65535)||!L(e.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...e})}function ze(e,t){return Object.keys(e).every((n)=>e[n]===t[n])}function H(e){if(e.length>4096||!e.startsWith("/")||e.startsWith("//")||/[\\\x00-\x20\x7f#]/.test(e))throw Error("preview_path_invalid");let t=decodeURIComponent(e);if(t.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(t))throw Error("preview_path_invalid");return e}function ue(e){return Array.isArray(e)&&e.length<=64&&e.every((t)=>Array.isArray(t)&&t.length===2&&typeof t[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(t[0])&&typeof t[1]==="string"&&t[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(t[1]))}function z(e,t=p.chunk){if(e.length>Math.ceil(t/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw Error("preview_data_invalid");let n=Buffer.from(e,"base64");if(n.length>t)throw Error("preview_data_too_large");return n}function me(e){if(Array.isArray(e))return Buffer.concat(e);if(typeof e==="string")return Buffer.from(e,"utf8");if(e instanceof ArrayBuffer)return Buffer.from(e);return e}function ge(e){if(Buffer.byteLength(e)>p.upload*1.4+300000)throw Error("preview_frame_too_large");let t=JSON.parse(e);if(!Z(t))throw Error("preview_frame_invalid");if(t.type==="hello")return{type:"hello",binding:C(t.binding),...L(t.messages,p.chunk,p.upload)?{messages:t.messages}:{},...L(t.window,1,p.window)?{window:t.window}:{},...t.bytes===!0?{bytes:!0}:{}};if(t.type==="refused"&&typeof t.reason==="string"&&/^[a-z_]{1,32}$/.test(t.reason))return{type:"refused",binding:C(t.binding),reason:t.reason};if(!pe(t.id))throw Error("preview_frame_invalid");if(t.type==="end"||t.type==="cancel"||t.type==="credit")return{type:t.type,id:t.id};if(t.type==="ws"&&typeof t.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(t.protocol))return{type:"ws",id:t.id,protocol:t.protocol};if(t.type==="data"&&typeof t.data==="string"&&typeof t.binary==="boolean")return z(t.data,p.upload),{type:"data",id:t.id,data:t.data,binary:t.binary};if(t.type==="head"&&L(t.status,200,599)&&ue(t.headers))return{type:"head",id:t.id,status:t.status,headers:t.headers};if(t.type==="request"&&typeof t.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(t.method)&&typeof t.path==="string"&&ue(t.headers)&&typeof t.body==="string"&&typeof t.upgrade==="boolean")return z(t.body,p.upload),{type:"request",id:t.id,method:t.method,path:H(t.path),headers:t.headers,body:t.body,upgrade:t.upgrade};throw Error("preview_frame_invalid")}function ee(e){let t=[...e],n=new Set(t.filter(([s])=>s.toLowerCase()==="connection").flatMap(([,s])=>s.toLowerCase().split(",").map((i)=>i.trim()))),o=new Set(["authorization","proxy-authorization","cookie","set-cookie","host","origin","referer","connection","upgrade","keep-alive","transfer-encoding","te","trailer","content-length","forwarded","alt-svc","service-worker-allowed","clear-site-data","refresh"]);return t.filter(([s])=>!o.has(s.toLowerCase())&&!n.has(s.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(s))}async function re(e){let t;try{return await Promise.race([Promise.resolve().then(e).then((n)=>n===!0||(n===!1?!1:void 0),()=>{return}),new Promise((n)=>{t=setTimeout(()=>n(void 0),p.authorizationMs)})])}finally{clearTimeout(t)}}async function Mt(e){return await re(e)===!0}function J(e,t){let n=new URL(e);if(n.username||n.password||n.search||n.hash||!(n.protocol==="wss:"||n.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(n.hostname))||!new RegExp(`^/${t}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(n.pathname))throw Error("preview_relay_invalid");return n.href}function ut(e){if(!Z(e)||Object.keys(e).length!==2||typeof e.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:C(e.binding),deviceRelayUrl:J(e.deviceRelayUrl,"device")}}function lo(e){if(!Z(e)||Object.keys(e).length!==1||!("binding"in e))throw Error("preview_close_invalid");return{binding:C(e.binding)}}var be="x-preview-connection";async function he(e,t){if(t.aborted)throw Error("preview_closed");let n=Re(32).toString("base64url"),o=new Set,s=!1,i=Le((c)=>{if(s||t.aborted||o.size>=p.streams*2)return c.destroy();o.add(c);let d=new AbortController;c.once("close",()=>{o.delete(c),d.abort()}),c.on("error",()=>c.destroy()),c.setTimeout(2000,()=>c.destroy());let b=Buffer.alloc(0),m=(g)=>{b=Buffer.concat([b,g]);let w=b.indexOf(`\r
2
+ import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{Ie,De}from"./vm-hands-entry-lite-1kt82jes.js";import{request as Ce}from"http";import{pipeline as Ne}from"stream";import{constants as te,createBrotliCompress as $e,createGzip as Me}from"zlib";import{WebSocket as U}from"ws";import{randomBytes as Re,timingSafeEqual as Be}from"crypto";import{createServer as Le}from"net";var p={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000,window:8};function Z(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function L(e,t,n=Number.MAX_SAFE_INTEGER){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=t&&e<=n}function pe(e){return typeof e==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(e)}function fe(e,t){let n=Buffer.from(e,"latin1");return Buffer.concat([Buffer.from([n.length]),n,t])}function C(e){if(!Z(e)||Object.keys(e).length!==12||![e.organizationId,e.userId,e.runId,e.deviceId,e.rootId,e.jobId,e.fenceId].every(pe)||!L(e.attachmentRevision,0)||!L(e.grantRevision,1)||!L(e.generation,1)||!L(e.port,1024,65535)||!L(e.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...e})}function ze(e,t){return Object.keys(e).every((n)=>e[n]===t[n])}function H(e){if(e.length>4096||!e.startsWith("/")||e.startsWith("//")||/[\\\x00-\x20\x7f#]/.test(e))throw Error("preview_path_invalid");let t=decodeURIComponent(e);if(t.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(t))throw Error("preview_path_invalid");return e}function ue(e){return Array.isArray(e)&&e.length<=64&&e.every((t)=>Array.isArray(t)&&t.length===2&&typeof t[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(t[0])&&typeof t[1]==="string"&&t[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(t[1]))}function z(e,t=p.chunk){if(e.length>Math.ceil(t/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw Error("preview_data_invalid");let n=Buffer.from(e,"base64");if(n.length>t)throw Error("preview_data_too_large");return n}function me(e){if(Array.isArray(e))return Buffer.concat(e);if(typeof e==="string")return Buffer.from(e,"utf8");if(e instanceof ArrayBuffer)return Buffer.from(e);return e}function ge(e){if(Buffer.byteLength(e)>p.upload*1.4+300000)throw Error("preview_frame_too_large");let t=JSON.parse(e);if(!Z(t))throw Error("preview_frame_invalid");if(t.type==="hello")return{type:"hello",binding:C(t.binding),...L(t.messages,p.chunk,p.upload)?{messages:t.messages}:{},...L(t.window,1,p.window)?{window:t.window}:{},...t.bytes===!0?{bytes:!0}:{}};if(t.type==="refused"&&typeof t.reason==="string"&&/^[a-z_]{1,32}$/.test(t.reason))return{type:"refused",binding:C(t.binding),reason:t.reason};if(!pe(t.id))throw Error("preview_frame_invalid");if(t.type==="end"||t.type==="cancel"||t.type==="credit")return{type:t.type,id:t.id};if(t.type==="ws"&&typeof t.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(t.protocol))return{type:"ws",id:t.id,protocol:t.protocol};if(t.type==="data"&&typeof t.data==="string"&&typeof t.binary==="boolean")return z(t.data,p.upload),{type:"data",id:t.id,data:t.data,binary:t.binary};if(t.type==="head"&&L(t.status,200,599)&&ue(t.headers))return{type:"head",id:t.id,status:t.status,headers:t.headers};if(t.type==="request"&&typeof t.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(t.method)&&typeof t.path==="string"&&ue(t.headers)&&typeof t.body==="string"&&typeof t.upgrade==="boolean")return z(t.body,p.upload),{type:"request",id:t.id,method:t.method,path:H(t.path),headers:t.headers,body:t.body,upgrade:t.upgrade};throw Error("preview_frame_invalid")}function ee(e){let t=[...e],n=new Set(t.filter(([s])=>s.toLowerCase()==="connection").flatMap(([,s])=>s.toLowerCase().split(",").map((i)=>i.trim()))),o=new Set(["authorization","proxy-authorization","cookie","set-cookie","host","origin","referer","connection","upgrade","keep-alive","transfer-encoding","te","trailer","content-length","forwarded","alt-svc","service-worker-allowed","clear-site-data","refresh"]);return t.filter(([s])=>!o.has(s.toLowerCase())&&!n.has(s.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(s))}async function re(e){let t;try{return await Promise.race([Promise.resolve().then(e).then((n)=>n===!0||(n===!1?!1:void 0),()=>{return}),new Promise((n)=>{t=setTimeout(()=>n(void 0),p.authorizationMs)})])}finally{clearTimeout(t)}}async function Mt(e){return await re(e)===!0}function J(e,t){let n=new URL(e);if(n.username||n.password||n.search||n.hash||!(n.protocol==="wss:"||n.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(n.hostname))||!new RegExp(`^/${t}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(n.pathname))throw Error("preview_relay_invalid");return n.href}function ut(e){if(!Z(e)||Object.keys(e).length!==2||typeof e.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:C(e.binding),deviceRelayUrl:J(e.deviceRelayUrl,"device")}}function uo(e){if(!Z(e)||Object.keys(e).length!==1||!("binding"in e))throw Error("preview_close_invalid");return{binding:C(e.binding)}}var be="x-preview-connection";async function he(e,t){if(t.aborted)throw Error("preview_closed");let n=Re(32).toString("base64url"),o=new Set,s=!1,i=Le((c)=>{if(s||t.aborted||o.size>=p.streams*2)return c.destroy();o.add(c);let d=new AbortController;c.once("close",()=>{o.delete(c),d.abort()}),c.on("error",()=>c.destroy()),c.setTimeout(2000,()=>c.destroy());let b=Buffer.alloc(0),m=(g)=>{b=Buffer.concat([b,g]);let w=b.indexOf(`\r
3
3
  \r
4
4
  `);if(w<0){if(b.length>16384)c.destroy();return}if(c.pause(),c.off("data",m),w>16384||b.length>p.upload+16384)return c.destroy();l(b,w).catch(()=>c.destroy())};c.on("data",m);async function l(g,w){let y=g.subarray(0,w).toString("latin1").split(`\r
5
5
  `),_=/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) (\S+) HTTP\/1\.1$/.exec(y.shift()??"");if(!_)throw Error("preview_request_invalid");H(_[2]);let k=!1,O=0,T=[];for(let B of y){let S=/^([a-zA-Z0-9-]+):[ \t]*([^\x00-\x08\x0a-\x1f\x7f]*)$/.exec(B);if(!S)throw Error("preview_header_invalid");if(S[1].toLowerCase()===be){O++;let N=Buffer.from(S[2].trim());k=N.length===n.length&&Be(N,Buffer.from(n))}else if(S[1].toLowerCase()!=="host")T.push(B)}if(!k||O!==1||s||d.signal.aborted)throw Error("preview_connection_denied");let v=await e.connect(d.signal);if(s||d.signal.aborted)throw v.destroy(),Error("preview_closed");o.add(v),v.on("error",()=>c.destroy()),v.once("close",()=>{o.delete(v),c.destroy()}),c.once("close",()=>v.destroy()),c.setTimeout(0);let P=[`${_[1]} ${_[2]} HTTP/1.1`,`Host: 127.0.0.1:${v.remotePort}`,...T,"",""].join(`\r
6
6
  `);v.write(Buffer.concat([Buffer.from(P,"latin1"),g.subarray(w+4)])),v.pipe(c),c.pipe(v),c.resume()}});await new Promise((c,d)=>{i.once("error",d),i.listen(0,"127.0.0.1",c)});let a=i.address();if(!a||typeof a==="string")throw i.close(),Error("preview_bind_failed");function u(){if(s)return;s=!0,t.removeEventListener("abort",u);for(let c of o)c.destroy();o.clear(),i.close()}if(t.addEventListener("abort",u,{once:!0}),t.aborted)u();return{port:a.port,headers:{[be]:n},close:u}}var Oe=60000,Fe=1e4,He=5000,Ue=/^(?:text\/(?!event-stream)|application\/(?:(?:x-)?javascript|json|[a-z.+-]*\+json|xml|[a-z.+-]*\+xml|wasm)|image\/svg\+xml)/i;function je(e,t,n,o){let s=(c)=>t.find(([d])=>d.toLowerCase()===c)?.[1],i=(c)=>o.find(([d])=>d.toLowerCase()===c)?.[1],a=Number(i("content-length")??Number.NaN);if(e!=="GET"||n!==200||s("range")!==void 0||i("content-encoding")!==void 0||!Ue.test(i("content-type")??"")||/\bno-transform\b/i.test(i("cache-control")??"")||a<1024)return null;let u=(c)=>new RegExp(`(?:^|,)\\s*${c}\\s*(?:,|$|;\\s*q=(?:1|0?\\.0*[1-9]))`,"i").test(s("accept-encoding")??"");return u("br")?"br":u("gzip")?"gzip":null}function qe(e,t){let n=e.filter(([o])=>o.toLowerCase()==="vary").map(([,o])=>o).join(", ");return[...e.filter(([o])=>!["vary","etag","content-md5"].includes(o.toLowerCase())),...e.filter(([o])=>o.toLowerCase()==="etag").map(([o,s])=>[o,s.startsWith("W/")?s:`W/${s}`]),["Content-Encoding",t],["Vary",n.split(",").some((o)=>/^\s*(?:accept-encoding|\*)\s*$/i.test(o))?n:n?`${n}, Accept-Encoding`:"Accept-Encoding"]]}async function An(e){process.stderr.write(`${JSON.stringify({event:"worker_preview.open_refused",job_id:e.jobId,port:e.port,reason_code:e.reason})}
7
- `);let t=e.binding,n;try{n=J(e.deviceRelayUrl,"device")}catch{return}if(!t)return;await new Promise((o)=>{let s=new U(n,{followRedirects:!1,perMessageDeflate:!1,maxPayload:4096}),i=setTimeout(()=>{s.terminate(),o()},p.authorizationMs*2);s.addEventListener("open",()=>{s.send(JSON.stringify({type:"refused",binding:t,reason:e.reason})),s.close(1000,`worker_refused_${e.reason}`)}),s.addEventListener("error",()=>{clearTimeout(i),o()}),s.addEventListener("close",()=>{clearTimeout(i),o()})})}async function Ke(e,t){let n=Date.now()+Fe,o;for(;;){if(!t())return"closed";let s=o??=e.refusal().finally(()=>{o=void 0}),i,a=await Promise.race([s.catch(()=>"port_unproved"),new Promise((u)=>{i=setTimeout(()=>u("port_check_timeout"),p.authorizationMs)})]).finally(()=>clearTimeout(i));if(a===null)return null;if(!["listener_unproved","port_check_timeout"].includes(a)||Date.now()+500>=n)return a;await new Promise((u)=>setTimeout(u,500))}}async function _e(e){let t=C(e.binding),n=()=>!e.signal.aborted&&Date.now()<t.expiresAtMs,o=t.expiresAtMs>Date.now()+p.lifetimeMs+He?"binding_mismatch":await Ke(e.port,n);if(o)throw await An({deviceRelayUrl:e.deviceRelayUrl,binding:t,jobId:t.jobId,port:t.port,reason:o}),Error("preview_not_authorized",{cause:o});let s=J(e.deviceRelayUrl,"device"),i=await he(e.port,e.signal),a;try{a=new U(s,{followRedirects:!1,perMessageDeflate:!1,maxPayload:p.upload*1.4+300000})}catch(f){throw i.close(),f}let u=new Map,c=!1,d=!1,b=0,m=!1,l,g,w,y=new Promise((f)=>{w=f}),_,k,O=new Promise((f,h)=>{_=f,k=h}),T=!1,v=(f)=>{let h=Buffer.isBuffer(f)?f:JSON.stringify(f);if(b+=Buffer.byteLength(h),!n()||d||a.readyState!==U.OPEN)return P(n()?"relay_closed":"expired");if(a.bufferedAmount>p.relayBuffered)return P("relay_backlog");if(b>p.total)return P("quota");a.send(h)};function P(f="closed"){if(d)return;d=!0,clearInterval(N),clearTimeout(S),e.signal.removeEventListener("abort",B);for(let h of u.values())h.stop();u.clear(),i.close(),a.close(1000,`worker_${f}`),k(Error("preview_closed")),w()}let B=()=>P("aborted"),S=setTimeout(()=>P("pair_timeout"),p.requestMs),N=setInterval(async()=>{if(!n())return P(e.signal.aborted?"aborted":"expired");if(m)return;m=!0;try{let f=l??=Promise.resolve().then(()=>e.port.check()).finally(()=>{l=void 0}),h=await re(()=>f);if(h===!1)return P("port_refused");if(h){g=void 0;return}if(Date.now()-(g??=Date.now())>Oe)return P("port_unknown");for(let E of u.values())E.stop()}finally{m=!1}},1000);if(e.signal.addEventListener("abort",B,{once:!0}),!n())P(e.signal.aborted?"aborted":"expired");a.addEventListener("open",()=>v({type:"hello",binding:t,messages:p.upload,window:p.window})),a.addEventListener("close",()=>P("relay_closed")),a.addEventListener("error",()=>P("relay_error")),a.addEventListener("message",(f)=>{try{if(!n()||d)return P(e.signal.aborted?"aborted":"expired");if(typeof f.data!=="string")throw Error("preview_frame_invalid");if(b+=Buffer.byteLength(f.data),b>p.total)return P("quota");let h=ge(f.data);if(!c){if(h.type!=="hello"||!ze(t,h.binding))return P("binding_mismatch");c=!0,T=h.bytes===!0,clearTimeout(S),_();return}if(h.type==="hello"||h.type==="refused")return P("invalid_frame");if(h.type==="request"){D(h).catch(()=>P("invalid_request"));return}let E=u.get(h.id);if(!E)return;if(h.type==="cancel"||h.type==="end")E.stop();else if(h.type==="credit"&&E.credit)E.credit();else if(h.type==="data"&&E.ws){if(E.ws.readyState!==U.OPEN||E.ws.bufferedAmount>p.buffered)return E.stop();let I=z(h.data,p.upload);E.ws.send(h.binary?I:I.toString("utf8"))}else P("invalid_frame")}catch{P("invalid_frame")}});async function D(f){if(u.has(f.id)||u.size>=p.streams)return P("stream_limit");if(!n())return P(e.signal.aborted?"aborted":"expired");let h=new AbortController,E,I,q,Y=0,R=(W=!1)=>{if(!u.delete(f.id))return;clearTimeout(E),h.abort(),I?.close(1000,"preview_closed"),q?.(),v({type:W?"end":"cancel",id:f.id})},ie={stop:()=>R(),credit:()=>{Y++,q?.()}};if(u.set(f.id,ie),E=setTimeout(R,p.requestMs),!await Mt(()=>e.port.check())||!n()||h.signal.aborted)return R();let ae=H(f.path);if(f.upgrade){if(f.method!=="GET"||f.body)return R();let W=f.headers.find(([A])=>A.toLowerCase()==="sec-websocket-protocol")?.[1].split(",").map((A)=>A.trim());if(W?.some((A)=>!/^[a-zA-Z0-9._-]{1,100}$/.test(A))||(W?.length??0)>8)return R();I=new U(`ws://127.0.0.1:${i.port}${ae}`,W,{headers:i.headers,followRedirects:!1,perMessageDeflate:!1,maxPayload:p.upload}),ie.ws=I,I.binaryType="arraybuffer",I.addEventListener("open",()=>{clearTimeout(E),v({type:"ws",id:f.id,protocol:I.protocol})}),I.addEventListener("message",(A)=>{let K=typeof A.data!=="string",M=me(A.data);if(M.length>p.upload)return R();v({type:"data",id:f.id,data:M.toString("base64"),binary:K})}),I.addEventListener("error",()=>R()),I.addEventListener("close",(A)=>R(A.wasClean));return}let Te=z(f.body,p.upload),de=Ce({hostname:"127.0.0.1",port:i.port,path:ae,method:f.method,headers:{...Object.fromEntries(ee(f.headers)),...i.headers,connection:"close"},signal:h.signal,agent:!1,maxHeaderSize:16384},async(W)=>{try{let A=[];for(let F=0;F<W.rawHeaders.length;F+=2)A.push([W.rawHeaders[F],W.rawHeaders[F+1]]);let K=W.statusCode??502,M=je(f.method,f.headers,K,A),Q=M==="br"?$e({flush:te.BROTLI_OPERATION_FLUSH,params:{[te.BROTLI_PARAM_QUALITY]:5}}):M==="gzip"?Me({level:6,flush:te.Z_SYNC_FLUSH}):void 0;if(v({type:"head",id:f.id,status:K,headers:ee(M?qe(A,M):A)}),clearTimeout(E),Q)Ne(W,Q,()=>{});for await(let F of Q??W){let ce=Buffer.from(F);for(let G=0;G<ce.length;G+=p.chunk){if(Y===0&&!h.signal.aborted)await new Promise((We)=>{q=We});if(q=void 0,h.signal.aborted)return;Y--;let le=ce.subarray(G,G+p.chunk);v(T?fe(f.id,le):{type:"data",id:f.id,data:le.toString("base64"),binary:!0})}}R(!0)}catch{R()}});de.on("error",()=>R()),de.end(Te)}return await O,{close:P,closed:y}}import{execFile as Ge}from"child_process";import{createRequire as Ze}from"module";import{win32 as V}from"path";var Je=250,Ve=50,Xe=250,Ye=4194304;function Pe(e){let t=/^(?:\[([^\]]+)\]|([^:]+)):([0-9]{1,5})$/.exec(e??""),n=Number(t?.[3]);return t&&n<=65535?{address:t[1]??t[2],port:n}:null}function Qe(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim().split(/\s+/);if(o[0]!=="TCP"||o.length<5)continue;let s=Pe(o[1]),i=Pe(o[2]),a=Number(o.at(-1));if(!s||!i||!Number.isSafeInteger(a)||a<0)continue;t.push({pid:a,localAddress:s.address,localPort:s.port,remoteAddress:i.address,remotePort:i.port,listening:i.port===0})}return t}function er(e){if(e.localAddress==="0.0.0.0"||e.localAddress==="::")return`*:${e.localPort}`;return e.localAddress.includes(":")?`[${e.localAddress}]:${e.localPort}`:`${e.localAddress}:${e.localPort}`}var ke=(e)=>new Promise((t,n)=>Ge(V.join(Ie("win32").split(";")[0],"NETSTAT.EXE"),["-ano"],{timeout:e,maxBuffer:Ye,encoding:"utf8",windowsHide:!0,env:De()},(o,s)=>o?n(o):t(s)));function ne(e){let t=V.normalize(e.startsWith("\\\\?\\")?e.slice(4):e);return t.length>3&&t.endsWith("\\")?t.slice(0,-1):t}function rr(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return o===n||o.startsWith(n.endsWith("\\")?n:`${n}\\`)}function xe(e,t,n){let o=e.cwd(n),s=o?ne(o):null;return s&&V.isAbsolute(s)&&rr(t,s)?s:null}var j;function ye(){if(j!==void 0)return j;if(j=null,process.platform!=="win32"||!["x64","arm64"].includes(process.arch))return null;let e;try{e=Ze(import.meta.url)("bun:ffi")}catch{return null}let{FFIType:t,ptr:n}=e,o,s;try{o=e.dlopen("kernel32.dll",{CreateToolhelp32Snapshot:{args:[t.u32,t.u32],returns:t.u64},Process32FirstW:{args:[t.u64,t.ptr],returns:t.i32},Process32NextW:{args:[t.u64,t.ptr],returns:t.i32},OpenProcess:{args:[t.u32,t.i32,t.u32],returns:t.u64},ReadProcessMemory:{args:[t.u64,t.u64,t.ptr,t.u64,t.ptr],returns:t.i32},CloseHandle:{args:[t.u64],returns:t.i32}}).symbols,s=e.dlopen("ntdll.dll",{NtQueryInformationProcess:{args:[t.u64,t.i32,t.ptr,t.u32,t.ptr],returns:t.i32}}).symbols}catch{return null}let i=0xFFFFFFFFFFFFFFFFn,a=2,u=1040,c=568,d=(b,m,l)=>{let g=Buffer.alloc(l);return o.ReadProcessMemory(b,m,n(g),l,null)?g:null};return j={processes(){let b=BigInt(o.CreateToolhelp32Snapshot(a,0));if(b===i)throw new r("process_inspection_failed","Reading this computer's processes did not complete.");try{let m=Buffer.alloc(c);m.writeUInt32LE(c,0);let l=n(m),g=[];for(let w=o.Process32FirstW(b,l);w;w=o.Process32NextW(b,l)){let y=m.toString("utf16le",44,c),_=y.slice(0,y.includes("\x00")?y.indexOf("\x00"):void 0),k=m.readUInt32LE(8);if(k>0)g.push({pid:k,parentPid:m.readUInt32LE(32),command:_.replace(/\.exe$/i,"")||null})}return g}finally{o.CloseHandle(b)}},cwd(b){let m=BigInt(o.OpenProcess(u,0,b));if(m===0n)return null;try{let l=Buffer.alloc(48);if(s.NtQueryInformationProcess(m,0,n(l),l.length,null)!==0)return null;let g=d(m,l.readBigUInt64LE(8)+0x20n,8)?.readBigUInt64LE(0),w=g?d(m,g+0x38n,16):null,y=w?.readUInt16LE(0)??0;if(!w||y===0||y%2!==0)return null;return d(m,w.readBigUInt64LE(8),y)?.toString("utf16le")??null}finally{o.CloseHandle(m)}}},j}function oe(e){if(!e)throw new r("process_inspection_failed","Reading this computer's processes is unavailable.");return e}async function Se(e,t){let n;try{n=await e(t)}catch{throw new r("process_inspection_failed","Reading this computer's ports did not complete.")}return Qe(n)}async function uo(e,t=ye()){let n=oe(t),o=ne(e),s=[];for(let i of n.processes()){if(s.length>=Je)break;let a=xe(n,o,i.pid);if(a)s.push({pid:i.pid,command:i.command,cwd:V.relative(o,a)||"."})}return{processes:s}}async function po(e,t=ye(),n=ke){let o=oe(t),s=ne(e),i=(await Se(n,5000)).filter((d)=>d.listening&&d.pid>0).map((d)=>({pid:d.pid,port:d.localPort,address:er(d)})).sort((d,b)=>d.pid-b.pid||d.port-b.port||(d.address<b.address?-1:d.address>b.address?1:0)),a=[...new Set(i.map((d)=>d.pid))].slice(0,Ve),u=new Set(a.filter((d)=>xe(o,s,d)!==null));if(u.size===0)return{ports:[]};let c=new Map(o.processes().map((d)=>[d.pid,d.command]));return{ports:i.filter((d)=>u.has(d.pid)).slice(0,Xe).map((d)=>({pid:d.pid,command:c.get(d.pid)??null,address:d.address}))}}function ve(e,t){let n=new Set([t]);for(let o=!0;o;){o=!1;for(let s of e)if(!n.has(s.pid)&&n.has(s.parentPid)&&s.pid!==s.parentPid)n.add(s.pid),o=!0}return n}function tr(e,t,n,o){let s=(i)=>i==="127.0.0.1"||i==="::ffff:127.0.0.1"||i==="::1";return e.flatMap((i)=>{if(!t.has(i.pid)||i.localPort!==o)return[];let a=i.listening&&(s(i.localAddress)||["0.0.0.0","::"].includes(i.localAddress)),u=!i.listening&&s(i.localAddress)&&s(i.remoteAddress);if(!a&&!u)return[];let c=`${i.localAddress}:${i.localPort}>${i.remoteAddress}:${i.remotePort}`;return[{pid:i.pid,processGroupId:n,descriptor:String(i.pid),kernelId:c,state:a?"listen":"established",port:o,peerPort:a?null:i.remotePort,host:i.localAddress==="::1"?"::1":"127.0.0.1"}]})}async function Ee(e,t,n=ye(),o=ke){let s=oe(n),i=ve(s.processes(),e),a=await Se(o,1000),u=ve(s.processes(),e);return tr(a,new Set([...i].filter((c)=>u.has(c))),e,t)}import{execFile as nr}from"child_process";import{readFile as or,readdir as sr,readlink as ir}from"fs/promises";import{connect as ar}from"net";import{setTimeout as dr}from"timers/promises";var cr={directory:sr,text:(e)=>or(e,"utf8"),link:ir};class se extends Error{code;constructor(e="port_unproved"){super("preview_port_ownership_unproved");this.code=e}}var x=(e)=>new se(e),X="preview_listener_unproved",Ae="00000000000000000000000001000000";async function lr(e,t,n=cr){let o=new Map;for(let a of["tcp","tcp6"]){let u=await n.text(`/proc/net/${a}`);if(u.length>4194304)throw x();for(let c of u.split(`
7
+ `);let t=e.binding,n;try{n=J(e.deviceRelayUrl,"device")}catch{return}if(!t)return;await new Promise((o)=>{let s=new U(n,{followRedirects:!1,perMessageDeflate:!1,maxPayload:4096}),i=setTimeout(()=>{s.terminate(),o()},p.authorizationMs*2);s.addEventListener("open",()=>{s.send(JSON.stringify({type:"refused",binding:t,reason:e.reason})),s.close(1000,`worker_refused_${e.reason}`)}),s.addEventListener("error",()=>{clearTimeout(i),o()}),s.addEventListener("close",()=>{clearTimeout(i),o()})})}async function Ke(e,t){let n=Date.now()+Fe,o;for(;;){if(!t())return"closed";let s=o??=e.refusal().finally(()=>{o=void 0}),i,a=await Promise.race([s.catch(()=>"port_unproved"),new Promise((u)=>{i=setTimeout(()=>u("port_check_timeout"),p.authorizationMs)})]).finally(()=>clearTimeout(i));if(a===null)return null;if(!["listener_unproved","port_check_timeout"].includes(a)||Date.now()+500>=n)return a;await new Promise((u)=>setTimeout(u,500))}}async function _e(e){let t=C(e.binding),n=()=>!e.signal.aborted&&Date.now()<t.expiresAtMs,o=t.expiresAtMs>Date.now()+p.lifetimeMs+He?"binding_mismatch":await Ke(e.port,n);if(o)throw await An({deviceRelayUrl:e.deviceRelayUrl,binding:t,jobId:t.jobId,port:t.port,reason:o}),Error("preview_not_authorized",{cause:o});let s=J(e.deviceRelayUrl,"device"),i=await he(e.port,e.signal),a;try{a=new U(s,{followRedirects:!1,perMessageDeflate:!1,maxPayload:p.upload*1.4+300000})}catch(f){throw i.close(),f}let u=new Map,c=!1,d=!1,b=0,m=!1,l,g,w,y=new Promise((f)=>{w=f}),_,k,O=new Promise((f,h)=>{_=f,k=h}),T=!1,v=(f)=>{let h=Buffer.isBuffer(f)?f:JSON.stringify(f);if(b+=Buffer.byteLength(h),!n()||d||a.readyState!==U.OPEN)return P(n()?"relay_closed":"expired");if(a.bufferedAmount>p.relayBuffered)return P("relay_backlog");if(b>p.total)return P("quota");a.send(h)};function P(f="closed"){if(d)return;d=!0,clearInterval(N),clearTimeout(S),e.signal.removeEventListener("abort",B);for(let h of u.values())h.stop();u.clear(),i.close(),a.close(1000,`worker_${f}`),k(Error("preview_closed")),w()}let B=()=>P("aborted"),S=setTimeout(()=>P("pair_timeout"),p.requestMs),N=setInterval(async()=>{if(!n())return P(e.signal.aborted?"aborted":"expired");if(m)return;m=!0;try{let f=l??=Promise.resolve().then(()=>e.port.check()).finally(()=>{l=void 0}),h=await re(()=>f);if(h===!1)return P("port_refused");if(h){g=void 0;return}if(Date.now()-(g??=Date.now())>Oe)return P("port_unknown");for(let E of u.values())E.stop()}finally{m=!1}},1000);if(e.signal.addEventListener("abort",B,{once:!0}),!n())P(e.signal.aborted?"aborted":"expired");a.addEventListener("open",()=>v({type:"hello",binding:t,messages:p.upload,window:p.window})),a.addEventListener("close",()=>P("relay_closed")),a.addEventListener("error",()=>P("relay_error")),a.addEventListener("message",(f)=>{try{if(!n()||d)return P(e.signal.aborted?"aborted":"expired");if(typeof f.data!=="string")throw Error("preview_frame_invalid");if(b+=Buffer.byteLength(f.data),b>p.total)return P("quota");let h=ge(f.data);if(!c){if(h.type!=="hello"||!ze(t,h.binding))return P("binding_mismatch");c=!0,T=h.bytes===!0,clearTimeout(S),_();return}if(h.type==="hello"||h.type==="refused")return P("invalid_frame");if(h.type==="request"){D(h).catch(()=>P("invalid_request"));return}let E=u.get(h.id);if(!E)return;if(h.type==="cancel"||h.type==="end")E.stop();else if(h.type==="credit"&&E.credit)E.credit();else if(h.type==="data"&&E.ws){if(E.ws.readyState!==U.OPEN||E.ws.bufferedAmount>p.buffered)return E.stop();let I=z(h.data,p.upload);E.ws.send(h.binary?I:I.toString("utf8"))}else P("invalid_frame")}catch{P("invalid_frame")}});async function D(f){if(u.has(f.id)||u.size>=p.streams)return P("stream_limit");if(!n())return P(e.signal.aborted?"aborted":"expired");let h=new AbortController,E,I,q,Y=0,R=(W=!1)=>{if(!u.delete(f.id))return;clearTimeout(E),h.abort(),I?.close(1000,"preview_closed"),q?.(),v({type:W?"end":"cancel",id:f.id})},ie={stop:()=>R(),credit:()=>{Y++,q?.()}};if(u.set(f.id,ie),E=setTimeout(R,p.requestMs),!await Mt(()=>e.port.check())||!n()||h.signal.aborted)return R();let ae=H(f.path);if(f.upgrade){if(f.method!=="GET"||f.body)return R();let W=f.headers.find(([A])=>A.toLowerCase()==="sec-websocket-protocol")?.[1].split(",").map((A)=>A.trim());if(W?.some((A)=>!/^[a-zA-Z0-9._-]{1,100}$/.test(A))||(W?.length??0)>8)return R();I=new U(`ws://127.0.0.1:${i.port}${ae}`,W,{headers:i.headers,followRedirects:!1,perMessageDeflate:!1,maxPayload:p.upload}),ie.ws=I,I.binaryType="arraybuffer",I.addEventListener("open",()=>{clearTimeout(E),v({type:"ws",id:f.id,protocol:I.protocol})}),I.addEventListener("message",(A)=>{let K=typeof A.data!=="string",M=me(A.data);if(M.length>p.upload)return R();v({type:"data",id:f.id,data:M.toString("base64"),binary:K})}),I.addEventListener("error",()=>R()),I.addEventListener("close",(A)=>R(A.wasClean));return}let Te=z(f.body,p.upload),de=Ce({hostname:"127.0.0.1",port:i.port,path:ae,method:f.method,headers:{...Object.fromEntries(ee(f.headers)),...i.headers,connection:"close"},signal:h.signal,agent:!1,maxHeaderSize:16384},async(W)=>{try{let A=[];for(let F=0;F<W.rawHeaders.length;F+=2)A.push([W.rawHeaders[F],W.rawHeaders[F+1]]);let K=W.statusCode??502,M=je(f.method,f.headers,K,A),Q=M==="br"?$e({flush:te.BROTLI_OPERATION_FLUSH,params:{[te.BROTLI_PARAM_QUALITY]:5}}):M==="gzip"?Me({level:6,flush:te.Z_SYNC_FLUSH}):void 0;if(v({type:"head",id:f.id,status:K,headers:ee(M?qe(A,M):A)}),clearTimeout(E),Q)Ne(W,Q,()=>{});for await(let F of Q??W){let ce=Buffer.from(F);for(let G=0;G<ce.length;G+=p.chunk){if(Y===0&&!h.signal.aborted)await new Promise((We)=>{q=We});if(q=void 0,h.signal.aborted)return;Y--;let le=ce.subarray(G,G+p.chunk);v(T?fe(f.id,le):{type:"data",id:f.id,data:le.toString("base64"),binary:!0})}}R(!0)}catch{R()}});de.on("error",()=>R()),de.end(Te)}return await O,{close:P,closed:y}}import{execFile as Ge}from"child_process";import{createRequire as Ze}from"module";import{win32 as V}from"path";var Je=250,Ve=50,Xe=250,Ye=4194304;function Pe(e){let t=/^(?:\[([^\]]+)\]|([^:]+)):([0-9]{1,5})$/.exec(e??""),n=Number(t?.[3]);return t&&n<=65535?{address:t[1]??t[2],port:n}:null}function Qe(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim().split(/\s+/);if(o[0]!=="TCP"||o.length<5)continue;let s=Pe(o[1]),i=Pe(o[2]),a=Number(o.at(-1));if(!s||!i||!Number.isSafeInteger(a)||a<0)continue;t.push({pid:a,localAddress:s.address,localPort:s.port,remoteAddress:i.address,remotePort:i.port,listening:i.port===0})}return t}function er(e){if(e.localAddress==="0.0.0.0"||e.localAddress==="::")return`*:${e.localPort}`;return e.localAddress.includes(":")?`[${e.localAddress}]:${e.localPort}`:`${e.localAddress}:${e.localPort}`}var ke=(e)=>new Promise((t,n)=>Ge(V.join(Ie("win32").split(";")[0],"NETSTAT.EXE"),["-ano"],{timeout:e,maxBuffer:Ye,encoding:"utf8",windowsHide:!0,env:De()},(o,s)=>o?n(o):t(s)));function ne(e){let t=V.normalize(e.startsWith("\\\\?\\")?e.slice(4):e);return t.length>3&&t.endsWith("\\")?t.slice(0,-1):t}function rr(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return o===n||o.startsWith(n.endsWith("\\")?n:`${n}\\`)}function xe(e,t,n){let o=e.cwd(n),s=o?ne(o):null;return s&&V.isAbsolute(s)&&rr(t,s)?s:null}var j;function ye(){if(j!==void 0)return j;if(j=null,process.platform!=="win32"||!["x64","arm64"].includes(process.arch))return null;let e;try{e=Ze(import.meta.url)("bun:ffi")}catch{return null}let{FFIType:t,ptr:n}=e,o,s;try{o=e.dlopen("kernel32.dll",{CreateToolhelp32Snapshot:{args:[t.u32,t.u32],returns:t.u64},Process32FirstW:{args:[t.u64,t.ptr],returns:t.i32},Process32NextW:{args:[t.u64,t.ptr],returns:t.i32},OpenProcess:{args:[t.u32,t.i32,t.u32],returns:t.u64},ReadProcessMemory:{args:[t.u64,t.u64,t.ptr,t.u64,t.ptr],returns:t.i32},CloseHandle:{args:[t.u64],returns:t.i32}}).symbols,s=e.dlopen("ntdll.dll",{NtQueryInformationProcess:{args:[t.u64,t.i32,t.ptr,t.u32,t.ptr],returns:t.i32}}).symbols}catch{return null}let i=0xFFFFFFFFFFFFFFFFn,a=2,u=1040,c=568,d=(b,m,l)=>{let g=Buffer.alloc(l);return o.ReadProcessMemory(b,m,n(g),l,null)?g:null};return j={processes(){let b=BigInt(o.CreateToolhelp32Snapshot(a,0));if(b===i)throw new r("process_inspection_failed","Reading this computer's processes did not complete.");try{let m=Buffer.alloc(c);m.writeUInt32LE(c,0);let l=n(m),g=[];for(let w=o.Process32FirstW(b,l);w;w=o.Process32NextW(b,l)){let y=m.toString("utf16le",44,c),_=y.slice(0,y.includes("\x00")?y.indexOf("\x00"):void 0),k=m.readUInt32LE(8);if(k>0)g.push({pid:k,parentPid:m.readUInt32LE(32),command:_.replace(/\.exe$/i,"")||null})}return g}finally{o.CloseHandle(b)}},cwd(b){let m=BigInt(o.OpenProcess(u,0,b));if(m===0n)return null;try{let l=Buffer.alloc(48);if(s.NtQueryInformationProcess(m,0,n(l),l.length,null)!==0)return null;let g=d(m,l.readBigUInt64LE(8)+0x20n,8)?.readBigUInt64LE(0),w=g?d(m,g+0x38n,16):null,y=w?.readUInt16LE(0)??0;if(!w||y===0||y%2!==0)return null;return d(m,w.readBigUInt64LE(8),y)?.toString("utf16le")??null}finally{o.CloseHandle(m)}}},j}function oe(e){if(!e)throw new r("process_inspection_failed","Reading this computer's processes is unavailable.");return e}async function Se(e,t){let n;try{n=await e(t)}catch{throw new r("process_inspection_failed","Reading this computer's ports did not complete.")}return Qe(n)}async function po(e,t=ye()){let n=oe(t),o=ne(e),s=[];for(let i of n.processes()){if(s.length>=Je)break;let a=xe(n,o,i.pid);if(a)s.push({pid:i.pid,command:i.command,cwd:V.relative(o,a)||"."})}return{processes:s}}async function ho(e,t=ye(),n=ke){let o=oe(t),s=ne(e),i=(await Se(n,5000)).filter((d)=>d.listening&&d.pid>0).map((d)=>({pid:d.pid,port:d.localPort,address:er(d)})).sort((d,b)=>d.pid-b.pid||d.port-b.port||(d.address<b.address?-1:d.address>b.address?1:0)),a=[...new Set(i.map((d)=>d.pid))].slice(0,Ve),u=new Set(a.filter((d)=>xe(o,s,d)!==null));if(u.size===0)return{ports:[]};let c=new Map(o.processes().map((d)=>[d.pid,d.command]));return{ports:i.filter((d)=>u.has(d.pid)).slice(0,Xe).map((d)=>({pid:d.pid,command:c.get(d.pid)??null,address:d.address}))}}function ve(e,t){let n=new Set([t]);for(let o=!0;o;){o=!1;for(let s of e)if(!n.has(s.pid)&&n.has(s.parentPid)&&s.pid!==s.parentPid)n.add(s.pid),o=!0}return n}function tr(e,t,n,o){let s=(i)=>i==="127.0.0.1"||i==="::ffff:127.0.0.1"||i==="::1";return e.flatMap((i)=>{if(!t.has(i.pid)||i.localPort!==o)return[];let a=i.listening&&(s(i.localAddress)||["0.0.0.0","::"].includes(i.localAddress)),u=!i.listening&&s(i.localAddress)&&s(i.remoteAddress);if(!a&&!u)return[];let c=`${i.localAddress}:${i.localPort}>${i.remoteAddress}:${i.remotePort}`;return[{pid:i.pid,processGroupId:n,descriptor:String(i.pid),kernelId:c,state:a?"listen":"established",port:o,peerPort:a?null:i.remotePort,host:i.localAddress==="::1"?"::1":"127.0.0.1"}]})}async function Ee(e,t,n=ye(),o=ke){let s=oe(n),i=ve(s.processes(),e),a=await Se(o,1000),u=ve(s.processes(),e);return tr(a,new Set([...i].filter((c)=>u.has(c))),e,t)}import{execFile as nr}from"child_process";import{readFile as or,readdir as sr,readlink as ir}from"fs/promises";import{connect as ar}from"net";import{setTimeout as dr}from"timers/promises";var cr={directory:sr,text:(e)=>or(e,"utf8"),link:ir};class se extends Error{code;constructor(e="port_unproved"){super("preview_port_ownership_unproved");this.code=e}}var x=(e)=>new se(e),X="preview_listener_unproved",Ae="00000000000000000000000001000000";async function lr(e,t,n=cr){let o=new Map;for(let a of["tcp","tcp6"]){let u=await n.text(`/proc/net/${a}`);if(u.length>4194304)throw x();for(let c of u.split(`
8
8
  `).slice(1)){let d=c.trim().split(/\s+/);if(d.length<10||!["0A","01"].includes(d[3]))continue;let[b,m]=d[1].split(":"),[l,g]=d[2].split(":");if(Number.parseInt(m,16)!==t)continue;let w=(k)=>k==="0100007F"||k==="0000000000000000FFFF00000100007F"||k===Ae,y=d[3]==="0A";if(!(w(b)||y&&/^0+$/.test(b??"")))continue;if(!y&&!w(l))continue;let _=d[9];if(!/^[1-9][0-9]*$/.test(_))continue;o.set(_,{kernelId:_,port:t,peerPort:y?null:Number.parseInt(g,16),state:y?"listen":"established",host:b===Ae?"::1":"127.0.0.1"})}}let s=await n.directory("/proc");if(s.length>8192)throw x();let i=[];for(let a of s){if(!/^[1-9][0-9]*$/.test(a))continue;try{let u=await n.text(`/proc/${a}/stat`),c=u.slice(u.lastIndexOf(")")+2).trim().split(/\s+/);if(Number(c[2])!==e)continue;let d=await n.directory(`/proc/${a}/fd`);if(d.length>1024)throw x();let b=[];for(let g of d){if(!/^[0-9]+$/.test(g))continue;let w=await n.link(`/proc/${a}/fd/${g}`).catch(()=>""),y=/^socket:\[([0-9]+)\]$/.exec(w)?.[1],_=y?o.get(y):void 0;if(_)b.push({..._,pid:Number(a),processGroupId:e,descriptor:g})}let m=await n.text(`/proc/${a}/stat`),l=m.slice(m.lastIndexOf(")")+2).trim().split(/\s+/);if(c[19]===l[19]&&c[2]===l[2])i.push(...b)}catch(u){if(u instanceof Error&&u.message==="preview_port_ownership_unproved")throw u}}return i}function ur(e,t,n){if(e.length>2097152)throw x();let o=0,s=0,i="",a="",u="",c="",d=[],b=()=>{if(o<1||s!==t||!/^\d+$/.test(i)||!/^0x[0-9a-f]+$/i.test(a))return;let m=c==="LISTEN"&&["*","127.0.0.1","[::ffff:127.0.0.1]","[::1]"].some((g)=>u===`${g}:${n}`),l=new RegExp(`^(?:127\\.0\\.0\\.1|\\[::ffff:127\\.0\\.0\\.1\\]|\\[::1\\]):${n}->(?:127\\.0\\.0\\.1|\\[::ffff:127\\.0\\.0\\.1\\]|\\[::1\\]):([0-9]+)$`).exec(u);if(m||c==="ESTABLISHED"&&l)d.push({pid:o,processGroupId:s,descriptor:i,kernelId:a,state:m?"listen":"established",port:n,peerPort:m?null:Number(l[1]),host:u.startsWith("[::1]:")?"::1":"127.0.0.1"})};for(let m of e.split(/[\0\n]/)){let l=m.slice(1);if(m[0]==="p")b(),o=Number(l),s=0,i=a=u=c="";else if(m[0]==="g")s=Number(l);else if(m[0]==="f")b(),i=l,a=u=c="";else if(m[0]==="d")a=l;else if(m[0]==="n")u=l;else if(m.startsWith("TST="))c=m.slice(4)}return b(),d}async function pr(e,t){if(process.platform==="linux")return lr(e,t);if(process.platform==="win32")return Ee(e,t);if(process.platform!=="darwin")throw x();let n=await new Promise((o,s)=>nr("/usr/sbin/lsof",["-nP","-a","-g",String(e),`-iTCP:${t}`,"-F0pgfdnT"],{timeout:1000,maxBuffer:2097152,encoding:"utf8",env:{PATH:"/usr/bin:/bin",LC_ALL:"C"}},(i,a)=>i?s(x()):o(a)));return ur(n,e,t)}function we(e,t={}){let n=C(e.binding),o=t.inspectSockets??pr,s=t.monotonicNow??(()=>performance.now());async function i(){let l=()=>{if(Date.now()>=n.expiresAtMs)throw x("binding_expired");if(e.deniedPorts.has(n.port))throw x("port_denied")};l();let g=await e.readCurrentJob(),w=g?.job,y=w?.process;if(l(),!g)throw x("server_stopped");if(!ze(n,g.binding)||w?.jobId!==n.jobId)throw x("binding_changed");if(w.state!=="running"||w.finishedAtMs!==null||w.leaseExpiresAtMs<n.expiresAtMs)throw x("job_not_running");if(!y||y.pid<1||y.pid!==y.processGroupId||y.executorLaunchId!==g.executorLaunchId)throw x("process_unproved");return{pid:y.pid,launch:y.executorLaunchId,started:w.startedAtMs}}let a,u;async function c(){let l=await i(),g=await o(l.pid,n.port).catch(()=>{throw Error(X)}),w=await i();if(l.pid!==w.pid||l.launch!==w.launch||l.started!==w.started)throw x("job_restarted");return g}async function d(l){for(;;){if(u&&u.startedAt>=l)return u.sockets;if(a&&a.startedAt>=l)return await a.sockets;if(a){await a.sockets.catch(()=>{});continue}let g={startedAt:s(),sockets:c()};a=g;try{let w=await g.sockets;if(!u||u.startedAt<=g.startedAt)u={startedAt:g.startedAt,sockets:w};return w}finally{if(a===g)a=void 0}}}async function b(l=()=>{},g=s()){l();let w=await d(g);if(l(),Date.now()>=n.expiresAtMs)throw x("binding_expired");if(!w.some((y)=>y.state==="listen"))throw Error(X);return w}async function m(){try{return await b(()=>{},s()-1000),null}catch(l){if(l instanceof Error&&l.message===X)return"listener_unproved";return l instanceof se?l.code:"port_unproved"}}return{refusal:m,async check(){let l=await m();if(l==="listener_unproved")throw Error(X);return l===null},async connect(l){if(l.aborted)throw x();let g=s()+2000,w=new AbortController,y=new Promise((P)=>w.signal.addEventListener("abort",()=>P(null),{once:!0})),_,k=()=>{w.abort(),_?.destroy()},O=setTimeout(k,2000);l.addEventListener("abort",k,{once:!0});let T=()=>{if(w.signal.aborted||l.aborted||s()>=g||_?.destroyed)throw k(),x()};async function v(P){T();let B=await Promise.race([P().then((S)=>({value:S})),y]);if(T(),!B)throw x();return B.value}try{let P=await v(()=>b(T,s()-1000));T();let B=P.some((f)=>f.state==="listen"&&f.host==="127.0.0.1")?"127.0.0.1":"::1",S=ar({host:B,port:n.port,signal:l});_=S,S.once("close",k),await v(()=>new Promise((f,h)=>{S.once("connect",f),S.once("error",h)}));let N=S.localPort;if(!N)throw x();let D=s();while(!(await v(()=>b(T,D))).some((f)=>f.state==="established"&&f.peerPort===N))await v(()=>dr(Math.min(20,Math.max(1,g-s())),void 0,{signal:w.signal})),D=s();return T(),S}catch(P){throw k(),P}finally{clearTimeout(O),l.removeEventListener("abort",k),_?.off("close",k),w.abort()}}}}
9
- export{p,ze,Mt,ut,lo,An,_e,ye,uo,po,we};
9
+ export{p,ze,Mt,ut,uo,An,_e,ye,po,ho,we};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{t,o,i,W,ee,s,n}from"./vm-hands-entry-lite-70x16hkx.js";var nt="inference.custom.v1",Et=32768,cr=67108864,on=16384,xt=4194304,h=204800,kt=2*xt+65536,Oi=600000,E=["content-type","anthropic-version","user-agent"],m=s(["openai-completions","openai-responses","anthropic-messages"]),f=new Set(E),C=ee(t(),t().max(2048)).refine((e)=>Object.keys(e).every((r)=>f.has(r))&&Object.values(e).every((r)=>!/[\r\n\0]/.test(r)),"Only non-secret custom endpoint request headers are permitted");function u(e){try{let r=new URL(e);return["http:","https:"].includes(r.protocol)&&!r.username&&!r.password&&!r.search&&!r.hash?r:null}catch{return null}}function sn(e,r){let a=u(e.baseUrl),d=u(r.baseUrl),c=u(e.url);if(!a||!d||!c||e.method!=="POST"||r.execution!=="device")return!1;let l=(p)=>p.origin+p.pathname.replace(/\/+$/,"");if(l(a)!==l(d)||c.origin!==a.origin)return!1;let _=r.api==="openai-completions"?"/chat/completions":r.api==="openai-responses"?"/responses":"/v1/messages";return c.pathname===a.pathname.replace(/\/+$/,"")+_}var Ii=i({baseUrl:t().max(2048),url:t().max(4096),method:n("POST"),body:t().refine((e)=>new TextEncoder().encode(e).byteLength<=xt).optional(),headers:C,credentialOrganizationId:t().uuid(),accountKey:t().min(1).max(256).optional()}).strict().refine((e)=>m.options.some((r)=>sn(e,{baseUrl:e.baseUrl,api:r,execution:"device"})),"Invalid custom endpoint inference URL"),D=i({status:o().int().min(200).max(599),statusText:t().max(256).refine((e)=>!/[\r\n\0]/.test(e)),headers:ee(t(),t().max(4096)).refine((e)=>Object.keys(e).every((r)=>["content-type","retry-after","x-request-id","request-id"].includes(r))&&Object.values(e).every((r)=>!/[\r\n\0]/.test(r)))}).strict(),y=W([i({eof:n(!0)}).strict(),i({eof:n(!1),data:t().max(Math.ceil(Et/3)*4).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/).refine((e)=>e.length>0&&e.length*3/4-(e.endsWith("==")?2:e.endsWith("=")?1:0)<=Et)}).strict()]),x=i({bytes:o().int().min(0).max(cr),chunks:o().int().min(0).max(on)}).strict(),Di=i({apiKey:t().min(1).max(16384).refine((e)=>!/[\r\n\0]/.test(e)),api:m}).strict(),S=["custom_endpoint_host_not_found","custom_endpoint_connection_failed","custom_endpoint_tls_failed","custom_endpoint_request_too_large","custom_endpoint_device_update_required"];function Ni(e){return typeof e==="string"&&S.includes(e)}var O="Ollama listens only on 127.0.0.1 unless it is started with OLLAMA_HOST=0.0.0.0.",T={custom_endpoint_host_not_found:"Your computer couldn't resolve your model server's hostname. Check the hostname in the Base URL, and that this computer is on the network or tailnet that resolves it.",custom_endpoint_connection_failed:`Your computer's connection to your model server was refused or timed out. Check that the server is running and listening on the Base URL's address and port. ${O}`,custom_endpoint_tls_failed:"Your computer couldn't make a secure (TLS) connection to your model server. Check the server's https certificate, or use an http:// Base URL for a server on your computer or private network.",custom_endpoint_request_too_large:`This conversation is too long for your computer to send to your model server: the request is over ${xt/1024/1024} MB, the most it relays. Start a new session to continue, or choose another model.`,custom_endpoint_device_update_required:`Reason on your computer is too old to send this conversation to your model server: it relays requests of at most ${h/1024} KB. Update Reason on that computer (reason update), then send your message again.`,401:"Your model server refused the request (HTTP 401). Check the API key saved for it in Models.",403:"Your model server refused the request (HTTP 403). Ollama refuses requests addressed to a hostname other than localhost, such as a *.ts.net name from tailscale serve or funnel: restart it with OLLAMA_HOST=0.0.0.0, or use http://localhost:11434/v1 when it runs on the session's computer. For another server, check the API key and its access rules.",404:"Your model server answered HTTP 404 (not found). Check that the Base URL is the API root (for Ollama, http://localhost:11434/v1) and that each model ID is one the server lists."};var I=new Set(Object.values(T));export{nt,Et,cr,on,xt,kt,Oi,sn,Ii,Di,Ni};
2
+ import{t,o,i,W,ee,s,n}from"./vm-hands-entry-lite-4cdn822w.js";var nt="inference.custom.v1",Et=32768,cr=67108864,on=16384,xt=4194304,h=204800,kt=2*xt+65536,Ii=600000,E=["content-type","anthropic-version","user-agent"],m=s(["openai-completions","openai-responses","anthropic-messages"]),f=new Set(E),C=ee(t(),t().max(2048)).refine((e)=>Object.keys(e).every((r)=>f.has(r))&&Object.values(e).every((r)=>!/[\r\n\0]/.test(r)),"Only non-secret custom endpoint request headers are permitted");function u(e){try{let r=new URL(e);return["http:","https:"].includes(r.protocol)&&!r.username&&!r.password&&!r.search&&!r.hash?r:null}catch{return null}}function sn(e,r){let a=u(e.baseUrl),d=u(r.baseUrl),c=u(e.url);if(!a||!d||!c||e.method!=="POST"||r.execution!=="device")return!1;let l=(p)=>p.origin+p.pathname.replace(/\/+$/,"");if(l(a)!==l(d)||c.origin!==a.origin)return!1;let _=r.api==="openai-completions"?"/chat/completions":r.api==="openai-responses"?"/responses":"/v1/messages";return c.pathname===a.pathname.replace(/\/+$/,"")+_}var Di=i({baseUrl:t().max(2048),url:t().max(4096),method:n("POST"),body:t().refine((e)=>new TextEncoder().encode(e).byteLength<=xt).optional(),headers:C,credentialOrganizationId:t().uuid(),accountKey:t().min(1).max(256).optional()}).strict().refine((e)=>m.options.some((r)=>sn(e,{baseUrl:e.baseUrl,api:r,execution:"device"})),"Invalid custom endpoint inference URL"),D=i({status:o().int().min(200).max(599),statusText:t().max(256).refine((e)=>!/[\r\n\0]/.test(e)),headers:ee(t(),t().max(4096)).refine((e)=>Object.keys(e).every((r)=>["content-type","retry-after","x-request-id","request-id"].includes(r))&&Object.values(e).every((r)=>!/[\r\n\0]/.test(r)))}).strict(),y=W([i({eof:n(!0)}).strict(),i({eof:n(!1),data:t().max(Math.ceil(Et/3)*4).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/).refine((e)=>e.length>0&&e.length*3/4-(e.endsWith("==")?2:e.endsWith("=")?1:0)<=Et)}).strict()]),x=i({bytes:o().int().min(0).max(cr),chunks:o().int().min(0).max(on)}).strict(),Ni=i({apiKey:t().min(1).max(16384).refine((e)=>!/[\r\n\0]/.test(e)),api:m}).strict(),S=["custom_endpoint_host_not_found","custom_endpoint_connection_failed","custom_endpoint_tls_failed","custom_endpoint_request_too_large","custom_endpoint_device_update_required"];function Li(e){return typeof e==="string"&&S.includes(e)}var O="Ollama listens only on 127.0.0.1 unless it is started with OLLAMA_HOST=0.0.0.0.",T={custom_endpoint_host_not_found:"Your computer couldn't resolve your model server's hostname. Check the hostname in the Base URL, and that this computer is on the network or tailnet that resolves it.",custom_endpoint_connection_failed:`Your computer's connection to your model server was refused or timed out. Check that the server is running and listening on the Base URL's address and port. ${O}`,custom_endpoint_tls_failed:"Your computer couldn't make a secure (TLS) connection to your model server. Check the server's https certificate, or use an http:// Base URL for a server on your computer or private network.",custom_endpoint_request_too_large:`This conversation is too long for your computer to send to your model server: the request is over ${xt/1024/1024} MB, the most it relays. Start a new session to continue, or choose another model.`,custom_endpoint_device_update_required:`Reason on your computer is too old to send this conversation to your model server: it relays requests of at most ${h/1024} KB. Update Reason on that computer (reason update), then send your message again.`,401:"Your model server refused the request (HTTP 401). Check the API key saved for it in Models.",403:"Your model server refused the request (HTTP 403). Ollama refuses requests addressed to a hostname other than localhost, such as a *.ts.net name from tailscale serve or funnel: restart it with OLLAMA_HOST=0.0.0.0, or use http://localhost:11434/v1 when it runs on the session's computer. For another server, check the API key and its access rules.",404:"Your model server answered HTTP 404 (not found). Check that the Base URL is the API root (for Ollama, http://localhost:11434/v1) and that each model ID is one the server lists."};var I=new Set(Object.values(T));export{nt,Et,cr,on,xt,kt,Ii,sn,Di,Ni,Li};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{H}from"./vm-hands-entry-lite-39qv4sqt.js";import{D,R,b}from"./vm-hands-entry-lite-q80xmhrx.js";import{je,gr,_r,Sn,En,ct}from"./vm-hands-entry-lite-n9rwh8vy.js";import{Mr}from"./vm-hands-entry-lite-gh0yjzye.js";import{p,ut,An,_e,we}from"./vm-hands-entry-lite-90y6pf98.js";import{v,h}from"./vm-hands-entry-lite-ymqb2927.js";import{a,nr,Uo}from"./vm-hands-entry-lite-0sh835na.js";import{an,y,t,k,o,d,ps,Oe,$i,u,i,W,g,ee,s,n,cn}from"./vm-hands-entry-lite-70x16hkx.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{se,A}from"./vm-hands-entry-lite-qz74j563.js";import{randomUUID as Q}from"crypto";import{spawn as Le}from"child_process";import{existsSync as Z,lstatSync as me,mkdirSync as We,readFileSync as Ne,realpathSync as G,rmSync as Ve,writeFileSync as He}from"fs";import{dirname as Ue,join as j,relative as qe,sep as Je}from"path";var Se=["process.run.v1","process.full.v1"],xe=600000,Pe=1800000,Ee=20000,ne="process.cancel.v1",ie=i({action:n("start"),request_id:t().uuid(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),cwd:t().min(1).max(4096).refine((e)=>!e.includes("\x00")&&!e.startsWith("/")&&!e.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:s(["host","confined"]).default("host"),timeout_ms:o().int().min(1000).max(Pe).default(xe).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),K={device_id:t().uuid(),root_id:t().uuid()},Re=g("action",[ie.extend(K),i({...K,action:n("inspect"),process_id:t().uuid(),after:o().int().min(0).default(0),wait_ms:o().int().min(0).max(Ee).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),i({...K,action:n("cancel"),process_id:t().uuid()}).strict()]),Fe=an(Re,{io:"input"}),Ke=ie.extend({process_brain_fence:t().uuid(),process_expires_at:y.datetime()}).strict(),J=i({version:n(1),process_id:t().uuid(),state:s(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:o().int().nullable(),first_cursor:o().int().min(0),next_cursor:o().int().min(0),truncated:d(),observed_at:y.datetime(),output:u(i({cursor:o().int().min(1),stream:s(["stdout","stderr"]),text:t().max(32768)}).strict()).max(128)}).strict().refine((e)=>{if(Buffer.byteLength(JSON.stringify(e))>1e5||e.next_cursor<e.first_cursor-1)return!1;if((e.state==="starting"||e.state==="running"||e.state==="uncertain")&&e.exit_code!==null)return!1;if(e.state==="exited"&&(e.exit_code===null||e.exit_code<0||e.exit_code>255))return!1;if(e.state==="cancelled"&&e.exit_code!==130||e.state==="expired"&&e.exit_code!==124)return!1;let _=e.first_cursor-1;for(let l of e.output){if(l.cursor<=_||l.cursor>e.next_cursor)return!1;_=l.cursor}return!0});function ae(e){return Se.includes(e)}var Xe=i({operation_constraints:ee(t(),Oe())}),Ye=i({ready:n(!0),version:n(1),execution_mode:s(["host","confined"]),max_timeout_ms:o().int().min(1000).optional()});var Ie=i({version:n(1),process_id:t().uuid(),state:s(["queued","cancelled_before_start","not_started"]),exit_code:ps(),output:u($i()).length(0),first_cursor:n(0),next_cursor:n(0),truncated:n(!1),cancellation_requested:n(!1),reason_code:s(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),De=i({...J.shape,state:s(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:y.datetime().optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:d(),reason_code:t().nullable().optional(),execution_authority:n("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:i({cause:n("brain_generation_changed"),terminal_confirmed:d(),next_step:s(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:J.shape.state.or(n("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),$e=an(De),Qe=W([J,Ie.refine((e)=>e.state==="cancelled_before_start")]),X=i({version:n(1),process_id:t().uuid(),state:s(["exited","cancelled","expired"]),exit_code:o().int().min(0).max(255),observed_at:y.datetime()}).strict().refine((e)=>(e.state!=="cancelled"||e.exit_code===130)&&(e.state!=="expired"||e.exit_code===124)),Ze=i({process_terminal_observation:X}).strict();var Ki="preview.serve.v1",Ji=43200000;var ce="preview.open.v1",de=1,_n="gid_proxy_v1",Zi="egress",yn=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,Ce=i({version:n(_n),allowed_domains:u(t().max(260).regex(yn)).max(1024)}).strict(),Ae=cn((e)=>H(e)!==null,"invalid workspace"),ke=i({version:n(1),request_id:k(),session_id:k(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),port:o().int().min(1024).max(65535),workspace:Ae,egress:Ce.optional()}).strict(),Xi=ke.extend({expires_at:y.datetime()}).strict();var Me=4,Te=5000;function Y(e,c,_){let l=null;try{l=ut(e)}catch{}An({deviceRelayUrl:l?.deviceRelayUrl??"",binding:l?.binding??null,jobId:c,port:l?.binding.port??0,reason:l?_:"binding_invalid"})}function le(e){let c=new Map;return{open(_){let l=(x)=>Y(_,e.claim.operation_id,x),C;try{C=ut(_)}catch{return l("binding_invalid")}let{binding:w,deviceRelayUrl:z}=C,E=e.claim.owner;if(!E||w.organizationId!==E.organization_id||w.userId!==E.user_id||w.deviceId!==E.device_id||w.rootId!==e.claim.root_id||w.jobId!==e.claim.operation_id||w.fenceId!==e.claim.operation_id||w.generation!==de||w.expiresAtMs>Math.min(Date.now()+p.lifetimeMs+Te,e.expiresAtMs))return l("binding_mismatch");if(w.expiresAtMs<=Date.now())return l("binding_expired");if(c.get(w.port)?.abort(),c.delete(w.port),c.size>=Me)return l("preview_capacity");let L=new AbortController;c.set(w.port,L);let P=we({binding:w,deniedPorts:e.deniedPorts,readCurrentJob:async()=>{if(L.signal.aborted)return null;let x=await e.inspect();return x?{binding:w,executorLaunchId:e.executorLaunchId,job:x}:null}});_e({binding:w,deviceRelayUrl:z,port:P,signal:L.signal}).then((x)=>x.closed,(x)=>{let I=x instanceof Error?x.message:"preview_failed";if(I!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:w.jobId,port:w.port,reason_code:I})}
3
- `)}).finally(()=>{if(c.get(w.port)===L)c.delete(w.port)})},dispose(){for(let _ of c.values())_.abort();c.clear()}}}class st extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var fe=256,B=new Map,he="preview.serve.v1",V=new Map;function be(e){let c=V.get(e.operation_id);if(c){if(c.claim!==e)throw M("process_authority_lost");return c}if(V.size>=fe)throw M("process_journal_capacity");let _={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return V.set(e.operation_id,_),_}function pe(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ue=(e)=>new Promise((c)=>setTimeout(c,e)),M=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function ze(e=a(),c=Ge()){let _=Ue(Mr({},e)),l=qe(nr(e),_),[C,...w]=l.split(Je);return{directory:j(c,l,"processes"),previous:[j(_,"processes"),...C==="reason"?[j(c,"ara",...w,"processes")]:[]]}}function Ge(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=Uo();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function fr(e){if(!e.claim.owner||e.signal.aborted||e.expiresAtMs<=Date.now())throw M("process_authority_lost");let c=be(e.claim);if(c.executing)throw M("process_busy");if(c.executing=!0,c.cancelRequested)return c.phase="settling",pe(e.claim.operation_id);c.phase="starting";let _=e.journals??ze();We(_.directory,{recursive:!0,mode:448});let l=gr({runtimeDirectory:G(_.directory),previousRuntimeDirectories:(_.previous??[]).filter((m)=>Z(m)).map((m)=>G(m)),root:e.root,runId:JSON.stringify([e.claim.owner,e.claim.run_id,e.claim.root_id,e.claim.operation_id]),maxScopes:fe});try{for(let m of[e.root,e.cwd])if(!je(G(m),l.journalDirectory))throw new r("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(m){throw l.disposeSocket(),m}let C=me(l.journalDirectory),w=e.claim.capability===he,z=()=>B.set(e.claim.operation_id,{path:l.journalDirectory,ino:C.ino,dev:C.dev,anyCompletion:w}),E=l.launchDirectory,L=j(E,"config.json"),P={url:"",transport:"local_job_ipc",directShell:{mode:e.mode,executable:e.shell,jobId:e.claim.operation_id},workerVersion:D,protocolVersion:2,workerArtifactSha256:b,workerEntrypoint:R,targetGeneration:1,fenceId:Q(),...process.platform==="win32"?{bashExecutable:se()}:{},workRoot:e.root,workspaceAliasPath:e.root,repoPath:e.cwd,jobEnvPath:j(E,"unused.env"),replSocketPath:j(E,"unused.sock"),readyPath:j(E,"ready.json"),directTerminalReceiptPath:j(E,"terminal.json"),launchId:Q(),expiresAtMs:e.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:l.journalDirectory,scopeId:l.scopeId},jobControlSocketPath:l.socketPath,...e.prefix?{bashCommandPrefix:e.prefix}:{},...e.jobsUser?{jobsUser:e.jobsUser}:{}},x;try{He(L,JSON.stringify(P),{mode:384});let m=Sn({configPath:L,root:e.cwd,grantedRoot:e.root,workRoot:e.root,temporaryDirectory:E});x=e.spawnWorker?.(L,P)??Le(m.command,m.args,{...m.options,env:e.environment,stdio:[En,"ignore","ignore"]})}catch(m){throw l.disposeSocket(),m}let I=!1,F=new Promise((m,S)=>{x.once("exit",(f)=>{I=!0,m(f)}),x.once("error",(f)=>{I=!0,S(f)})});F.catch(()=>{});let ge={root:e.root,runId:e.claim.run_id,scopeId:l.scopeId,socketPath:l.socketPath,generation:1,fenceId:P.fenceId,executorLaunchId:P.launchId,expiresAtMs:P.expiresAtMs},N=async(m)=>{let S=await _r(ge,{type:"job",version:2,generation:1,id:Q(),jobId:e.claim.operation_id,...m==="start"?{action:m,input:{script:e.command,leaseExpiresAtMs:e.expiresAtMs}}:m==="inspect"?{action:m,input:{after:0}}:m==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:m,input:{}}},new AbortController().signal);if(!S.ok)throw M(S.error);return S.job},U=!1,q=!1,te,re=()=>{U=!0,ct(x,"SIGTERM")};e.signal.addEventListener("abort",re,{once:!0});let T,oe=0,ve=async(m)=>{let S=[...m.output],f={version:1,process_id:e.claim.operation_id,state:m.state,exit_code:m.exitCode,first_cursor:m.firstCursor,next_cursor:m.nextCursor,truncated:m.truncated,output:S,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(f))>90000&&S.length)S.shift(),f.truncated=!0,f.first_cursor=S[0]?.cursor??f.next_cursor+1;T=J.parse(f),await e.emit(T),oe=Date.now()};try{let m=Math.min(Date.now()+1e4,e.expiresAtMs);while(!Z(P.readyPath)){if(I)throw new r("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if(e.signal.aborted||Date.now()>=m)throw M("process_start_unconfirmed");await ue(25)}let S=JSON.parse(Ne(P.readyPath,"utf8"));if(S.launchId!==P.launchId||S.fenceId!==P.fenceId||S.workerArtifactSha256!==b)throw M();if(e.signal.throwIfAborted(),c.cancelRequested)return pe(e.claim.operation_id);let f;try{q=!0,f=await N("start")}catch(O){if(!(O instanceof r)||O.code!=="hands_job_result_unknown")throw O;f=await N("inspect")}if(c.phase="running",c.cancel=async()=>{await N("cancel")},w&&e.preview)c.tunnels=le({claim:e.claim,executorLaunchId:P.launchId,expiresAtMs:e.expiresAtMs,deniedPorts:e.preview.deniedPorts,inspect:async()=>c.phase==="running"&&!I?await N("probe"):null});if(c.cancelRequested)await c.cancel(),f=await N("inspect");for(;;){if(!["starting","running"].includes(f.state))c.phase="settling",c.cancel=void 0;if(!T||T.state!==f.state||T.next_cursor!==f.nextCursor&&Date.now()-oe>=5000)await ve(f);if(!["starting","running"].includes(f.state))break;if(e.signal.aborted||I)throw M();await ue(1000);try{f=await N("inspect"),te=void 0}catch(O){if(!(O instanceof r)||O.code!=="hands_job_result_unknown"||e.signal.aborted||I||Date.now()-(te??=Date.now())>120000)throw O}}if(!T||T.state==="uncertain")throw M();return T}finally{if(c.phase="settling",c.cancel=void 0,c.tunnels?.dispose(),c.tunnels=void 0,await c.cancelInFlight?.catch(()=>{}),e.signal.removeEventListener("abort",re),!I&&!U)ct(x,"SIGTERM");let m,S=await Promise.race([F.then((f)=>({code:f})),new Promise((f)=>{m=setTimeout(()=>f(null),6000)})]).finally(()=>{clearTimeout(m)});if(!S){try{ct(x,"SIGKILL")}catch{}try{await F}finally{if(I)l.disposeSocket()}throw M("process_cleanup_unconfirmed")}try{if((U||e.signal.aborted)&&S.code===0&&q){v(E);let f=JSON.parse(h(P.directTerminalReceiptPath)),O=X.safeParse(f.observation);if(Object.keys(f).length===4&&f.launch_id===P.launchId&&f.fence_id===P.fenceId&&f.scope_id===l.scopeId&&O.success&&O.data.process_id===e.claim.operation_id){if(w)z();throw new st(O.data)}}}catch(f){if(f instanceof st)throw f}finally{if(I)l.disposeSocket()}if(S.code!==0&&!U&&q)throw M("process_cleanup_unconfirmed");if(!U&&S.code===0&&(T&&["exited","cancelled","expired"].includes(T.state)||!q&&c.cancelRequested)||w&&S.code===0&&!q)z()}}async function $s(e,c){if(c.kind===ce&&e.capability===he){let C=V.get(e.operation_id);if(C?.claim===e&&C.tunnels)C.tunnels.open(c.payload);else Y(c.payload,e.operation_id,"server_not_running");return!0}if(c.kind!==ne||!ae(e.capability)||!e.owner||c.payload.process_id!==e.operation_id)return!1;let _=V.get(e.operation_id);if(_&&_.claim!==e)return!1;let l=be(e);if(l.cancelRequested=!0,l.phase==="running"&&l.cancel)l.cancelInFlight??=l.cancel(),await l.cancelInFlight;return!0}function Bs(e,c){V.delete(e);let _=B.get(e);if(!_||c!=="succeeded"&&!_.anyCompletion)return B.delete(e),!1;try{let l=me(_.path);if(!l.isDirectory()||l.isSymbolicLink()||l.ino!==_.ino||l.dev!==_.dev||!A(l)||G(_.path)!==_.path||Z(j(_.path,"owner.lock")))return!1;return Ve(_.path,{recursive:!0}),B.delete(e),!0}catch{return!1}}
4
- export{Ki,Ji,_n,Zi,yn,Xi,st,fr,$s,Bs};
2
+ import{H}from"./vm-hands-entry-lite-39qv4sqt.js";import{D,T,b}from"./vm-hands-entry-lite-tash5m18.js";import{je,gr,_r,Sn,En,ct}from"./vm-hands-entry-lite-fzq1je66.js";import{Mr}from"./vm-hands-entry-lite-hc11hecd.js";import{p,ut,An,_e,we}from"./vm-hands-entry-lite-kwmjn9y3.js";import{v,h}from"./vm-hands-entry-lite-c4959xva.js";import{a,nr,qo}from"./vm-hands-entry-lite-haws181e.js";import{an,y,t,k,o,d,ms,Oe,Bi,u,i,W,g,ee,s,n,cn}from"./vm-hands-entry-lite-4cdn822w.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{se,A}from"./vm-hands-entry-lite-1kt82jes.js";import{randomUUID as Q}from"crypto";import{spawn as Le}from"child_process";import{existsSync as Z,lstatSync as me,mkdirSync as We,readFileSync as Ne,realpathSync as G,rmSync as Ve,writeFileSync as He}from"fs";import{dirname as Ue,join as j,relative as qe,sep as Je}from"path";var Se=["process.run.v1","process.full.v1"],xe=600000,Pe=1800000,Ee=20000,ne="process.cancel.v1",ie=i({action:n("start"),request_id:t().uuid(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),cwd:t().min(1).max(4096).refine((e)=>!e.includes("\x00")&&!e.startsWith("/")&&!e.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:s(["host","confined"]).default("host"),timeout_ms:o().int().min(1000).max(Pe).default(xe).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),K={device_id:t().uuid(),root_id:t().uuid()},Re=g("action",[ie.extend(K),i({...K,action:n("inspect"),process_id:t().uuid(),after:o().int().min(0).default(0),wait_ms:o().int().min(0).max(Ee).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),i({...K,action:n("cancel"),process_id:t().uuid()}).strict()]),Fe=an(Re,{io:"input"}),Ke=ie.extend({process_brain_fence:t().uuid(),process_expires_at:y.datetime()}).strict(),J=i({version:n(1),process_id:t().uuid(),state:s(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:o().int().nullable(),first_cursor:o().int().min(0),next_cursor:o().int().min(0),truncated:d(),observed_at:y.datetime(),output:u(i({cursor:o().int().min(1),stream:s(["stdout","stderr"]),text:t().max(32768)}).strict()).max(128)}).strict().refine((e)=>{if(Buffer.byteLength(JSON.stringify(e))>1e5||e.next_cursor<e.first_cursor-1)return!1;if((e.state==="starting"||e.state==="running"||e.state==="uncertain")&&e.exit_code!==null)return!1;if(e.state==="exited"&&(e.exit_code===null||e.exit_code<0||e.exit_code>255))return!1;if(e.state==="cancelled"&&e.exit_code!==130||e.state==="expired"&&e.exit_code!==124)return!1;let _=e.first_cursor-1;for(let l of e.output){if(l.cursor<=_||l.cursor>e.next_cursor)return!1;_=l.cursor}return!0});function ae(e){return Se.includes(e)}var Xe=i({operation_constraints:ee(t(),Oe())}),Ye=i({ready:n(!0),version:n(1),execution_mode:s(["host","confined"]),max_timeout_ms:o().int().min(1000).optional()});var Ie=i({version:n(1),process_id:t().uuid(),state:s(["queued","cancelled_before_start","not_started"]),exit_code:ms(),output:u(Bi()).length(0),first_cursor:n(0),next_cursor:n(0),truncated:n(!1),cancellation_requested:n(!1),reason_code:s(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),De=i({...J.shape,state:s(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:y.datetime().optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:d(),reason_code:t().nullable().optional(),execution_authority:n("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:i({cause:n("brain_generation_changed"),terminal_confirmed:d(),next_step:s(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:J.shape.state.or(n("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),$e=an(De),Qe=W([J,Ie.refine((e)=>e.state==="cancelled_before_start")]),X=i({version:n(1),process_id:t().uuid(),state:s(["exited","cancelled","expired"]),exit_code:o().int().min(0).max(255),observed_at:y.datetime()}).strict().refine((e)=>(e.state!=="cancelled"||e.exit_code===130)&&(e.state!=="expired"||e.exit_code===124)),Ze=i({process_terminal_observation:X}).strict();var Ji="preview.serve.v1",Zi=43200000;var ce="preview.open.v1",de=1,_n="gid_proxy_v1",Xi="egress",yn=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,Ce=i({version:n(_n),allowed_domains:u(t().max(260).regex(yn)).max(1024)}).strict(),Ae=cn((e)=>H(e)!==null,"invalid workspace"),ke=i({version:n(1),request_id:k(),session_id:k(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),port:o().int().min(1024).max(65535),workspace:Ae,egress:Ce.optional()}).strict(),Yi=ke.extend({expires_at:y.datetime()}).strict();var Me=4,Te=5000;function Y(e,c,_){let l=null;try{l=ut(e)}catch{}An({deviceRelayUrl:l?.deviceRelayUrl??"",binding:l?.binding??null,jobId:c,port:l?.binding.port??0,reason:l?_:"binding_invalid"})}function le(e){let c=new Map;return{open(_){let l=(x)=>Y(_,e.claim.operation_id,x),I;try{I=ut(_)}catch{return l("binding_invalid")}let{binding:w,deviceRelayUrl:z}=I,E=e.claim.owner;if(!E||w.organizationId!==E.organization_id||w.userId!==E.user_id||w.deviceId!==E.device_id||w.rootId!==e.claim.root_id||w.jobId!==e.claim.operation_id||w.fenceId!==e.claim.operation_id||w.generation!==de||w.expiresAtMs>Math.min(Date.now()+p.lifetimeMs+Te,e.expiresAtMs))return l("binding_mismatch");if(w.expiresAtMs<=Date.now())return l("binding_expired");if(c.get(w.port)?.abort(),c.delete(w.port),c.size>=Me)return l("preview_capacity");let L=new AbortController;c.set(w.port,L);let P=we({binding:w,deniedPorts:e.deniedPorts,readCurrentJob:async()=>{if(L.signal.aborted)return null;let x=await e.inspect();return x?{binding:w,executorLaunchId:e.executorLaunchId,job:x}:null}});_e({binding:w,deviceRelayUrl:z,port:P,signal:L.signal}).then((x)=>x.closed,(x)=>{let R=x instanceof Error?x.message:"preview_failed";if(R!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:w.jobId,port:w.port,reason_code:R})}
3
+ `)}).finally(()=>{if(c.get(w.port)===L)c.delete(w.port)})},dispose(){for(let _ of c.values())_.abort();c.clear()}}}class st extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var fe=256,B=new Map,he="preview.serve.v1",V=new Map;function be(e){let c=V.get(e.operation_id);if(c){if(c.claim!==e)throw O("process_authority_lost");return c}if(V.size>=fe)throw O("process_journal_capacity");let _={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return V.set(e.operation_id,_),_}function pe(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ue=(e)=>new Promise((c)=>setTimeout(c,e)),O=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function ze(e=a(),c=Ge()){let _=Ue(Mr({},e)),l=qe(nr(e),_),[I,...w]=l.split(Je);return{directory:j(c,l,"processes"),previous:[j(_,"processes"),...I==="reason"?[j(c,"ara",...w,"processes")]:[]]}}function Ge(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=qo();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function fr(e){if(!e.claim.owner||e.signal.aborted||e.expiresAtMs<=Date.now())throw O("process_authority_lost");let c=be(e.claim);if(c.executing)throw O("process_busy");if(c.executing=!0,c.cancelRequested)return c.phase="settling",pe(e.claim.operation_id);c.phase="starting";let _=e.journals??ze();We(_.directory,{recursive:!0,mode:448});let l=gr({runtimeDirectory:G(_.directory),previousRuntimeDirectories:(_.previous??[]).filter((m)=>Z(m)).map((m)=>G(m)),root:e.root,runId:JSON.stringify([e.claim.owner,e.claim.run_id,e.claim.root_id,e.claim.operation_id]),maxScopes:fe});try{for(let m of[e.root,e.cwd])if(!je(G(m),l.journalDirectory))throw new r("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(m){throw l.disposeSocket(),m}let I=me(l.journalDirectory),w=e.claim.capability===he,z=()=>B.set(e.claim.operation_id,{path:l.journalDirectory,ino:I.ino,dev:I.dev,anyCompletion:w}),E=l.launchDirectory,L=j(E,"config.json"),P={url:"",transport:"local_job_ipc",directShell:{mode:e.mode,executable:e.shell,jobId:e.claim.operation_id},workerVersion:D,protocolVersion:2,workerArtifactSha256:b,workerEntrypoint:T,targetGeneration:1,fenceId:Q(),...process.platform==="win32"?{bashExecutable:se()}:{},workRoot:e.root,workspaceAliasPath:e.root,repoPath:e.cwd,jobEnvPath:j(E,"unused.env"),replSocketPath:j(E,"unused.sock"),readyPath:j(E,"ready.json"),directTerminalReceiptPath:j(E,"terminal.json"),launchId:Q(),expiresAtMs:e.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:l.journalDirectory,scopeId:l.scopeId},jobControlSocketPath:l.socketPath,...e.prefix?{bashCommandPrefix:e.prefix}:{},...e.jobsUser?{jobsUser:e.jobsUser}:{}},x;try{He(L,JSON.stringify(P),{mode:384});let m=Sn({configPath:L,root:e.cwd,grantedRoot:e.root,workRoot:e.root,temporaryDirectory:E});x=e.spawnWorker?.(L,P)??Le(m.command,m.args,{...m.options,env:e.environment,stdio:[En,"ignore","ignore"]})}catch(m){throw l.disposeSocket(),m}let R=!1,F=new Promise((m,S)=>{x.once("exit",(f)=>{R=!0,m(f)}),x.once("error",(f)=>{R=!0,S(f)})});F.catch(()=>{});let ge={root:e.root,runId:e.claim.run_id,scopeId:l.scopeId,socketPath:l.socketPath,generation:1,fenceId:P.fenceId,executorLaunchId:P.launchId,expiresAtMs:P.expiresAtMs},N=async(m)=>{let S=await _r(ge,{type:"job",version:2,generation:1,id:Q(),jobId:e.claim.operation_id,...m==="start"?{action:m,input:{script:e.command,leaseExpiresAtMs:e.expiresAtMs}}:m==="inspect"?{action:m,input:{after:0}}:m==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:m,input:{}}},new AbortController().signal);if(!S.ok)throw O(S.error);return S.job},U=!1,q=!1,te,re=()=>{U=!0,ct(x,"SIGTERM")};e.signal.addEventListener("abort",re,{once:!0});let M,oe=0,ve=async(m)=>{let S=[...m.output],f={version:1,process_id:e.claim.operation_id,state:m.state,exit_code:m.exitCode,first_cursor:m.firstCursor,next_cursor:m.nextCursor,truncated:m.truncated,output:S,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(f))>90000&&S.length)S.shift(),f.truncated=!0,f.first_cursor=S[0]?.cursor??f.next_cursor+1;M=J.parse(f),await e.emit(M),oe=Date.now()};try{let m=Math.min(Date.now()+1e4,e.expiresAtMs);while(!Z(P.readyPath)){if(R)throw new r("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if(e.signal.aborted||Date.now()>=m)throw O("process_start_unconfirmed");await ue(25)}let S=JSON.parse(Ne(P.readyPath,"utf8"));if(S.launchId!==P.launchId||S.fenceId!==P.fenceId||S.workerArtifactSha256!==b)throw O();if(e.signal.throwIfAborted(),c.cancelRequested)return pe(e.claim.operation_id);let f;try{q=!0,f=await N("start")}catch(C){if(!(C instanceof r)||C.code!=="hands_job_result_unknown")throw C;f=await N("inspect")}if(c.phase="running",c.cancel=async()=>{await N("cancel")},w&&e.preview)c.tunnels=le({claim:e.claim,executorLaunchId:P.launchId,expiresAtMs:e.expiresAtMs,deniedPorts:e.preview.deniedPorts,inspect:async()=>c.phase==="running"&&!R?await N("probe"):null});if(c.cancelRequested)await c.cancel(),f=await N("inspect");for(;;){if(!["starting","running"].includes(f.state))c.phase="settling",c.cancel=void 0;if(!M||M.state!==f.state||M.next_cursor!==f.nextCursor&&Date.now()-oe>=5000)await ve(f);if(!["starting","running"].includes(f.state))break;if(e.signal.aborted||R)throw O();await ue(1000);try{f=await N("inspect"),te=void 0}catch(C){if(!(C instanceof r)||C.code!=="hands_job_result_unknown"||e.signal.aborted||R||Date.now()-(te??=Date.now())>120000)throw C}}if(!M||M.state==="uncertain")throw O();return M}finally{if(c.phase="settling",c.cancel=void 0,c.tunnels?.dispose(),c.tunnels=void 0,await c.cancelInFlight?.catch(()=>{}),e.signal.removeEventListener("abort",re),!R&&!U)ct(x,"SIGTERM");let m,S=await Promise.race([F.then((f)=>({code:f})),new Promise((f)=>{m=setTimeout(()=>f(null),6000)})]).finally(()=>{clearTimeout(m)});if(!S){try{ct(x,"SIGKILL")}catch{}try{await F}finally{if(R)l.disposeSocket()}throw O("process_cleanup_unconfirmed")}try{if((U||e.signal.aborted)&&S.code===0&&q){v(E);let f=JSON.parse(h(P.directTerminalReceiptPath)),C=X.safeParse(f.observation);if(Object.keys(f).length===4&&f.launch_id===P.launchId&&f.fence_id===P.fenceId&&f.scope_id===l.scopeId&&C.success&&C.data.process_id===e.claim.operation_id){if(w)z();throw new st(C.data)}}}catch(f){if(f instanceof st)throw f}finally{if(R)l.disposeSocket()}if(S.code!==0&&!U&&q)throw O("process_cleanup_unconfirmed");if(!U&&S.code===0&&(M&&["exited","cancelled","expired"].includes(M.state)||!q&&c.cancelRequested)||w&&S.code===0&&!q)z()}}async function js(e,c){if(c.kind===ce&&e.capability===he){let I=V.get(e.operation_id);if(I?.claim===e&&I.tunnels)I.tunnels.open(c.payload);else Y(c.payload,e.operation_id,"server_not_running");return!0}if(c.kind!==ne||!ae(e.capability)||!e.owner||c.payload.process_id!==e.operation_id)return!1;let _=V.get(e.operation_id);if(_&&_.claim!==e)return!1;let l=be(e);if(l.cancelRequested=!0,l.phase==="running"&&l.cancel)l.cancelInFlight??=l.cancel(),await l.cancelInFlight;return!0}function Us(e,c){V.delete(e);let _=B.get(e);if(!_||c!=="succeeded"&&!_.anyCompletion)return B.delete(e),!1;try{let l=me(_.path);if(!l.isDirectory()||l.isSymbolicLink()||l.ino!==_.ino||l.dev!==_.dev||!A(l)||G(_.path)!==_.path||Z(j(_.path,"owner.lock")))return!1;return Ve(_.path,{recursive:!0}),B.delete(e),!0}catch{return!1}}
4
+ export{Ji,Zi,_n,Xi,yn,Yi,st,fr,js,Us};