@reason-machines/cli-linux-x64 0.2.494 → 0.2.496

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 (101) hide show
  1. package/bin/reason +1 -1
  2. package/bin/vm-hands/api-c5b67kgx.js +2 -0
  3. package/bin/vm-hands/api-credentials-t0eyqvyb.js +2 -0
  4. package/bin/vm-hands/connect-cli-v2desvzn.js +2 -0
  5. package/bin/vm-hands/credentials-drj5ktpt.js +2 -0
  6. package/bin/vm-hands/custom-endpoint-device-389h3q6n.js +2 -0
  7. package/bin/vm-hands/desktop-account-tjf36aya.js +2 -0
  8. package/bin/vm-hands/{fsevents-wa96aeq8.js → fsevents-s0cwdhcq.js} +1 -1
  9. package/bin/vm-hands/hands-worker-source-wrj180b5.js +2 -0
  10. package/bin/vm-hands/{index-tpxh1rhj.js → index-w9sxzata.js} +7 -7
  11. package/bin/vm-hands/install-receipt-9bv4vth9.js +2 -0
  12. package/bin/vm-hands/local-automation-r8799erc.js +2 -0
  13. package/bin/vm-hands/local-capabilities-3e80wdfw.js +2 -0
  14. package/bin/vm-hands/local-desktop-users-tqagws7p.js +2 -0
  15. package/bin/vm-hands/local-display-mac-w792g9g3.js +2 -0
  16. package/bin/vm-hands/local-display-session-k3nbmz44.js +2 -0
  17. package/bin/vm-hands/local-display-video-wymf2q2t.js +2 -0
  18. package/bin/vm-hands/local-managed-process-knn335hh.js +2 -0
  19. package/bin/vm-hands/local-pty-session-rdv5wv5g.js +2 -0
  20. package/bin/vm-hands/managed-runtime-ajjy7qxf.js +2 -0
  21. package/bin/vm-hands/network-contract-h6s7ptm5.js +2 -0
  22. package/bin/vm-hands/package-yy8qcwwn.js +2 -0
  23. package/bin/vm-hands/permissions-x0d6x75e.js +2 -0
  24. package/bin/vm-hands/{reason-hands-protocol-7ck7a2ba.js → reason-hands-protocol-vw2dbdse.js} +1 -1
  25. package/bin/vm-hands/serve-service-gs1056pz.js +2 -0
  26. package/bin/vm-hands/{status-zmw3r5r6.js → status-x99x0y2e.js} +1 -1
  27. package/bin/vm-hands/version-qztzqxab.js +2 -0
  28. package/bin/vm-hands/{vm-hands-entry-lite-gfrp4eht.js → vm-hands-entry-lite-13rapgf5.js} +2 -2
  29. package/bin/vm-hands/{vm-hands-entry-lite-ytxa5cq0.js → vm-hands-entry-lite-1g1v87ky.js} +3 -3
  30. package/bin/vm-hands/{vm-hands-entry-lite-bveg8vsa.js → vm-hands-entry-lite-2dx4pnz7.js} +2 -2
  31. package/bin/vm-hands/{vm-hands-entry-lite-35rmpfdk.js → vm-hands-entry-lite-2jadtgms.js} +1 -1
  32. package/bin/vm-hands/{vm-hands-entry-lite-myb9bjy9.js → vm-hands-entry-lite-2zq8s2sr.js} +4 -4
  33. package/bin/vm-hands/{vm-hands-entry-lite-nnzqx15h.js → vm-hands-entry-lite-3gztfxwt.js} +13 -13
  34. package/bin/vm-hands/{vm-hands-entry-lite-smx6w8h0.js → vm-hands-entry-lite-4egbv7sp.js} +6 -6
  35. package/bin/vm-hands/{vm-hands-entry-lite-hy242z2t.js → vm-hands-entry-lite-64z2tjpg.js} +1 -1
  36. package/bin/vm-hands/{vm-hands-entry-lite-hza7bvk8.js → vm-hands-entry-lite-6kq28jjd.js} +1 -1
  37. package/bin/vm-hands/{vm-hands-entry-lite-gn2rg810.js → vm-hands-entry-lite-6x1an7es.js} +3 -3
  38. package/bin/vm-hands/{vm-hands-entry-lite-xkba45hh.js → vm-hands-entry-lite-7777m86y.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-4e32vgs8.js → vm-hands-entry-lite-7yyx4qf9.js} +20 -20
  40. package/bin/vm-hands/{vm-hands-entry-lite-tbawqj1n.js → vm-hands-entry-lite-87vmbt38.js} +2 -2
  41. package/bin/vm-hands/{vm-hands-entry-lite-vtbw3evj.js → vm-hands-entry-lite-8qhz89mt.js} +3 -3
  42. package/bin/vm-hands/{vm-hands-entry-lite-vezfnqf1.js → vm-hands-entry-lite-9wa2y4x0.js} +5 -5
  43. package/bin/vm-hands/{vm-hands-entry-lite-g27kmejx.js → vm-hands-entry-lite-a1xa7s06.js} +3 -3
  44. package/bin/vm-hands/vm-hands-entry-lite-b7zgdjf9.js +2 -0
  45. package/bin/vm-hands/{vm-hands-entry-lite-ya9p67x3.js → vm-hands-entry-lite-dw558ggz.js} +1 -1
  46. package/bin/vm-hands/{vm-hands-entry-lite-pk8fxewf.js → vm-hands-entry-lite-e4c6z5t3.js} +1 -1
  47. package/bin/vm-hands/{vm-hands-entry-lite-633mzx27.js → vm-hands-entry-lite-f62fvme8.js} +1 -1
  48. package/bin/vm-hands/{vm-hands-entry-lite-0tzzctxx.js → vm-hands-entry-lite-f69t48dj.js} +2 -2
  49. package/bin/vm-hands/{vm-hands-entry-lite-9r4d4mx1.js → vm-hands-entry-lite-gc7550c0.js} +1 -1
  50. package/bin/vm-hands/{vm-hands-entry-lite-55xh3ezr.js → vm-hands-entry-lite-h1gpv5px.js} +2 -2
  51. package/bin/vm-hands/{vm-hands-entry-lite-ss5n593s.js → vm-hands-entry-lite-ht7fk059.js} +5 -5
  52. package/bin/vm-hands/{vm-hands-entry-lite-v3ga0xcz.js → vm-hands-entry-lite-jc8dwrgp.js} +6 -6
  53. package/bin/vm-hands/vm-hands-entry-lite-jr2jmk4v.js +52 -0
  54. package/bin/vm-hands/{vm-hands-entry-lite-kgf255a9.js → vm-hands-entry-lite-jsbjsdgn.js} +3 -3
  55. package/bin/vm-hands/vm-hands-entry-lite-krm8w7wp.js +3 -0
  56. package/bin/vm-hands/{vm-hands-entry-lite-sk9jyg5p.js → vm-hands-entry-lite-n4xgpgkw.js} +2 -2
  57. package/bin/vm-hands/{vm-hands-entry-lite-hxhd7btg.js → vm-hands-entry-lite-nqdstx24.js} +2 -2
  58. package/bin/vm-hands/{vm-hands-entry-lite-0ybetwry.js → vm-hands-entry-lite-nwwa0k2s.js} +1 -1
  59. package/bin/vm-hands/{vm-hands-entry-lite-27z324rk.js → vm-hands-entry-lite-p629s0jp.js} +3 -3
  60. package/bin/vm-hands/{vm-hands-entry-lite-ytdg3zx5.js → vm-hands-entry-lite-pfjesssg.js} +2 -2
  61. package/bin/vm-hands/{vm-hands-entry-lite-dxkxgqyy.js → vm-hands-entry-lite-pr1t5d93.js} +2 -2
  62. package/bin/vm-hands/{vm-hands-entry-lite-1qjw1rt2.js → vm-hands-entry-lite-psywfz8m.js} +4 -4
  63. package/bin/vm-hands/{vm-hands-entry-lite-hff5yfen.js → vm-hands-entry-lite-sqqw5ftm.js} +19 -19
  64. package/bin/vm-hands/{vm-hands-entry-lite-y7z8pfgt.js → vm-hands-entry-lite-swrymqj9.js} +2 -2
  65. package/bin/vm-hands/{vm-hands-entry-lite-p7m36kw7.js → vm-hands-entry-lite-tebh7dcm.js} +3 -3
  66. package/bin/vm-hands/{vm-hands-entry-lite-whdnstpa.js → vm-hands-entry-lite-w0pegc58.js} +4 -4
  67. package/bin/vm-hands/{vm-hands-entry-lite-6nhbph7w.js → vm-hands-entry-lite-w14a2f89.js} +3 -3
  68. package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
  69. package/bin/vm-hands/{vm-hands-executor-f9mnj5vh.js → vm-hands-executor-f986qmnd.js} +2 -2
  70. package/bin/vm-hands/{vm-hands-op-runner-fxb4977p.js → vm-hands-op-runner-bss4cb7g.js} +1 -1
  71. package/bin/vm-hands/{vm-hands-runtime-471q11j3.js → vm-hands-runtime-qzw9ndeb.js} +3 -3
  72. package/bin/vm-hands/worker-preview-readiness-m2dn9mmn.js +2 -0
  73. package/bin/vm-hands/worker-sandbox-k4cfh0ya.js +2 -0
  74. package/package.json +1 -1
  75. package/bin/vm-hands/api-9ett3970.js +0 -2
  76. package/bin/vm-hands/api-credentials-pcn0yerk.js +0 -2
  77. package/bin/vm-hands/connect-cli-naectjzw.js +0 -2
  78. package/bin/vm-hands/credentials-snvdd3wy.js +0 -2
  79. package/bin/vm-hands/custom-endpoint-device-v82y34dy.js +0 -2
  80. package/bin/vm-hands/desktop-account-c35292yy.js +0 -2
  81. package/bin/vm-hands/hands-worker-source-pd1m7s16.js +0 -2
  82. package/bin/vm-hands/install-receipt-n79tzg6r.js +0 -2
  83. package/bin/vm-hands/local-automation-826fbrc0.js +0 -2
  84. package/bin/vm-hands/local-capabilities-xkq59r1s.js +0 -2
  85. package/bin/vm-hands/local-desktop-users-mhhw7e7q.js +0 -2
  86. package/bin/vm-hands/local-display-mac-73yk1493.js +0 -2
  87. package/bin/vm-hands/local-display-session-csergvtt.js +0 -2
  88. package/bin/vm-hands/local-display-video-amgnx87w.js +0 -2
  89. package/bin/vm-hands/local-managed-process-djnpyxga.js +0 -2
  90. package/bin/vm-hands/local-pty-session-h88gf14w.js +0 -2
  91. package/bin/vm-hands/managed-runtime-3edzgtm8.js +0 -2
  92. package/bin/vm-hands/network-contract-gg5ztcdt.js +0 -2
  93. package/bin/vm-hands/package-0nbmep23.js +0 -2
  94. package/bin/vm-hands/permissions-e81yz7xe.js +0 -2
  95. package/bin/vm-hands/serve-service-k0vta12g.js +0 -2
  96. package/bin/vm-hands/version-s2brry6v.js +0 -2
  97. package/bin/vm-hands/vm-hands-entry-lite-1ymtsqqk.js +0 -52
  98. package/bin/vm-hands/vm-hands-entry-lite-5g508mhr.js +0 -2
  99. package/bin/vm-hands/vm-hands-entry-lite-ytazq3rk.js +0 -3
  100. package/bin/vm-hands/worker-preview-readiness-y992mb4a.js +0 -2
  101. package/bin/vm-hands/worker-sandbox-y62j1dkh.js +0 -2
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{gt,_,_t}from"./vm-hands-entry-lite-hxhd7btg.js";import{chmodSync as Q,existsSync as C,mkdirSync as Z,readlinkSync as S,readFileSync as b,renameSync as nn,unlinkSync as tn,writeFileSync as en}from"fs";import{homedir as u}from"os";import{basename as h,dirname as p,isAbsolute as f,join as o,normalize as A,relative as O,resolve as N}from"path";var c=3,P=1,D=2,x=1,T=1,L="Reason may read and write files and run commands in this signed-in OS account, subject to saved restrictions and operating system permissions.",M="Reason may later execute on this computer inside a Reason sandbox, limited to folders explicitly attached by the user.",F=[M,"Ara may later execute on this computer inside an Ara sandbox, limited to folders explicitly attached by the user."];function B(n){return typeof n==="string"&&F.includes(n)}var U=["future_device","updates_only","cli_only"];function y(n){return typeof n==="string"&&U.some((t)=>t===n)}function V(n=process.env,t=u()){return n.XDG_CONFIG_HOME?.trim()||o(t,".config")}function Kr(n=process.env,t=u()){let r=_({env:n}),e=V(n,t);return o(e,_t(e).state==="kept"?"ara":"reason",...r==="staging"?["staging"]:[],"installation.json")}function a(n){return typeof n==="string"&&n.trim().length>0}var K=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function z(n){return typeof n==="string"&&K.test(n)}function l(n){return a(n)&&f(n)&&A(n)===n}function g(n){if(!n||typeof n!=="object"||Array.isArray(n))return!1;let t=n;return l(t.path)&&(t.role==="launcher"&&(t.kind==="file"||t.kind==="symlink")||t.role==="worker_root"&&t.kind==="directory"||t.role==="alias"&&t.kind==="symlink"&&l(t.target))}function m(n){return n==="staging"?["reason-staging","ara-staging"]:["reason","ara"]}function Qn(n){let t=n.owned_paths.filter((e)=>e.role==="launcher").map((e)=>e.path),[r]=m(n.channel);return t.find((e)=>h(e)===r)??t[0]??null}function I(n){let[t,r]=m(n.channel==="staging"?"staging":"production"),e=[[t,r],[r,t]];return n.owned_paths?.every((i)=>i.role!=="alias"||n.installer==="shell"&&e.some(([s,R])=>i.path===o(n.install_dir,s)&&i.target===o(n.install_dir,R))&&n.owned_paths?.some((s)=>s.role==="launcher"&&s.path===i.target))??!1}function d(n,t){try{return N(p(n),S(n))===t}catch{return!1}}function Jr(n){let t=h(n),r=t==="ara"?"reason":t==="ara-staging"?"reason-staging":null;if(!r)return n;let e=o(p(n),r);return d(e,n)||d(n,e)?e:n}function w(n,t){let r=O(n,t);return r.length>0&&!r.startsWith("..")&&!f(r)}function E(n){if(n===null)return!0;if(!n||typeof n!=="object"||Array.isArray(n))return!1;let t=n;return(t.kind==="shell_profile"||t.kind==="windows_user_path")&&a(t.location)&&a(t.value)&&(typeof t.added_by_installer==="boolean"||typeof t.added_by_ara==="boolean")&&(t.added_by_installer===void 0||typeof t.added_by_installer==="boolean")&&(t.added_by_ara===void 0||typeof t.added_by_ara==="boolean")}function k(n,t){if(t===null)return n==="cli_only";if(!t||typeof t!=="object"||Array.isArray(t))return!1;let r=t;if(r.version!==x||!a(r.recorded_at))return!1;if(n==="future_device")return r.decision==="authorized"&&B(r.scope);return r.scope===null&&r.decision===(n==="updates_only"?"ask":"disabled")}function G(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let t=n;if(t.schema_version!==P||!gt.includes(t.channel)||t.install_method!=="curl"||t.installer!=="shell"&&t.installer!=="powershell"||!a(t.installed_at)||!a(t.version)||!a(t.target)||!l(t.install_dir)||!Array.isArray(t.owned_paths)||!t.owned_paths.every(g)||!t.owned_paths.every((r)=>w(t.install_dir,r.path))||!I(t)||!E(t.path_entry))return null;return{...t,schema_version:c,installation_id:null,background_mode:"cli_only",device_consent:null}}function j(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let t=n;if(t.schema_version!==D||!v(t)||!y(t.background_mode)||!k(t.background_mode,t.device_consent))return null;return{...t,schema_version:c,installation_id:null}}function v(n){return gt.includes(n.channel)&&(n.install_method==="curl"&&(n.installer==="shell"||n.installer==="powershell")||n.install_method==="desktop"&&n.installer==="desktop"&&Array.isArray(n.owned_paths)&&n.owned_paths.length===0&&n.path_entry===null)&&a(n.installed_at)&&a(n.version)&&a(n.target)&&l(n.install_dir)&&Array.isArray(n.owned_paths)&&n.owned_paths.every(g)&&n.owned_paths.every((t)=>w(n.install_dir,t.path))&&I(n)&&E(n.path_entry)}function H(n){let t=G(n);if(t)return t;let r=j(n);if(r)return r;if(!n||typeof n!=="object"||Array.isArray(n))return null;let e=n;if(e.schema_version!==c||!z(e.installation_id)||!v(e)||!y(e.background_mode)||!k(e.background_mode,e.device_consent)||e.desktop_account_access!==void 0&&(e.desktop_account_access===null||typeof e.desktop_account_access!=="object"||Array.isArray(e.desktop_account_access)||e.desktop_account_access.version!==T||e.desktop_account_access.scope!==L||!a(e.desktop_account_access.recorded_at)||!Number.isFinite(Date.parse(e.desktop_account_access.recorded_at))))return null;return e}function ei(n=Kr()){if(!C(n))return null;try{return H(JSON.parse(b(n,"utf8")))}catch{return null}}export{Kr,Qn,Jr,ei};
2
+ import{gt,_,_t}from"./vm-hands-entry-lite-nqdstx24.js";import{chmodSync as Q,existsSync as C,mkdirSync as Z,readlinkSync as S,readFileSync as b,renameSync as nn,unlinkSync as tn,writeFileSync as en}from"fs";import{homedir as u}from"os";import{basename as h,dirname as p,isAbsolute as f,join as o,normalize as A,relative as O,resolve as N}from"path";var c=3,P=1,D=2,x=1,T=1,L="Reason may read and write files and run commands in this signed-in OS account, subject to saved restrictions and operating system permissions.",M="Reason may later execute on this computer inside a Reason sandbox, limited to folders explicitly attached by the user.",F=[M,"Ara may later execute on this computer inside an Ara sandbox, limited to folders explicitly attached by the user."];function B(n){return typeof n==="string"&&F.includes(n)}var U=["future_device","updates_only","cli_only"];function y(n){return typeof n==="string"&&U.some((t)=>t===n)}function V(n=process.env,t=u()){return n.XDG_CONFIG_HOME?.trim()||o(t,".config")}function Kr(n=process.env,t=u()){let r=_({env:n}),e=V(n,t);return o(e,_t(e).state==="kept"?"ara":"reason",...r==="staging"?["staging"]:[],"installation.json")}function a(n){return typeof n==="string"&&n.trim().length>0}var K=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function z(n){return typeof n==="string"&&K.test(n)}function l(n){return a(n)&&f(n)&&A(n)===n}function g(n){if(!n||typeof n!=="object"||Array.isArray(n))return!1;let t=n;return l(t.path)&&(t.role==="launcher"&&(t.kind==="file"||t.kind==="symlink")||t.role==="worker_root"&&t.kind==="directory"||t.role==="alias"&&t.kind==="symlink"&&l(t.target))}function m(n){return n==="staging"?["reason-staging","ara-staging"]:["reason","ara"]}function ei(n){let t=n.owned_paths.filter((e)=>e.role==="launcher").map((e)=>e.path),[r]=m(n.channel);return t.find((e)=>h(e)===r)??t[0]??null}function I(n){let[t,r]=m(n.channel==="staging"?"staging":"production"),e=[[t,r],[r,t]];return n.owned_paths?.every((i)=>i.role!=="alias"||n.installer==="shell"&&e.some(([s,R])=>i.path===o(n.install_dir,s)&&i.target===o(n.install_dir,R))&&n.owned_paths?.some((s)=>s.role==="launcher"&&s.path===i.target))??!1}function d(n,t){try{return N(p(n),S(n))===t}catch{return!1}}function Jr(n){let t=h(n),r=t==="ara"?"reason":t==="ara-staging"?"reason-staging":null;if(!r)return n;let e=o(p(n),r);return d(e,n)||d(n,e)?e:n}function w(n,t){let r=O(n,t);return r.length>0&&!r.startsWith("..")&&!f(r)}function E(n){if(n===null)return!0;if(!n||typeof n!=="object"||Array.isArray(n))return!1;let t=n;return(t.kind==="shell_profile"||t.kind==="windows_user_path")&&a(t.location)&&a(t.value)&&(typeof t.added_by_installer==="boolean"||typeof t.added_by_ara==="boolean")&&(t.added_by_installer===void 0||typeof t.added_by_installer==="boolean")&&(t.added_by_ara===void 0||typeof t.added_by_ara==="boolean")}function k(n,t){if(t===null)return n==="cli_only";if(!t||typeof t!=="object"||Array.isArray(t))return!1;let r=t;if(r.version!==x||!a(r.recorded_at))return!1;if(n==="future_device")return r.decision==="authorized"&&B(r.scope);return r.scope===null&&r.decision===(n==="updates_only"?"ask":"disabled")}function G(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let t=n;if(t.schema_version!==P||!gt.includes(t.channel)||t.install_method!=="curl"||t.installer!=="shell"&&t.installer!=="powershell"||!a(t.installed_at)||!a(t.version)||!a(t.target)||!l(t.install_dir)||!Array.isArray(t.owned_paths)||!t.owned_paths.every(g)||!t.owned_paths.every((r)=>w(t.install_dir,r.path))||!I(t)||!E(t.path_entry))return null;return{...t,schema_version:c,installation_id:null,background_mode:"cli_only",device_consent:null}}function j(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let t=n;if(t.schema_version!==D||!v(t)||!y(t.background_mode)||!k(t.background_mode,t.device_consent))return null;return{...t,schema_version:c,installation_id:null}}function v(n){return gt.includes(n.channel)&&(n.install_method==="curl"&&(n.installer==="shell"||n.installer==="powershell")||n.install_method==="desktop"&&n.installer==="desktop"&&Array.isArray(n.owned_paths)&&n.owned_paths.length===0&&n.path_entry===null)&&a(n.installed_at)&&a(n.version)&&a(n.target)&&l(n.install_dir)&&Array.isArray(n.owned_paths)&&n.owned_paths.every(g)&&n.owned_paths.every((t)=>w(n.install_dir,t.path))&&I(n)&&E(n.path_entry)}function H(n){let t=G(n);if(t)return t;let r=j(n);if(r)return r;if(!n||typeof n!=="object"||Array.isArray(n))return null;let e=n;if(e.schema_version!==c||!z(e.installation_id)||!v(e)||!y(e.background_mode)||!k(e.background_mode,e.device_consent)||e.desktop_account_access!==void 0&&(e.desktop_account_access===null||typeof e.desktop_account_access!=="object"||Array.isArray(e.desktop_account_access)||e.desktop_account_access.version!==T||e.desktop_account_access.scope!==L||!a(e.desktop_account_access.recorded_at)||!Number.isFinite(Date.parse(e.desktop_account_access.recorded_at))))return null;return e}function ti(n=Kr()){if(!C(n))return null;try{return H(JSON.parse(b(n,"utf8")))}catch{return null}}export{Kr,ei,Jr,ti};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{_,Zr,ke}from"./vm-hands-entry-lite-hxhd7btg.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 an(r,n=Fe()){return u(S(n),{recursive:!0,mode:448}),d(n,`${JSON.stringify(r,null,2)}
2
+ import{_,Zr,ke}from"./vm-hands-entry-lite-nqdstx24.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 an(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 Tt(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=Zr(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 cn(r=Fe()){if(!a(r))return!1;return l(r),!0}
5
5
  export{Fe,an,Tt,cn};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{A}from"./vm-hands-entry-lite-tbawqj1n.js";import{randomUUID as m}from"crypto";import{closeSync as k,constants as c,fstatSync as u,lstatSync as s,mkdirSync as l,openSync as E,readFileSync as S,realpathSync as a,renameSync as g,unlinkSync as p,writeFileSync as O}from"fs";import{dirname as w,resolve as _}from"path";var d=65536;function f(r){try{return s(r),!0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return!1;throw o}}function v(r,o=!1){if(!f(r)){if(!o)throw Error("worker_state_missing");y(r),l(r,{mode:448})}let e=s(r);if(!e.isDirectory()||e.isSymbolicLink()||!A(e)||a(r)!==_(r))throw Error("worker_state_directory_not_private_or_canonical")}function y(r){let o=w(r);if(!f(o))y(o),l(o,{mode:448});if(a(o)!==_(o))throw Error("worker_parent_not_canonical")}function h(r,o=d){let e=E(r,c.O_RDONLY|c.O_NOFOLLOW);try{let n=u(e);if(!n.isFile()||n.nlink!==1||!A(n)||n.size>o)throw Error("worker_file_not_private");return S(e,"utf8")}finally{k(e)}}function co(r,o,e=d){let n=JSON.stringify(o);if(n===void 0)throw Error("worker_file_invalid");let t=n+`
2
+ import{A}from"./vm-hands-entry-lite-87vmbt38.js";import{randomUUID as m}from"crypto";import{closeSync as k,constants as c,fstatSync as u,lstatSync as s,mkdirSync as l,openSync as E,readFileSync as S,realpathSync as a,renameSync as g,unlinkSync as p,writeFileSync as O}from"fs";import{dirname as w,resolve as _}from"path";var d=65536;function f(r){try{return s(r),!0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return!1;throw o}}function v(r,o=!1){if(!f(r)){if(!o)throw Error("worker_state_missing");y(r),l(r,{mode:448})}let e=s(r);if(!e.isDirectory()||e.isSymbolicLink()||!A(e)||a(r)!==_(r))throw Error("worker_state_directory_not_private_or_canonical")}function y(r){let o=w(r);if(!f(o))y(o),l(o,{mode:448});if(a(o)!==_(o))throw Error("worker_parent_not_canonical")}function h(r,o=d){let e=E(r,c.O_RDONLY|c.O_NOFOLLOW);try{let n=u(e);if(!n.isFile()||n.nlink!==1||!A(n)||n.size>o)throw Error("worker_file_not_private");return S(e,"utf8")}finally{k(e)}}function lo(r,o,e=d){let n=JSON.stringify(o);if(n===void 0)throw Error("worker_file_invalid");let t=n+`
3
3
  `;if(Buffer.byteLength(t,"utf8")>e)throw Error("worker_file_too_large");if(v(w(r)),f(r))h(r,e);let i=`${r}.${m()}`;try{O(i,t,{mode:384,flag:"wx"}),g(i,r)}finally{if(f(i))p(i)}}
4
- export{f,v,h,co};
4
+ export{f,v,h,lo};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{_,Xr,_t,ke}from"./vm-hands-entry-lite-hxhd7btg.js";import{Ao}from"./vm-hands-entry-lite-xkba45hh.js";import{a}from"./vm-hands-entry-lite-y7z8pfgt.js";import{t,i,s,n}from"./vm-hands-entry-lite-g27kmejx.js";import{createHmac as bt,createPublicKey as be,randomBytes as mt,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 Wt(r=process.execPath){let e=r;try{e=te(r)}catch{}return Ao(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=Wt(),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");_t(r);let e=f(r,"ara");return Xr(e)?e:f(r,"reason")}class Nr{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 Nr}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{_,Xr,_t,ke}from"./vm-hands-entry-lite-nqdstx24.js";import{Po}from"./vm-hands-entry-lite-7777m86y.js";import{a}from"./vm-hands-entry-lite-swrymqj9.js";import{t,i,s,n}from"./vm-hands-entry-lite-a1xa7s06.js";import{createHmac as bt,createPublicKey as be,randomBytes as mt,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 Wt(r=process.execPath){let e=r;try{e=te(r)}catch{}return Po(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=Wt(),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");_t(r);let e=f(r,"ara");return Xr(e)?e:f(r,"reason")}class Nr{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 Nr}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 Vt(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 Lr(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 Mr(r=Lr(),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 pt(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 Gt=1;function Be(r=Lr()){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!==Gt||typeof o.url!=="string"||o.url.length===0||o.caFile!==void 0&&(typeof o.caFile!=="string"||!Ae(o.caFile)))return null;return{version:Gt,url:o.url,...o.caFile?{caFile:o.caFile}:{}}}
5
5
  export{l,Wt,Ke,Nr,Vt,Lr,Mr,pt,Gt,j};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{Io}from"./vm-hands-entry-lite-hxhd7btg.js";import{Fe,an,Tt,cn}from"./vm-hands-entry-lite-633mzx27.js";import{Yn}from"./vm-hands-entry-lite-5g508mhr.js";import{t,o,d,u,i,os,W,g,s,n}from"./vm-hands-entry-lite-g27kmejx.js";var z=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function S(e){let r=typeof e==="string"?z.exec(e):null;return r?{major:Number(r[1]),minor:Number(r[2])}:null}var j=25,E=i({day:t().regex(/^\d{4}-\d{2}-\d{2}$/),sent:o().int().min(0).max(1e9),received:o().int().min(0).max(1e9)}),ve=i({machine:t().min(1).max(200),person:t().min(1).max(200),team:t().min(1).max(200),team_id:t().min(1).max(200).optional(),workspace:d().optional(),version:t().max(64).optional(),wait_seconds:o().int().min(0).max(j).optional(),message_counts:u(E).max(14).optional()}),L=g("kind",[i({id:t(),kind:n("who"),all:d().optional()}),i({id:t(),kind:n("send"),to:t(),body:t(),from_name:t(),from_agent:t(),wake:d(),reply_to:t().max(100).optional(),notify:d().optional()})]),k=i({job:L.nullable(),retry_after_seconds:o().optional()}),D=i({address:t(),person:t(),machine:t(),agent:t(),repo:t().nullable(),branch:t().nullable(),status:t(),since:o().nullable(),doing:t().nullable(),worker:d(),tier:t().max(10).optional()}),N=i({person:t(),machine:t(),online:d()}),H=i({team:t().nullable(),sessions:u(D).max(2000),machines:u(N).max(500),all:d().optional()}),B=i({address:t().max(300),state:t().max(40),note:t().max(500)}),Pe=W([i({who:H}),i({sent:i({ids:u(t().max(100)).max(500),recipients:u(t().max(300)).max(500),from:t().max(300),deliveries:u(B).max(500).optional()})}),i({error:t().min(1).max(2000)})]),F=i({id:t().max(100),from:t().max(300),from_agent:t().max(100).nullable(),to:t().max(300),reply_to:t().max(100).nullable(),body:t().max(64000),sent_at:o()}),xe=i({messages:u(F).max(100),team:t().min(1).max(200).optional(),team_id:t().min(1).max(200).optional(),workspace:d().optional()});var v=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var Ne=v.filter((e)=>e!=="network:read"&&e!=="network:write");class b extends Error{oauthCode;constructor(e,r=null){super(e);this.oauthCode=r;this.name="LoginError"}}function J(e,r){let a=typeof e.error==="string"?e.error:null,l=typeof e.error_description==="string"?e.error_description:a?a:r;return new b(l,a)}async function G(e,r,a,l){let c=await a(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:r,signal:l}),m=await c.json().catch(()=>({}));if(!c.ok)throw J(m,`OAuth token request failed (${c.status})`);return m}var Q=1e4;async function K(e,r={}){let a=r.fetchImpl??fetch,l=await G(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),a,AbortSignal.timeout(Q)).catch((m)=>{if(m instanceof Error&&m.name==="TimeoutError")throw new b("Reason did not answer the login refresh in time. Check the network and retry.");throw m});if(typeof l.access_token!=="string"||typeof l.refresh_token!=="string"||typeof l.expires_in!=="number")throw new b("Reason returned an incomplete refreshed login.");let c={...e,accessToken:l.access_token,refreshToken:l.refresh_token,expiresAt:new Date(Date.now()+l.expires_in*1000).toISOString(),scopes:typeof l.scope==="string"?l.scope.split(/\s+/).filter(Boolean):e.scopes};return an(c,r.path??Fe()),c}var R=new Map,V=2000,Y=100;function P(e,r){if(!r)return e;if(r.aborted)return Promise.reject(r.reason);return new Promise((a,l)=>{let c=()=>l(r.reason);r.addEventListener("abort",c,{once:!0}),e.then(a,l).finally(()=>r.removeEventListener("abort",c))})}async function Pt(e={}){let r=e.path??Fe(),a=Tt(r);if(!a)return null;let l=e.apiOrigin??T(process.env,"REASON_API_URL")?.trim();if(l&&!Io(a.apiOrigin,new URL(l).origin))return null;if(!(Date.parse(a.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&a.accessToken!==e.refused))return a;let m=[r,a.apiOrigin,a.clientId,a.refreshToken].join("\x00"),p=R.get(m);if(p)return P(p,e.signal);let f;return f=K(a,{fetchImpl:e.fetchImpl,path:r}).catch(async(y)=>{if(!(y instanceof b)||y.oauthCode!=="invalid_grant"&&y.oauthCode!=="invalid_client")throw y;let w=(_)=>_!==null&&(y.oauthCode==="invalid_client"?_.clientId!==a.clientId:_.refreshToken!==a.refreshToken),O=Date.now()+V;while(!w(Tt(r))&&Date.now()<O)await new Promise((_)=>setTimeout(_,Y));if(w(Tt(r)))return Pt({fetchImpl:e.fetchImpl,path:r});return cn(r),null}).finally(()=>{if(R.get(m)===f)R.delete(m)}),R.set(m,f),P(f,e.signal)}var Z=i({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:d().nullable()}),X=i({groups:u(i({selectable:d().optional(),accounts:u(i({source_id:t().min(1),model_ids:u(t().min(1)).optional()}))}))});function ee(e){let r=X.safeParse(e);if(!r.success)return;return r.data.groups.some((a)=>a.selectable!==!1&&a.accounts.some((l)=>l.model_ids===void 0||l.model_ids.length>0))}class I extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor(e,r,a,l,c,m){super(a);this.status=e;this.code=r;this.suggestedModel=l;this.retryAfterMs=c;this.resolutionReason=m;this.name="ApiError"}static rateLimitDelayMs(e,r){if(!(e instanceof I)||e.status!==429)return null;return Math.min(60000,Math.max(r,e.retryAfterMs??0))}}var ne=["minimal","low","medium","high","xhigh","max"],te=i({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:d(),compatible:d().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:u(i({id:t().min(1),label:t()}))}),se=i({devices:u(te),end_cursor:t().nullish(),has_next_page:d().optional()}),oe=i({id:t().min(1),name:t()}),re=i({items:u(oe)}),ie=i({id:t().min(1),name:t(),main:d(),mine:d(),session_id:t().nullish(),appearance:i({color:t().nullish()}).nullish().catch(null)}),ae=i({items:u(ie)}),le=i({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:u(t()).default([]),is_enabled:d().default(!0)}),ce=i({items:u(le).default([])}),de=i({id:t().min(1),kind:t(),enabled:d(),schedule:i({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:i({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),C=i({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:d(),triggers:u(de).default([])}),me=i({items:u(C).default([]),end_cursor:t().nullish(),has_next_page:d().optional()}),ue=i({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:d()}),ge=i({items:u(ue).default([])}),he=i({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),x=i({tags:u(t()).default([])}),pe=s(["linux","macos"]),A=i({id:t().min(1),name:t().min(1),platform:pe.nullable(),workers:i({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:i({queued:o().int(),running:o().int()})}),fe=i({machines:u(A)}),ye=i({machine:A}),_e=i({deleted:n(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),be=i({token:i({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),U=os({machine_id:t().min(1),machine_name:t().min(1)}),Re=U.extend({organization_id:t().min(1)}),We=i({id:t().min(1),name:t().min(1),state:s(["waiting","placed"]),queue_position:o().int().nullable()});var Ve=W([i({kind:n("cloud")}),i({kind:s(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function h(e,r,a){let l=e.safeParse(r);if(!l.success)throw new I(502,a,"Reason returned an unexpected response.");return l.data}var we=i({error:i({type:t(),message:t()})});function q(e,r,a){let l=we.safeParse(r),c=typeof r.error==="string"?r.error:l.success?l.data.error.type:`http_${e}`,m=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:l.success?l.data.error.message:`Reason request failed (${e}${typeof r.error==="string"?` ${r.error}`:""})`,p=c==="github_connection_required"&&typeof r.connect_url==="string"&&/^https?:\/\//.test(r.connect_url)?` Connect it at ${r.connect_url}`:"",f=a===null||a.trim()===""?NaN:Number(a);return new I(e,c,`${m}${p}`,typeof r.suggested_model==="string"?r.suggested_model:void 0,Number.isFinite(f)&&f>=0?f*1000:void 0,typeof r.resolution_reason==="string"?r.resolution_reason:void 0)}async function gs(e){let r=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),a=await r.json().catch(()=>({}));if(!r.ok)throw q(r.status,a,r.headers.get("retry-after"));return h(Re,a,"invalid_machine_ticket")}class Vo{options;credentials;constructor(e,r={}){this.options=r;this.credentials=e}trackEvent(e,r={}){}async request(e,r={},a=!1){let l=this.options.fetchImpl??fetch,c=await l(`${this.credentials.apiOrigin}/v3${e}`,{method:r.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Yn,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...r.raw?{"content-type":r.raw.contentType}:r.body===void 0?{}:{"content-type":"application/json"},...r.headers},body:r.raw?r.raw.bytes:r.body===void 0?void 0:JSON.stringify(r.body),signal:r.signal,redirect:"error"}),m=await c.json().catch(()=>({}));if(c.status===401&&!a&&r.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let p=await Pt({fetchImpl:l,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:r.signal});if(p)return this.credentials=p,this.request(e,r,!0)}if(!c.ok)throw q(c.status,m,c.headers.get("retry-after"));return m}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(r){if(r instanceof I&&(r.status===404||r.status===405||r.status===403&&r.code==="endpoint_not_available"))return null;throw r}}addDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(r)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,r=""){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?a:`${a}/${encodeURIComponent(e)}${r}`}async listMachines(){return h(fe,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let r=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return h(ye,r,"invalid_machine").machine}async deleteMachine(e){let r=await this.request(this.machinePath(e),{method:"DELETE"});return h(_e,r,"invalid_machine_deletion")}async createMachineToken(e){let r=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return h(be,r,"invalid_machine_token")}async createMachineEnrollmentTicket(e,r){let a=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:r,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return h(U,a,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:r});return h(k,a,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((r)=>typeof r.email==="string"?[{email:r.email,role:typeof r.role==="string"?r.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,r,a={}){let l=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:a.retryUnauthorized,signal:a.signal,body:{...l,...r?{account_key:r}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((r)=>{let a=typeof r.full_name==="string"?r.full_name:typeof r.repo_full_name==="string"?r.repo_full_name:null;if(!a)return[];return[{repo_id:typeof r.repo_id==="string"?r.repo_id:void 0,full_name:a,provider:r.provider==="gitlab"?"gitlab":"github",default_branch:typeof r.default_branch==="string"?r.default_branch:null,private:typeof r.private==="boolean"?r.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),r=re.safeParse(e);if(!r.success)throw new I(502,"invalid_project_list","Reason returned an unexpected project list.");return r.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return h(ae,e,"invalid_reason_list").items}async openReasonConversation(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return h(i({session_id:t().min(1)}),r,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return h(ce,e,"invalid_skill_list").items}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${r?`?after=${encodeURIComponent(r)}`:""}`),c=se.safeParse(l);if(!c.success)throw new I(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...c.data.devices),r=c.data.has_next_page?c.data.end_cursor??null:null,!r)break}return e}async listModels(){try{let r=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((c)=>c.hidden!==!0),a=r.filter((c)=>c.available!==!1).map(({reasoning_efforts:c,hidden:m,available:p,...f})=>({...f,...Array.isArray(c)?{reasoning_efforts:ne.filter((y)=>c.includes(y))}:{}})),l=new Set(a.map((c)=>c.detail));return{models:a.length>1&&l.size===1?a.map(({detail:c,...m})=>m):a,runnable:a.length>0||r.length===0}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let r=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return S(r.reason_version)?r.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=Z.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let r;try{r=ee(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:r}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return null;throw e}}async listSessions(e=50,r,a={}){let l=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:a.status??"active"});if(r)l.set("project_id",r);if(a.origin)l.set("origin",a.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${l.toString()}`)).items??[]}getSession(e,r){let a=r?.fields.length?`?fields=${encodeURIComponent(r.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${a}`)}async prestartSession(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return r?.status==="starting"||r?.status==="ready"}async createSession(e){let r=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(r||e.runtimeProfile){let c=await this.request("/deployment");if(r&&(!Array.isArray(c.session_modes)||!c.session_modes.includes(e.mode??"standard")||!Array.isArray(c.workspace_ownerships)||!c.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(c.experimental_runtime_profiles)||!c.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),l=await this.getSession(a.session_id);if(r){let c=l.session_policy,m=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!c||c.version!==1||c.mode!==(e.mode??"standard")||c.workspaceOwnership!==(e.workspaceOwnership??"managed")||!c.components||m.some((p)=>c.components[p]!==!0))throw await this.cancelSession(a.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&l.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(a.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return l}async getEvents(e,r=-1,a={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${r}&limit=500${a.waitMs?`&wait_ms=${a.waitMs}`:""}`,a.signal?{signal:a.signal}:{})}catch(l){if(!(l instanceof I)||l.status!==403&&l.status!==404)throw l;return{session:await this.getSession(e),items:[],next_seq:r}}}async getMessages(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${r===void 0?"":`&after_seq=${r}`}`)}async getAttachments(e,r){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${r?`?view=${r}`:""}`)).items??[]}catch(a){if(a instanceof I&&(a.status===403||a.status===404))return[];throw a}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let r=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,a=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,l=[r,a].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${l?` (${l})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,r,a={}){if(a.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:r,...a.attachments?.length?{attachments:a.attachments}:{},...a.model?{model:a.model}:{},...a.reasoningEffort?{reasoning_effort:a.reasoningEffort}:{},...a.target?{target:a.target}:{},...a.delivery?{delivery:a.delivery}:{}}})}async steerQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/queued`,{method:"DELETE"})}async getConversation(e){let r=[],a=null;for(let l=0;l<50;l+=1){let c=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${a?`?after=${encodeURIComponent(a)}`:""}`);if(r.push(...c.items??[]),!c.has_next_page||!c.end_cursor)break;a=c.end_cursor}return r}createSharedLink(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:r.url,...r.label?{label:r.label}:{},...r.expiresInSeconds!==void 0?{expires_in_seconds:r.expiresInSeconds}:{}}})}sessionAction(e,r,a={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${r}`,{method:"POST",body:a})}renameSession(e,r){return this.sessionAction(e,"rename",{title:r||null})}moveSessionToProject(e,r){return this.sessionAction(e,"project",{project_id:r})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,r){return this.sessionAction(e,"rewind",{message_id:r.messageId,content:r.content,request_id:r.requestId})}forkSession(e,r){return this.sessionAction(e,"fork",{...r.message?{message:r.message}:{},client_session_id:r.clientSessionId})}cancelSession(e,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:r.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,r=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return h(x,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,r){let a=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:r}});return h(x,a,"invalid_session_tags").tags}async sessionInsight(e,r=!1){let a=await this.request(this.sessionPath(e,r?"/insights/generate":"/insights"),r?{method:"POST",body:{}}:{});return h(he,a,"invalid_session_insight")}async listAutomations(){let e=[],r=null;for(let a=0;a<20;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${r?`&after=${encodeURIComponent(r)}`:""}`),c=h(me,l,"invalid_automation_list");if(e.push(...c.items),r=c.has_next_page?c.end_cursor??null:null,!r)break}return e}async createScheduledAutomation(e,r){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,l=h(C,await this.request(a,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${a}/${encodeURIComponent(l.id)}/triggers`,{method:"POST",body:r})}catch(c){throw await this.deleteAutomation(l.id).catch(()=>{return}),c}return l}async setAutomationEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:r}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:r}});return h(i({transcript:t()}),a,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return h(ge,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:r}})}}
3
- export{Pt,I,gs,Vo};
2
+ import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{Do}from"./vm-hands-entry-lite-nqdstx24.js";import{Fe,an,Tt,cn}from"./vm-hands-entry-lite-f62fvme8.js";import{Qn}from"./vm-hands-entry-lite-b7zgdjf9.js";import{t,o,d,u,i,ss,W,g,s,n}from"./vm-hands-entry-lite-a1xa7s06.js";var z=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function S(e){let r=typeof e==="string"?z.exec(e):null;return r?{major:Number(r[1]),minor:Number(r[2])}:null}var j=25,E=i({day:t().regex(/^\d{4}-\d{2}-\d{2}$/),sent:o().int().min(0).max(1e9),received:o().int().min(0).max(1e9)}),ve=i({machine:t().min(1).max(200),person:t().min(1).max(200),team:t().min(1).max(200),team_id:t().min(1).max(200).optional(),workspace:d().optional(),version:t().max(64).optional(),wait_seconds:o().int().min(0).max(j).optional(),message_counts:u(E).max(14).optional()}),L=g("kind",[i({id:t(),kind:n("who"),all:d().optional()}),i({id:t(),kind:n("send"),to:t(),body:t(),from_name:t(),from_agent:t(),wake:d(),reply_to:t().max(100).optional(),notify:d().optional()})]),k=i({job:L.nullable(),retry_after_seconds:o().optional()}),D=i({address:t(),person:t(),machine:t(),agent:t(),repo:t().nullable(),branch:t().nullable(),status:t(),since:o().nullable(),doing:t().nullable(),worker:d(),tier:t().max(10).optional()}),N=i({person:t(),machine:t(),online:d()}),H=i({team:t().nullable(),sessions:u(D).max(2000),machines:u(N).max(500),all:d().optional()}),B=i({address:t().max(300),state:t().max(40),note:t().max(500)}),Pe=W([i({who:H}),i({sent:i({ids:u(t().max(100)).max(500),recipients:u(t().max(300)).max(500),from:t().max(300),deliveries:u(B).max(500).optional()})}),i({error:t().min(1).max(2000)})]),F=i({id:t().max(100),from:t().max(300),from_agent:t().max(100).nullable(),to:t().max(300),reply_to:t().max(100).nullable(),body:t().max(64000),sent_at:o()}),xe=i({messages:u(F).max(100),team:t().min(1).max(200).optional(),team_id:t().min(1).max(200).optional(),workspace:d().optional()});var v=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var Ne=v.filter((e)=>e!=="network:read"&&e!=="network:write");class b extends Error{oauthCode;constructor(e,r=null){super(e);this.oauthCode=r;this.name="LoginError"}}function J(e,r){let a=typeof e.error==="string"?e.error:null,l=typeof e.error_description==="string"?e.error_description:a?a:r;return new b(l,a)}async function G(e,r,a,l){let c=await a(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:r,signal:l}),m=await c.json().catch(()=>({}));if(!c.ok)throw J(m,`OAuth token request failed (${c.status})`);return m}var Q=1e4;async function K(e,r={}){let a=r.fetchImpl??fetch,l=await G(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),a,AbortSignal.timeout(Q)).catch((m)=>{if(m instanceof Error&&m.name==="TimeoutError")throw new b("Reason did not answer the login refresh in time. Check the network and retry.");throw m});if(typeof l.access_token!=="string"||typeof l.refresh_token!=="string"||typeof l.expires_in!=="number")throw new b("Reason returned an incomplete refreshed login.");let c={...e,accessToken:l.access_token,refreshToken:l.refresh_token,expiresAt:new Date(Date.now()+l.expires_in*1000).toISOString(),scopes:typeof l.scope==="string"?l.scope.split(/\s+/).filter(Boolean):e.scopes};return an(c,r.path??Fe()),c}var R=new Map,V=2000,Y=100;function P(e,r){if(!r)return e;if(r.aborted)return Promise.reject(r.reason);return new Promise((a,l)=>{let c=()=>l(r.reason);r.addEventListener("abort",c,{once:!0}),e.then(a,l).finally(()=>r.removeEventListener("abort",c))})}async function Pt(e={}){let r=e.path??Fe(),a=Tt(r);if(!a)return null;let l=e.apiOrigin??T(process.env,"REASON_API_URL")?.trim();if(l&&!Do(a.apiOrigin,new URL(l).origin))return null;if(!(Date.parse(a.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&a.accessToken!==e.refused))return a;let m=[r,a.apiOrigin,a.clientId,a.refreshToken].join("\x00"),p=R.get(m);if(p)return P(p,e.signal);let f;return f=K(a,{fetchImpl:e.fetchImpl,path:r}).catch(async(y)=>{if(!(y instanceof b)||y.oauthCode!=="invalid_grant"&&y.oauthCode!=="invalid_client")throw y;let w=(_)=>_!==null&&(y.oauthCode==="invalid_client"?_.clientId!==a.clientId:_.refreshToken!==a.refreshToken),O=Date.now()+V;while(!w(Tt(r))&&Date.now()<O)await new Promise((_)=>setTimeout(_,Y));if(w(Tt(r)))return Pt({fetchImpl:e.fetchImpl,path:r});return cn(r),null}).finally(()=>{if(R.get(m)===f)R.delete(m)}),R.set(m,f),P(f,e.signal)}var Z=i({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:d().nullable()}),X=i({groups:u(i({selectable:d().optional(),accounts:u(i({source_id:t().min(1),model_ids:u(t().min(1)).optional()}))}))});function ee(e){let r=X.safeParse(e);if(!r.success)return;return r.data.groups.some((a)=>a.selectable!==!1&&a.accounts.some((l)=>l.model_ids===void 0||l.model_ids.length>0))}class I extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor(e,r,a,l,c,m){super(a);this.status=e;this.code=r;this.suggestedModel=l;this.retryAfterMs=c;this.resolutionReason=m;this.name="ApiError"}static rateLimitDelayMs(e,r){if(!(e instanceof I)||e.status!==429)return null;return Math.min(60000,Math.max(r,e.retryAfterMs??0))}}var ne=["minimal","low","medium","high","xhigh","max"],te=i({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:d(),compatible:d().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:u(i({id:t().min(1),label:t()}))}),se=i({devices:u(te),end_cursor:t().nullish(),has_next_page:d().optional()}),oe=i({id:t().min(1),name:t()}),re=i({items:u(oe)}),ie=i({id:t().min(1),name:t(),main:d(),mine:d(),session_id:t().nullish(),appearance:i({color:t().nullish()}).nullish().catch(null)}),ae=i({items:u(ie)}),le=i({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:u(t()).default([]),is_enabled:d().default(!0)}),ce=i({items:u(le).default([])}),de=i({id:t().min(1),kind:t(),enabled:d(),schedule:i({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:i({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),C=i({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:d(),triggers:u(de).default([])}),me=i({items:u(C).default([]),end_cursor:t().nullish(),has_next_page:d().optional()}),ue=i({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:d()}),ge=i({items:u(ue).default([])}),he=i({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),x=i({tags:u(t()).default([])}),pe=s(["linux","macos"]),A=i({id:t().min(1),name:t().min(1),platform:pe.nullable(),workers:i({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:i({queued:o().int(),running:o().int()})}),fe=i({machines:u(A)}),ye=i({machine:A}),_e=i({deleted:n(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),be=i({token:i({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),U=ss({machine_id:t().min(1),machine_name:t().min(1)}),Re=U.extend({organization_id:t().min(1)}),We=i({id:t().min(1),name:t().min(1),state:s(["waiting","placed"]),queue_position:o().int().nullable()});var Ve=W([i({kind:n("cloud")}),i({kind:s(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function h(e,r,a){let l=e.safeParse(r);if(!l.success)throw new I(502,a,"Reason returned an unexpected response.");return l.data}var we=i({error:i({type:t(),message:t()})});function q(e,r,a){let l=we.safeParse(r),c=typeof r.error==="string"?r.error:l.success?l.data.error.type:`http_${e}`,m=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:l.success?l.data.error.message:`Reason request failed (${e}${typeof r.error==="string"?` ${r.error}`:""})`,p=c==="github_connection_required"&&typeof r.connect_url==="string"&&/^https?:\/\//.test(r.connect_url)?` Connect it at ${r.connect_url}`:"",f=a===null||a.trim()===""?NaN:Number(a);return new I(e,c,`${m}${p}`,typeof r.suggested_model==="string"?r.suggested_model:void 0,Number.isFinite(f)&&f>=0?f*1000:void 0,typeof r.resolution_reason==="string"?r.resolution_reason:void 0)}async function _s(e){let r=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),a=await r.json().catch(()=>({}));if(!r.ok)throw q(r.status,a,r.headers.get("retry-after"));return h(Re,a,"invalid_machine_ticket")}class Go{options;credentials;constructor(e,r={}){this.options=r;this.credentials=e}trackEvent(e,r={}){}async request(e,r={},a=!1){let l=this.options.fetchImpl??fetch,c=await l(`${this.credentials.apiOrigin}/v3${e}`,{method:r.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Qn,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...r.raw?{"content-type":r.raw.contentType}:r.body===void 0?{}:{"content-type":"application/json"},...r.headers},body:r.raw?r.raw.bytes:r.body===void 0?void 0:JSON.stringify(r.body),signal:r.signal,redirect:"error"}),m=await c.json().catch(()=>({}));if(c.status===401&&!a&&r.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let p=await Pt({fetchImpl:l,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:r.signal});if(p)return this.credentials=p,this.request(e,r,!0)}if(!c.ok)throw q(c.status,m,c.headers.get("retry-after"));return m}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(r){if(r instanceof I&&(r.status===404||r.status===405||r.status===403&&r.code==="endpoint_not_available"))return null;throw r}}addDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(r)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,r=""){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?a:`${a}/${encodeURIComponent(e)}${r}`}async listMachines(){return h(fe,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let r=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return h(ye,r,"invalid_machine").machine}async deleteMachine(e){let r=await this.request(this.machinePath(e),{method:"DELETE"});return h(_e,r,"invalid_machine_deletion")}async createMachineToken(e){let r=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return h(be,r,"invalid_machine_token")}async createMachineEnrollmentTicket(e,r){let a=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:r,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return h(U,a,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:r});return h(k,a,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((r)=>typeof r.email==="string"?[{email:r.email,role:typeof r.role==="string"?r.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,r,a={}){let l=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:a.retryUnauthorized,signal:a.signal,body:{...l,...r?{account_key:r}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((r)=>{let a=typeof r.full_name==="string"?r.full_name:typeof r.repo_full_name==="string"?r.repo_full_name:null;if(!a)return[];return[{repo_id:typeof r.repo_id==="string"?r.repo_id:void 0,full_name:a,provider:r.provider==="gitlab"?"gitlab":"github",default_branch:typeof r.default_branch==="string"?r.default_branch:null,private:typeof r.private==="boolean"?r.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),r=re.safeParse(e);if(!r.success)throw new I(502,"invalid_project_list","Reason returned an unexpected project list.");return r.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return h(ae,e,"invalid_reason_list").items}async openReasonConversation(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return h(i({session_id:t().min(1)}),r,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return h(ce,e,"invalid_skill_list").items}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${r?`?after=${encodeURIComponent(r)}`:""}`),c=se.safeParse(l);if(!c.success)throw new I(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...c.data.devices),r=c.data.has_next_page?c.data.end_cursor??null:null,!r)break}return e}async listModels(){try{let r=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((c)=>c.hidden!==!0),a=r.filter((c)=>c.available!==!1).map(({reasoning_efforts:c,hidden:m,available:p,...f})=>({...f,...Array.isArray(c)?{reasoning_efforts:ne.filter((y)=>c.includes(y))}:{}})),l=new Set(a.map((c)=>c.detail));return{models:a.length>1&&l.size===1?a.map(({detail:c,...m})=>m):a,runnable:a.length>0||r.length===0}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let r=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return S(r.reason_version)?r.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=Z.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let r;try{r=ee(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:r}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return null;throw e}}async listSessions(e=50,r,a={}){let l=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:a.status??"active"});if(r)l.set("project_id",r);if(a.origin)l.set("origin",a.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${l.toString()}`)).items??[]}getSession(e,r){let a=r?.fields.length?`?fields=${encodeURIComponent(r.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${a}`)}async prestartSession(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return r?.status==="starting"||r?.status==="ready"}async createSession(e){let r=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(r||e.runtimeProfile){let c=await this.request("/deployment");if(r&&(!Array.isArray(c.session_modes)||!c.session_modes.includes(e.mode??"standard")||!Array.isArray(c.workspace_ownerships)||!c.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(c.experimental_runtime_profiles)||!c.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),l=await this.getSession(a.session_id);if(r){let c=l.session_policy,m=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!c||c.version!==1||c.mode!==(e.mode??"standard")||c.workspaceOwnership!==(e.workspaceOwnership??"managed")||!c.components||m.some((p)=>c.components[p]!==!0))throw await this.cancelSession(a.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&l.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(a.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return l}async getEvents(e,r=-1,a={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${r}&limit=500${a.waitMs?`&wait_ms=${a.waitMs}`:""}`,a.signal?{signal:a.signal}:{})}catch(l){if(!(l instanceof I)||l.status!==403&&l.status!==404)throw l;return{session:await this.getSession(e),items:[],next_seq:r}}}async getMessages(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${r===void 0?"":`&after_seq=${r}`}`)}async getAttachments(e,r){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${r?`?view=${r}`:""}`)).items??[]}catch(a){if(a instanceof I&&(a.status===403||a.status===404))return[];throw a}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let r=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,a=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,l=[r,a].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${l?` (${l})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,r,a={}){if(a.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:r,...a.attachments?.length?{attachments:a.attachments}:{},...a.model?{model:a.model}:{},...a.reasoningEffort?{reasoning_effort:a.reasoningEffort}:{},...a.target?{target:a.target}:{},...a.delivery?{delivery:a.delivery}:{}}})}async steerQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/queued`,{method:"DELETE"})}async getConversation(e){let r=[],a=null;for(let l=0;l<50;l+=1){let c=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${a?`?after=${encodeURIComponent(a)}`:""}`);if(r.push(...c.items??[]),!c.has_next_page||!c.end_cursor)break;a=c.end_cursor}return r}createSharedLink(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:r.url,...r.label?{label:r.label}:{},...r.expiresInSeconds!==void 0?{expires_in_seconds:r.expiresInSeconds}:{}}})}sessionAction(e,r,a={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${r}`,{method:"POST",body:a})}renameSession(e,r){return this.sessionAction(e,"rename",{title:r||null})}moveSessionToProject(e,r){return this.sessionAction(e,"project",{project_id:r})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,r){return this.sessionAction(e,"rewind",{message_id:r.messageId,content:r.content,request_id:r.requestId})}forkSession(e,r){return this.sessionAction(e,"fork",{...r.message?{message:r.message}:{},client_session_id:r.clientSessionId})}cancelSession(e,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:r.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,r=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return h(x,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,r){let a=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:r}});return h(x,a,"invalid_session_tags").tags}async sessionInsight(e,r=!1){let a=await this.request(this.sessionPath(e,r?"/insights/generate":"/insights"),r?{method:"POST",body:{}}:{});return h(he,a,"invalid_session_insight")}async listAutomations(){let e=[],r=null;for(let a=0;a<20;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${r?`&after=${encodeURIComponent(r)}`:""}`),c=h(me,l,"invalid_automation_list");if(e.push(...c.items),r=c.has_next_page?c.end_cursor??null:null,!r)break}return e}async createScheduledAutomation(e,r){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,l=h(C,await this.request(a,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${a}/${encodeURIComponent(l.id)}/triggers`,{method:"POST",body:r})}catch(c){throw await this.deleteAutomation(l.id).catch(()=>{return}),c}return l}async setAutomationEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:r}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:r}});return h(i({transcript:t()}),a,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return h(ge,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:r}})}}
3
+ export{Pt,I,_s,Go};
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import{Qe}from"./vm-hands-entry-lite-5g508mhr.js";import{a}from"./vm-hands-entry-lite-y7z8pfgt.js";import{randomUUID as L}from"crypto";import{spawnSync as b}from"child_process";import{chmodSync as ee,cpSync as te,existsSync as x,lstatSync as A,mkdirSync as Y,readdirSync as ne,readFileSync as w,readlinkSync as re,realpathSync as T,renameSync as E,rmdirSync as ie,rmSync as g,symlinkSync as M,writeFileSync as oe}from"fs";import{dirname as I,join as u,relative as se,resolve as ce}from"path";var Zn="so.ara.cli",k=[Zn,"com.reasonmachines.cli"],F="5LJFSBRY2F";function Vr(e){return`(${e.map((t)=>`identifier "${t}"`).join(" or ")}) and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = "${F}"`}var G="ReasonBackgroundIdentity",Po="Contents/Helpers/ReasonPermissionTile",ae="so.ara.cli.permission-tile",Ne=Vr([ae,"com.reasonmachines.cli.permission-tile"]),v="AraBackgroundIdentity",ue="Reason",Ce=Vr(k),de=`anchor apple generic and (${k.map((e)=>`identifier "${e}"`).join(" or ")}) and certificate leaf[subject.OU] = "${F}"`;class h extends Error{code;constructor(e,t){super(t);this.code=e;this.name="MacOSBackgroundIdentityError"}}var R="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";function le(e=a()){return u(e,"Library","Application Support","Reason","Background","Reason.app")}function O(e=a()){return u(e,"Library","Application Support","Ara","Background","Ara.app")}function fe(e){try{return A(e).isFile()}catch{return!1}}function D(e){return[G,v].map((t)=>u(e,"Contents","MacOS",t)).find(fe)??null}function d(e){try{if(!A(e).isDirectory())return!1;let t=w(u(e,"Contents","Info.plist"),"utf8");return k.some((n)=>t.includes(`<string>${n}</string>`))&&(t.includes(`<string>${ue}</string>`)||t.includes("<string>Ara</string>"))&&D(e)!==null}catch{return!1}}function Gr(e=a()){let t=le(e);if(!d(t))return null;try{let n=w(u(t,"Contents","Info.plist"),"utf8");return/<key>CFBundleVersion<\/key>\s*<string>(\d+\.\d+\.\d+)<\/string>/.exec(n)?.[1]??null}catch{return null}}function pe(e,t=a()){let n=Gr(t);return n===null||j(N(n.split(".")),N(e.split(/[.-]/).slice(0,3)))}var ge=1e4;function K(e,t){return b(e,[...t],{stdio:"ignore",timeout:ge}).status??1}var W=new Set;function H(e){if(process.env.REASON_TEST_REFUSE_REAL_IDENTITY!=="1")return;let t=(n)=>{try{return T(n)}catch{return ce(n)}};if(e!==void 0&&t(e)!==t(a()))return;throw Error("A test tried to change this computer's real Reason background identity; pass a temporary home. Refused by scripts/test-env.ts.")}var V=/\/(?:runtime|CLI)\/versions\/(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$|\/\.(?:ara|reason)(?:-staging)?-worker-(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$/,J=new Set(["ara","ara.exe","reason","reason.exe"]);function N(e){return e.map((t)=>Number(t))}function j(e,t){for(let n=0;n<3;n+=1)if(e[n]!==t[n])return e[n]<t[n];return!1}var ye=[0,2,161];function me(e){if(e===null)return!0;let t=ye,n=null;try{n=T(process.execPath)}catch{}return e.some((r)=>{let i=V.exec(r);if(i){let f=i[1]===void 0?i.slice(4,7):i.slice(1,4);return j(N(f),t)}let o=r.slice(r.lastIndexOf("/")+1);return J.has(o)&&r!==n&&r!==process.execPath})}function Ee(){let e=b("/bin/ps",["-xo","pid=,comm="],{encoding:"utf8",timeout:5000});if(e.status!==0)return null;let t=[];for(let n of e.stdout.split(`
2
+ import{Qe}from"./vm-hands-entry-lite-b7zgdjf9.js";import{a}from"./vm-hands-entry-lite-swrymqj9.js";import{randomUUID as L}from"crypto";import{spawnSync as b}from"child_process";import{chmodSync as ee,cpSync as te,existsSync as x,lstatSync as A,mkdirSync as Y,readdirSync as ne,readFileSync as w,readlinkSync as re,realpathSync as T,renameSync as E,rmdirSync as ie,rmSync as g,symlinkSync as M,writeFileSync as oe}from"fs";import{dirname as I,join as u,relative as se,resolve as ce}from"path";var Xn="so.ara.cli",k=[Xn,"com.reasonmachines.cli"],F="5LJFSBRY2F";function Vr(e){return`(${e.map((t)=>`identifier "${t}"`).join(" or ")}) and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = "${F}"`}var G="ReasonBackgroundIdentity",To="Contents/Helpers/ReasonPermissionTile",ae="so.ara.cli.permission-tile",Ne=Vr([ae,"com.reasonmachines.cli.permission-tile"]),v="AraBackgroundIdentity",ue="Reason",Ce=Vr(k),de=`anchor apple generic and (${k.map((e)=>`identifier "${e}"`).join(" or ")}) and certificate leaf[subject.OU] = "${F}"`;class h extends Error{code;constructor(e,t){super(t);this.code=e;this.name="MacOSBackgroundIdentityError"}}var R="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";function le(e=a()){return u(e,"Library","Application Support","Reason","Background","Reason.app")}function O(e=a()){return u(e,"Library","Application Support","Ara","Background","Ara.app")}function fe(e){try{return A(e).isFile()}catch{return!1}}function D(e){return[G,v].map((t)=>u(e,"Contents","MacOS",t)).find(fe)??null}function d(e){try{if(!A(e).isDirectory())return!1;let t=w(u(e,"Contents","Info.plist"),"utf8");return k.some((n)=>t.includes(`<string>${n}</string>`))&&(t.includes(`<string>${ue}</string>`)||t.includes("<string>Ara</string>"))&&D(e)!==null}catch{return!1}}function Gr(e=a()){let t=le(e);if(!d(t))return null;try{let n=w(u(t,"Contents","Info.plist"),"utf8");return/<key>CFBundleVersion<\/key>\s*<string>(\d+\.\d+\.\d+)<\/string>/.exec(n)?.[1]??null}catch{return null}}function pe(e,t=a()){let n=Gr(t);return n===null||j(N(n.split(".")),N(e.split(/[.-]/).slice(0,3)))}var ge=1e4;function K(e,t){return b(e,[...t],{stdio:"ignore",timeout:ge}).status??1}var W=new Set;function H(e){if(process.env.REASON_TEST_REFUSE_REAL_IDENTITY!=="1")return;let t=(n)=>{try{return T(n)}catch{return ce(n)}};if(e!==void 0&&t(e)!==t(a()))return;throw Error("A test tried to change this computer's real Reason background identity; pass a temporary home. Refused by scripts/test-env.ts.")}var V=/\/(?:runtime|CLI)\/versions\/(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$|\/\.(?:ara|reason)(?:-staging)?-worker-(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$/,J=new Set(["ara","ara.exe","reason","reason.exe"]);function N(e){return e.map((t)=>Number(t))}function j(e,t){for(let n=0;n<3;n+=1)if(e[n]!==t[n])return e[n]<t[n];return!1}var ye=[0,2,161];function me(e){if(e===null)return!0;let t=ye,n=null;try{n=T(process.execPath)}catch{}return e.some((r)=>{let i=V.exec(r);if(i){let f=i[1]===void 0?i.slice(4,7):i.slice(1,4);return j(N(f),t)}let o=r.slice(r.lastIndexOf("/")+1);return J.has(o)&&r!==n&&r!==process.execPath})}function Ee(){let e=b("/bin/ps",["-xo","pid=,comm="],{encoding:"utf8",timeout:5000});if(e.status!==0)return null;let t=[];for(let n of e.stdout.split(`
3
3
  `)){let r=/^\s*(\d+)\s+(\S.*)$/.exec(n);if(!r||Number(r[1])===process.pid)continue;let i=r[2].trimEnd(),o=i.slice(i.lastIndexOf("/")+1);if(!V.test(i)&&J.has(o)){let c=b("/usr/sbin/lsof",["-a","-p",r[1],"-d","txt","-Fn"],{encoding:"utf8",timeout:5000}).stdout?.split(`
4
4
  `).find((l)=>l.startsWith("n/"));if(c)i=c.slice(1)}t.push(i)}return t}function _e(e){if(H(e.home),!d(e.sourceApp))throw new h("identity_invalid","The packaged Reason background identity is missing or invalid.");let t=e.command??K,n=le(e.home),r=I(n);Y(r,{recursive:!0,mode:448}),ee(r,448);let i=T(e.sourceApp),o=null;try{o=T(n)}catch{}if(i!==o){let f=`${process.pid}.${L()}`,c=u(r,`.Reason.app.${f}.tmp`),l=u(r,`.Reason.app.${f}.old`),y=!1;try{if(te(i,c,{recursive:!0,errorOnExist:!0,preserveTimestamps:!0}),!d(c))throw new h("identity_invalid","The copied Reason background identity is invalid.");let _=e.releaseSigned?["--test-requirement",`=${de}`]:[];if(t("/usr/bin/codesign",["--verify","--strict",..._,c])!==0)throw new h("identity_invalid_signature","The installed Reason background identity has an invalid signature.");let S=!1;for(let p=0;p<4;p+=1){let m=!1;try{E(n,l),m=!0,y=!0}catch(s){if(s.code!=="ENOENT")throw s}if(p===0)e.beforePublish?.();try{E(c,n),S=!0}catch(s){let Z=s.code;if(!["EEXIST","ENOTEMPTY"].includes(Z??""))throw s;if(m)g(l,{recursive:!0,force:!0}),y=!1;if(p===3)throw s;continue}if(m)g(l,{recursive:!0,force:!0}),y=!1;break}if(!S)throw Error("Could not publish Reason's background identity.")}catch(_){if(y&&!x(n)&&x(l))E(l,n);throw _}finally{g(c,{recursive:!0,force:!0}),g(l,{recursive:!0,force:!0})}}return z(n,e,{verified:i!==o}),n}function X(e){return u(I(e),".Reason.app.registered")}function q(e){try{let t=A(e);return t.isDirectory()?`${t.ino}:${t.birthtimeMs}`:null}catch{return null}}function C(e){let t=q(e);try{return t!==null&&w(X(e),"utf8")===t}catch{return!1}}function Q(e){if(d(e))return"bundle";try{if(A(u(e,"Contents","Info.plist"),{throwIfNoEntry:!1}))return null;return A(u(e,"Contents","MacOS",v)).isSymbolicLink()?"retired":null}catch{return null}}function z(e,t,n={}){let r=t.command??K;if(!n.verified&&r("/usr/bin/codesign",["--verify","--strict",e])!==0)throw new h("identity_invalid_signature","The installed Reason background identity has an invalid signature.");if(r(R,["-f",e])!==0)throw new h("identity_register_failed","Could not register Reason's macOS background identity.");let i=q(e);try{if(i)oe(X(e),i,{mode:384})}catch{}try{Se(e,t.home,r,t.runningExecutables??Ee)}catch(o){let f=o.code??"unknown";process.stderr.write(`Reason background identity: legacy_identity_retire_failed (${f})
5
- `)}}function Se(e,t,n,r){let i=D(e);if(!i)return;let o=O(t),f=I(o),c=(s)=>u(s,"Contents","MacOS",v),l=se(I(c(o)),i),y=`${process.pid}.${L()}`,_=Q(o);if(_===null)return;let S=_==="bundle";if(S)n(R,["-u",o]);let p=u(f,`.Ara.app.${y}.old`);if(!W.has(o)&&!me(r())){if(!S)n(R,["-u",o]);try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}g(p,{recursive:!0,force:!0}),Ie(f);return}if(!S){if(re(c(o))===l)return;let s=`${c(o)}.${y}`;M(l,s);try{E(s,c(o))}finally{g(s,{force:!0})}return}let m=u(f,`.Ara.app.${y}.shim`);Y(I(c(m)),{recursive:!0}),M(l,c(m));try{try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}try{E(m,o)}catch(s){if(x(o))return;throw E(p,o),s}}finally{g(m,{recursive:!0,force:!0}),g(p,{recursive:!0,force:!0})}}function Ie(e){try{if(ne(e).some((n)=>n!==".DS_Store"))return;g(u(e,".DS_Store"),{force:!0}),ie(e)}catch{}}var B=new Map;function Xn(e=a()){let t=B.get(e);if(t)return t;if(process.platform!=="darwin")return[];let n=U(e);if(n===null&&x(I(le(e))))Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100),n=U(e);if(n===null)return[];return B.set(e,n),n}function U(e){let t=le(e),n=O(e);if(!d(t)||!C(t))try{he({home:e,skipWhenSettled:!0})}catch{}let r=d(t)&&(C(t)||!d(n))?t:d(n)?n:null,i=r?D(r):null;if(!i)return null;if(r===n)W.add(n);let o=b(i,["--can-spawn"],{env:{},timeout:2000,encoding:"utf8"});return o.status===0&&o.stdout===`spawn
6
- `?[i,"--spawn"]:[]}var P=new Map;function mt(e=a()){let t=Xn(e),n=t[0];if(!n)return[];let r=P.get(n);if(r===void 0){let i=b(n,["--can-spawn-computer-use"],{env:{},timeout:2000,encoding:"utf8"});r=i.status===0&&i.stdout===`spawn
7
- `,P.set(n,r)}return r?t:[]}function To(e=mt(),t=a()){if(e.length>0)return null;if(Gr(t)===null)return"computer_use_identity_missing";return pe(Qe,t)?"computer_use_identity_outdated":"computer_use_identity_unavailable"}function he(e={}){H(e.home);let t=le(e.home);if(e.skipWhenSettled&&d(t)&&C(t)&&Q(O(e.home))===null)return!0;if(!d(t)){let n=O(e.home);if(!d(n))return!1;try{return _e({...e,sourceApp:n}),!0}catch(r){if(!d(t))throw r}}return z(t,e),!0}var Yt="REASON_WORKER_IDENTITY_APP";function Ro(e,t=process.env,n=a()){let r=t[Yt];return r&&r===le(n)?r:e}function Oo(e,t){if(process.platform!=="darwin")return null;let n=le(e),r=u(n,"Contents","MacOS",G),i=b(r,["--can-run-worker",t],{env:{},timeout:2000,encoding:"utf8"});return i.status===0&&i.stdout===`run-worker
5
+ `)}}function Se(e,t,n,r){let i=D(e);if(!i)return;let o=O(t),f=I(o),c=(s)=>u(s,"Contents","MacOS",v),l=se(I(c(o)),i),y=`${process.pid}.${L()}`,_=Q(o);if(_===null)return;let S=_==="bundle";if(S)n(R,["-u",o]);let p=u(f,`.Ara.app.${y}.old`);if(!W.has(o)&&!me(r())){if(!S)n(R,["-u",o]);try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}g(p,{recursive:!0,force:!0}),Ie(f);return}if(!S){if(re(c(o))===l)return;let s=`${c(o)}.${y}`;M(l,s);try{E(s,c(o))}finally{g(s,{force:!0})}return}let m=u(f,`.Ara.app.${y}.shim`);Y(I(c(m)),{recursive:!0}),M(l,c(m));try{try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}try{E(m,o)}catch(s){if(x(o))return;throw E(p,o),s}}finally{g(m,{recursive:!0,force:!0}),g(p,{recursive:!0,force:!0})}}function Ie(e){try{if(ne(e).some((n)=>n!==".DS_Store"))return;g(u(e,".DS_Store"),{force:!0}),ie(e)}catch{}}var B=new Map;function Yn(e=a()){let t=B.get(e);if(t)return t;if(process.platform!=="darwin")return[];let n=U(e);if(n===null&&x(I(le(e))))Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100),n=U(e);if(n===null)return[];return B.set(e,n),n}function U(e){let t=le(e),n=O(e);if(!d(t)||!C(t))try{he({home:e,skipWhenSettled:!0})}catch{}let r=d(t)&&(C(t)||!d(n))?t:d(n)?n:null,i=r?D(r):null;if(!i)return null;if(r===n)W.add(n);let o=b(i,["--can-spawn"],{env:{},timeout:2000,encoding:"utf8"});return o.status===0&&o.stdout===`spawn
6
+ `?[i,"--spawn"]:[]}var P=new Map;function mt(e=a()){let t=Yn(e),n=t[0];if(!n)return[];let r=P.get(n);if(r===void 0){let i=b(n,["--can-spawn-computer-use"],{env:{},timeout:2000,encoding:"utf8"});r=i.status===0&&i.stdout===`spawn
7
+ `,P.set(n,r)}return r?t:[]}function Ro(e=mt(),t=a()){if(e.length>0)return null;if(Gr(t)===null)return"computer_use_identity_missing";return pe(Qe,t)?"computer_use_identity_outdated":"computer_use_identity_unavailable"}function he(e={}){H(e.home);let t=le(e.home);if(e.skipWhenSettled&&d(t)&&C(t)&&Q(O(e.home))===null)return!0;if(!d(t)){let n=O(e.home);if(!d(n))return!1;try{return _e({...e,sourceApp:n}),!0}catch(r){if(!d(t))throw r}}return z(t,e),!0}var Yt="REASON_WORKER_IDENTITY_APP";function Oo(e,t=process.env,n=a()){let r=t[Yt];return r&&r===le(n)?r:e}function Io(e,t){if(process.platform!=="darwin")return null;let n=le(e),r=u(n,"Contents","MacOS",G),i=b(r,["--can-run-worker",t],{env:{},timeout:2000,encoding:"utf8"});return i.status===0&&i.stdout===`run-worker
8
8
  `?{app:n,executable:r}:null}
9
- export{Zn,Vr,Po,le,Gr,Xn,mt,To,Yt,Ro,Oo};
9
+ export{Xn,Vr,To,le,Gr,Yn,mt,Ro,Yt,Oo,Io};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{_}from"./vm-hands-entry-lite-hxhd7btg.js";import{Kr,Qn,Jr,ei}from"./vm-hands-entry-lite-pk8fxewf.js";import{Zn,Yt,Oo}from"./vm-hands-entry-lite-ss5n593s.js";import{C}from"./vm-hands-entry-lite-tbawqj1n.js";import{spawnSync as y}from"child_process";import{createHash as ke,randomUUID as Se}from"crypto";import{chmodSync as we,existsSync as P,mkdirSync as $e,readdirSync as Ve,readFileSync as p,renameSync as ye,rmSync as u,statSync as ve,writeFileSync as be}from"fs";import{dirname as We,isAbsolute as q,join as g}from"path";import{spawnSync as de}from"child_process";import{readFileSync as me}from"fs";import{userInfo as D}from"os";import{join as fe}from"path";var ge="REASON_SCHEDULED_TASK";function H(r){return fe(r,"AppData","Local","Reason","Tasks")}function S(r){if(/[\0-\x1f\x7f"%]/.test(r))throw Error(`A background task cannot use a value with a double quote, percent sign or control character: ${r}`);return`'${r.replace(/['\u2018\u2019\u201a\u201b]/g,"$&$&")}'`}function M(r){if(!/^[A-Za-z0-9._-]+$/.test(r))throw Error(`Invalid Windows Scheduled Task name: ${r}`);return`$env:${ge}=${S(r)};`}function K(r){let e=Object.entries(r.environment).map(([t,i])=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw Error(`Invalid Windows Scheduled Task environment name: ${t}`);return`$env:${t}=${S(i)};`}),n=`$global:LASTEXITCODE=1; & ${[r.program,...r.args].map(S).join(" ")} 2>&1 | ForEach-Object { Add-Content -LiteralPath ${S(r.log)} -Value $_.ToString() -Encoding UTF8 }; $c=$LASTEXITCODE;`;return[M(r.name),...e,"$ErrorActionPreference='Continue';",r.keepAlive?`do { ${n} if ($c) { Start-Sleep -Seconds 10 } } while ($c)`:`${n} exit $c`].join(" ")}function A(r){return r.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function pe(){let r=process.env.USERDOMAIN?.trim();return r?`${r}\\${D().username}`:D().username}function U(r){let e=A(r.user??pe()),n=r.schedule==="logon",t=r.schedule==="logon"?`<LogonTrigger><Enabled>true</Enabled><UserId>${e}</UserId></LogonTrigger>`:`<TimeTrigger><Repetition><Interval>PT${r.schedule.everyMinutes}M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition><StartBoundary>2026-01-01T00:00:00</StartBoundary><Enabled>true</Enabled></TimeTrigger>`,i=`-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -Command "${r.script}"`;return`<?xml version="1.0" encoding="UTF-16"?>
2
+ import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{_}from"./vm-hands-entry-lite-nqdstx24.js";import{Kr,ei,Jr,ti}from"./vm-hands-entry-lite-e4c6z5t3.js";import{Xn,Yt,Io}from"./vm-hands-entry-lite-ht7fk059.js";import{C}from"./vm-hands-entry-lite-87vmbt38.js";import{spawnSync as y}from"child_process";import{createHash as ke,randomUUID as Se}from"crypto";import{chmodSync as we,existsSync as P,mkdirSync as $e,readdirSync as Ve,readFileSync as p,renameSync as ye,rmSync as u,statSync as ve,writeFileSync as be}from"fs";import{dirname as We,isAbsolute as q,join as g}from"path";import{spawnSync as de}from"child_process";import{readFileSync as me}from"fs";import{userInfo as D}from"os";import{join as fe}from"path";var ge="REASON_SCHEDULED_TASK";function H(r){return fe(r,"AppData","Local","Reason","Tasks")}function S(r){if(/[\0-\x1f\x7f"%]/.test(r))throw Error(`A background task cannot use a value with a double quote, percent sign or control character: ${r}`);return`'${r.replace(/['\u2018\u2019\u201a\u201b]/g,"$&$&")}'`}function M(r){if(!/^[A-Za-z0-9._-]+$/.test(r))throw Error(`Invalid Windows Scheduled Task name: ${r}`);return`$env:${ge}=${S(r)};`}function K(r){let e=Object.entries(r.environment).map(([t,i])=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw Error(`Invalid Windows Scheduled Task environment name: ${t}`);return`$env:${t}=${S(i)};`}),n=`$global:LASTEXITCODE=1; & ${[r.program,...r.args].map(S).join(" ")} 2>&1 | ForEach-Object { Add-Content -LiteralPath ${S(r.log)} -Value $_.ToString() -Encoding UTF8 }; $c=$LASTEXITCODE;`;return[M(r.name),...e,"$ErrorActionPreference='Continue';",r.keepAlive?`do { ${n} if ($c) { Start-Sleep -Seconds 10 } } while ($c)`:`${n} exit $c`].join(" ")}function A(r){return r.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function pe(){let r=process.env.USERDOMAIN?.trim();return r?`${r}\\${D().username}`:D().username}function U(r){let e=A(r.user??pe()),n=r.schedule==="logon",t=r.schedule==="logon"?`<LogonTrigger><Enabled>true</Enabled><UserId>${e}</UserId></LogonTrigger>`:`<TimeTrigger><Repetition><Interval>PT${r.schedule.everyMinutes}M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition><StartBoundary>2026-01-01T00:00:00</StartBoundary><Enabled>true</Enabled></TimeTrigger>`,i=`-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -Command "${r.script}"`;return`<?xml version="1.0" encoding="UTF-16"?>
3
3
  <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
4
4
  <RegistrationInfo>
5
5
  <Description>${A(r.description)}</Description>
@@ -42,11 +42,11 @@ import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{_}from"./vm-hands-entry-
42
42
  `)}function j(r,e){return["/Create","/TN",r,"/XML",e,"/F"]}function I(r){return["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(r,"utf16le").toString("base64")]}function x(r){return`'*${M(r).replaceAll("'","''")}*'`}function E(r,e){return I(["$all = @(Get-CimInstance Win32_Process)",`$wrappers = @($all | ? { $_.ProcessId -ne $PID -and $_.CommandLine -like ${x(r)} })`,...e.keepWrapper?[]:["foreach ($w in $wrappers) { Stop-Process -Id $w.ProcessId -Force -ErrorAction SilentlyContinue }"],`foreach ($w in $wrappers) { $all | ? { $_.ParentProcessId -eq $w.ProcessId } | % { taskkill.exe /F ${e.tree?"/T ":""}/PID $_.ProcessId | Out-Null } }`].join(`
43
43
  `))}function F(r){return I(["$all = @(Get-CimInstance Win32_Process)",`$wrappers = @($all | ? { $_.ProcessId -ne $PID -and $_.CommandLine -like ${x(r)} })`,"foreach ($w in $wrappers) { if ($all | ? { $_.ParentProcessId -eq $w.ProcessId -and $_.Name -ne 'conhost.exe' }) { 'running'; exit 0 } }","exit 1"].join(`
44
44
  `))}function X(r,e=process.pid){let n=de(C("powershell.exe"),I(["$all = @{}; Get-CimInstance Win32_Process | % { $all[[int]$_.ProcessId] = $_ }",`$p = $all[${Math.trunc(e)}]`,"for ($i = 0; $p -and $i -lt 64; $i++) {",` if ($p.CommandLine -like ${x(r)}) { exit 10 }`," $n = $all[[int]$p.ParentProcessId]"," if (-not $n -or $n.ProcessId -eq $p.ProcessId -or $n.CreationDate -gt $p.CreationDate) { exit 11 }"," $p = $n","}","exit 11"].join(`
45
- `)),{stdio:"ignore",timeout:15000,windowsHide:!0});return n.status===10?!0:n.status===11?!1:null}var qr="REASON_WORKER_SERVICE",Ae="worker_identity_unavailable";function xe(r){return{platform:process.platform,home:r,uid:process.getuid?.(),command:(e,n)=>y(C(e),[...n],{stdio:"ignore"}).status??1,read:(e,n)=>{let t=y(C(e),[...n],{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4});return t.status===0?t.stdout:null},sleep:(e)=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e),workerIdentity:(e)=>Oo(r,e),insideService:(e,n)=>Ie(e,process.platform,process.getuid?.(),n)}}function Ie(r,e,n,t=!0){if(process.env[qr]===r||process.env.XPC_SERVICE_NAME===r)return!0;if(e==="linux")try{return p("/proc/self/cgroup","utf8").includes(`/${r}.service`)}catch{return!0}if(e==="win32")return X(r)??t;if(e!=="darwin")return!1;if(typeof n!=="number")return!0;let i=y("/bin/launchctl",["print",`gui/${n}/${r}`],{encoding:"utf8",timeout:5000});if(i.status===Ee)return!1;if(i.error||i.status!==0)return!0;let s=Number(/^\s*pid = (\d+)$/m.exec(i.stdout??"")?.[1]??0);if(!s)return!1;let a=process.pid;for(let o=0;o<64&&a>1;o+=1){if(a===s)return!0;let l=y("/bin/ps",["-o","ppid=","-p",String(a)],{encoding:"utf8",timeout:5000}),c=Number(l.stdout?.trim());if(l.error||l.status!==0||!Number.isSafeInteger(c)||c<=0)return!0;if(c===a)return!1;a=c}return a>1}var Ee=113;class J extends Error{code;constructor(r,e){super(r);this.code=e}}function Kn(r,e){if(!re(r.home,r.platform))throw new J(ee);if(r.platform==="darwin")k(r);let n=ei(Kr(e,r.home)),t=_({env:e})==="staging",i=t?"ara-staging":"ara",s=[n?Qn(n):null,T(e,"REASON_CLI_LAUNCHER_PATH")?.trim(),r.platform==="win32"?g(r.home,"AppData","Local","Reason",...t?["staging"]:[],"bin",t?"reason-staging.exe":"reason.exe"):g(r.home,".local","bin",i)];for(let a of s)try{if(a&&q(a)&&ve(a).isFile())return Jr(a)}catch{}throw new J(`A background service runs the installed Reason launcher, which was not found. Install Reason with: ${r.platform==="win32"?"irm https://reasonmachines.com/install.ps1 | iex":"curl -fsSL https://reasonmachines.com/install | sh"}`,"worker_launcher_missing")}var R=/(<key>ProgramArguments<\/key>\s*<array>\n)((?:\s*<string>[^<]*<\/string>\n)*)(\s*<\/array>)/,w=new RegExp(`(\\n\\s*<key>${Yt}</key>\\s*<string>)[^<]*(</string>)`),_e=/(<key>EnvironmentVariables<\/key>\s*<dict>[\s\S]*?)(\n\s*<\/dict>)/;function Te(r){return r.replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&amp;","&")}function Y(r){let e=[...(R.exec(r)?.[2]??"").matchAll(/<string>([^<]*)<\/string>/g)].map((t)=>Te(t[1])),n=e[1]==="--run-worker"?e.slice(2):e;return n[0]?{launcher:n[0],args:n.slice(1)}:null}function z(r,e,n){let t=n.workerIdentity?.(r)??null;return{program:t?[t.executable,"--run-worker",r,...e]:[r,...e],identity:t}}function h(r){return r.map((e)=>` <string>${d(e)}</string>`).join(`
45
+ `)),{stdio:"ignore",timeout:15000,windowsHide:!0});return n.status===10?!0:n.status===11?!1:null}var qr="REASON_WORKER_SERVICE",Ae="worker_identity_unavailable";function xe(r){return{platform:process.platform,home:r,uid:process.getuid?.(),command:(e,n)=>y(C(e),[...n],{stdio:"ignore"}).status??1,read:(e,n)=>{let t=y(C(e),[...n],{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4});return t.status===0?t.stdout:null},sleep:(e)=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e),workerIdentity:(e)=>Io(r,e),insideService:(e,n)=>Ie(e,process.platform,process.getuid?.(),n)}}function Ie(r,e,n,t=!0){if(process.env[qr]===r||process.env.XPC_SERVICE_NAME===r)return!0;if(e==="linux")try{return p("/proc/self/cgroup","utf8").includes(`/${r}.service`)}catch{return!0}if(e==="win32")return X(r)??t;if(e!=="darwin")return!1;if(typeof n!=="number")return!0;let i=y("/bin/launchctl",["print",`gui/${n}/${r}`],{encoding:"utf8",timeout:5000});if(i.status===Ee)return!1;if(i.error||i.status!==0)return!0;let s=Number(/^\s*pid = (\d+)$/m.exec(i.stdout??"")?.[1]??0);if(!s)return!1;let a=process.pid;for(let o=0;o<64&&a>1;o+=1){if(a===s)return!0;let l=y("/bin/ps",["-o","ppid=","-p",String(a)],{encoding:"utf8",timeout:5000}),c=Number(l.stdout?.trim());if(l.error||l.status!==0||!Number.isSafeInteger(c)||c<=0)return!0;if(c===a)return!1;a=c}return a>1}var Ee=113;class J extends Error{code;constructor(r,e){super(r);this.code=e}}function Jn(r,e){if(!re(r.home,r.platform))throw new J(ee);if(r.platform==="darwin")k(r);let n=ti(Kr(e,r.home)),t=_({env:e})==="staging",i=t?"ara-staging":"ara",s=[n?ei(n):null,T(e,"REASON_CLI_LAUNCHER_PATH")?.trim(),r.platform==="win32"?g(r.home,"AppData","Local","Reason",...t?["staging"]:[],"bin",t?"reason-staging.exe":"reason.exe"):g(r.home,".local","bin",i)];for(let a of s)try{if(a&&q(a)&&ve(a).isFile())return Jr(a)}catch{}throw new J(`A background service runs the installed Reason launcher, which was not found. Install Reason with: ${r.platform==="win32"?"irm https://reasonmachines.com/install.ps1 | iex":"curl -fsSL https://reasonmachines.com/install | sh"}`,"worker_launcher_missing")}var R=/(<key>ProgramArguments<\/key>\s*<array>\n)((?:\s*<string>[^<]*<\/string>\n)*)(\s*<\/array>)/,w=new RegExp(`(\\n\\s*<key>${Yt}</key>\\s*<string>)[^<]*(</string>)`),_e=/(<key>EnvironmentVariables<\/key>\s*<dict>[\s\S]*?)(\n\s*<\/dict>)/;function Te(r){return r.replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&amp;","&")}function Y(r){let e=[...(R.exec(r)?.[2]??"").matchAll(/<string>([^<]*)<\/string>/g)].map((t)=>Te(t[1])),n=e[1]==="--run-worker"?e.slice(2):e;return n[0]?{launcher:n[0],args:n.slice(1)}:null}function z(r,e,n){let t=n.workerIdentity?.(r)??null;return{program:t?[t.executable,"--run-worker",r,...e]:[r,...e],identity:t}}function h(r){return r.map((e)=>` <string>${d(e)}</string>`).join(`
46
46
  `)}function Z(r,e){let n;try{n=p(r,"utf8")}catch{return null}let t=Y(n);if(!t)return null;let i=q(t.launcher)?Jr(t.launcher):t.launcher,{program:s,identity:a}=z(i,t.args,e),o=n.replace(R,(l,c,m,O)=>`${c}${h(s)}
47
47
  ${O}`);if(!a)o=o.replace(w,"");else if(w.test(o))o=o.replace(w,(l,c,m)=>`${c}${d(a.app)}${m}`);else o=o.replace(_e,(l,c,m)=>`${c}
48
48
  <key>${Yt}</key>
49
- <string>${d(a.app)}</string>${m}`);return o===n?null:o}function Pe(r,e){let n=Z(r,e);if(n!==null)W(r,n)}function Fs(r,e,n){if(e.platform!=="darwin")return!1;let t=Ye(r,e,n);return t!==null&&Z(t.definition,e)!==null}var b="com.reasonmachines.worker.",N="so.reason.worker.",Q=[b,N];function Co(r,e=b){return`${e}connect${r==="production"?"":`.${r}`}`}function js(r,e){return Q.some((n)=>r===Co(e,n))}function Re(r,e,n){if(e==="connect")return Co(r.channel,n);let t=ke("sha256").update(r.workspaceRoot).digest("hex").slice(0,8);return`${n}${r.name.toLowerCase()}.${t}`}var ee="A background service needs macOS (launchd), Linux (systemd --user) or Windows (Task Scheduler).";function re(r,e){if(e==="darwin")return{directory:g(r,"Library","LaunchAgents"),suffix:".plist"};if(e==="linux")return{directory:g(r,".config","systemd","user"),suffix:".service"};if(e==="win32")return{directory:H(r),suffix:".xml"};return null}function f(r,e,n,t=b){let i=Re(r,n,t),s=re(e.home,e.platform);if(!s)return null;return{label:i,definition:g(s.directory,`${i}${s.suffix}`),logs:e.platform==="linux"?`journalctl --user -u ${i}.service`:g(r.stateDirectory,"service.log")}}function Ye(r,e,n="serve"){return ne(r,e,n)[0]??null}function ne(r,e,n){return Q.map((t)=>f(r,e,n,t)).filter((t)=>t!==null&&P(t.definition))}function te(r,e,n){let t=f(r,e,n,N);return t&&P(t.definition)?t:null}function rs(r,e,n){let t=f(r,e,n),i=te(r,e,n);if(!t||!i||!P(t.definition)||e.insideService?.(i.label))return null;if(!Ce(t,e))return"current_not_running";if(e.platform==="darwin"){if(typeof e.uid==="number"&&e.uid>0)e.command("/bin/launchctl",["bootout",`gui/${e.uid}/${i.label}`]);return u(i.definition,{force:!0}),"retired"}if(e.platform==="win32")return v(i,e,!0),"retired";return e.command("systemctl",["--user","disable","--now",`${i.label}.service`]),u(i.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"]),"retired"}function Ce(r,e){if(e.platform==="darwin")return typeof e.uid==="number"&&e.uid>0&&e.command("/bin/launchctl",["print",`gui/${e.uid}/${r.label}`])===0;if(e.platform==="win32")return e.command("schtasks",["/Query","/TN",r.label])===0;let n=`${r.label}.service`;return e.command("systemctl",["--user","is-enabled","--quiet",n])===0&&he.has(e.read("systemctl",["--user","show","--property=ActiveState","--value",n])?.trim()??"")}var he=new Set(["active","activating","reloading"]);function Jn(r,e){if(e.platform==="darwin"){if(typeof e.uid!=="number"||e.uid<=0)return!1;let n=e.read("/bin/launchctl",["print",`gui/${e.uid}/${r.label}`]);return Number(/^\s*pid = (\d+)$/m.exec(n??"")?.[1]??0)>0}if(e.platform==="win32")return e.read("powershell.exe",F(r.label))?.trim()==="running";return Number(e.read("systemctl",["--user","show","--property=MainPID","--value",`${r.label}.service`])?.trim()??0)>0}function Us(r){let{config:e,launcher:n,host:t,kind:i}=r,s=f(e,t,i);if(!s)return!1;let a;try{a=t.platform==="win32"?V(s.definition):p(s.definition,"utf8")}catch{return!1}if(t.platform==="win32")return a===se(e,i,s,n);if(t.platform!=="darwin")return a===oe(e,i,s,n,t.home,r.path);let o=Y(a);return a.replace(w,"").replace(R,(c,m,O,ue)=>`${m}${o?`${h([o.launcher,...o.args])}
49
+ <string>${d(a.app)}</string>${m}`);return o===n?null:o}function Pe(r,e){let n=Z(r,e);if(n!==null)W(r,n)}function js(r,e,n){if(e.platform!=="darwin")return!1;let t=Ye(r,e,n);return t!==null&&Z(t.definition,e)!==null}var b="com.reasonmachines.worker.",N="so.reason.worker.",Q=[b,N];function Ao(r,e=b){return`${e}connect${r==="production"?"":`.${r}`}`}function Us(r,e){return Q.some((n)=>r===Ao(e,n))}function Re(r,e,n){if(e==="connect")return Ao(r.channel,n);let t=ke("sha256").update(r.workspaceRoot).digest("hex").slice(0,8);return`${n}${r.name.toLowerCase()}.${t}`}var ee="A background service needs macOS (launchd), Linux (systemd --user) or Windows (Task Scheduler).";function re(r,e){if(e==="darwin")return{directory:g(r,"Library","LaunchAgents"),suffix:".plist"};if(e==="linux")return{directory:g(r,".config","systemd","user"),suffix:".service"};if(e==="win32")return{directory:H(r),suffix:".xml"};return null}function f(r,e,n,t=b){let i=Re(r,n,t),s=re(e.home,e.platform);if(!s)return null;return{label:i,definition:g(s.directory,`${i}${s.suffix}`),logs:e.platform==="linux"?`journalctl --user -u ${i}.service`:g(r.stateDirectory,"service.log")}}function Ye(r,e,n="serve"){return ne(r,e,n)[0]??null}function ne(r,e,n){return Q.map((t)=>f(r,e,n,t)).filter((t)=>t!==null&&P(t.definition))}function te(r,e,n){let t=f(r,e,n,N);return t&&P(t.definition)?t:null}function ns(r,e,n){let t=f(r,e,n),i=te(r,e,n);if(!t||!i||!P(t.definition)||e.insideService?.(i.label))return null;if(!Ce(t,e))return"current_not_running";if(e.platform==="darwin"){if(typeof e.uid==="number"&&e.uid>0)e.command("/bin/launchctl",["bootout",`gui/${e.uid}/${i.label}`]);return u(i.definition,{force:!0}),"retired"}if(e.platform==="win32")return v(i,e,!0),"retired";return e.command("systemctl",["--user","disable","--now",`${i.label}.service`]),u(i.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"]),"retired"}function Ce(r,e){if(e.platform==="darwin")return typeof e.uid==="number"&&e.uid>0&&e.command("/bin/launchctl",["print",`gui/${e.uid}/${r.label}`])===0;if(e.platform==="win32")return e.command("schtasks",["/Query","/TN",r.label])===0;let n=`${r.label}.service`;return e.command("systemctl",["--user","is-enabled","--quiet",n])===0&&he.has(e.read("systemctl",["--user","show","--property=ActiveState","--value",n])?.trim()??"")}var he=new Set(["active","activating","reloading"]);function Zn(r,e){if(e.platform==="darwin"){if(typeof e.uid!=="number"||e.uid<=0)return!1;let n=e.read("/bin/launchctl",["print",`gui/${e.uid}/${r.label}`]);return Number(/^\s*pid = (\d+)$/m.exec(n??"")?.[1]??0)>0}if(e.platform==="win32")return e.read("powershell.exe",F(r.label))?.trim()==="running";return Number(e.read("systemctl",["--user","show","--property=MainPID","--value",`${r.label}.service`])?.trim()??0)>0}function Hs(r){let{config:e,launcher:n,host:t,kind:i}=r,s=f(e,t,i);if(!s)return!1;let a;try{a=t.platform==="win32"?V(s.definition):p(s.definition,"utf8")}catch{return!1}if(t.platform==="win32")return a===se(e,i,s,n);if(t.platform!=="darwin")return a===oe(e,i,s,n,t.home,r.path);let o=Y(a);return a.replace(w,"").replace(R,(c,m,O,ue)=>`${m}${o?`${h([o.launcher,...o.args])}
50
50
  `:""}${ue}`)===ie(e,i,s,n,{...t,workerIdentity:()=>null},r.path).plist}function L(r,e){if(e==="connect")return{args:["connect"],environment:{REASON_CLI_CHANNEL:r.channel},description:"Reason connection of this computer"};return{args:["serve",r.name,"--dir",r.workspaceRoot,...r.executionMode==="confined"?["--sandbox"]:[]],environment:{},description:`Reason machine ${r.name} worker`}}function d(r){return r.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function G(r,e=!1){if(/[\0-\x1f\x7f]/.test(r))throw new J("A background service cannot use a path with control characters.");let n=r.replaceAll("\\","\\\\").replaceAll('"',"\\\"").replaceAll("%","%%");return`"${e?n.replaceAll("$","$$$$"):n}"`}function ie(r,e,n,t,i,s){let a=L(r,e),o=z(t,a.args,i),l={HOME:i.home,PATH:s,[qr]:n.label,...a.environment,...o.identity?{[Yt]:o.identity.app}:{}};return{identity:o.identity,plist:`<?xml version="1.0" encoding="UTF-8"?>
51
51
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
52
52
  <plist version="1.0">
@@ -55,7 +55,7 @@ ${O}`);if(!a)o=o.replace(w,"");else if(w.test(o))o=o.replace(w,(l,c,m)=>`${c}${d
55
55
  <string>${d(n.label)}</string>
56
56
  <key>AssociatedBundleIdentifiers</key>
57
57
  <array>
58
- <string>${Zn}</string>
58
+ <string>${Xn}</string>
59
59
  </array>
60
60
  <key>ProgramArguments</key>
61
61
  <array>
@@ -101,5 +101,5 @@ UMask=0077
101
101
 
102
102
  [Install]
103
103
  WantedBy=default.target
104
- `}function se(r,e,n,t){let i=L(r,e);return U({description:i.description,schedule:"logon",script:K({name:n.label,program:t,args:i.args,environment:{[qr]:n.label,...i.environment},log:n.logs,keepAlive:!0})})}function ae(r,e,n){e.command("powershell.exe",E(r.label,{tree:n,keepWrapper:!n}))}function v(r,e,n){e.command("schtasks",["/Delete","/F","/TN",r.label]),e.command("powershell.exe",E(r.label,{tree:n,keepWrapper:!1})),u(r.definition,{force:!0})}function W(r,e){$e(We(r),{recursive:!0,mode:448});let n=`${r}.${Se()}.tmp`;try{be(n,e,{mode:384,flag:"wx"}),we(n,384),ye(n,r)}finally{u(n,{force:!0})}}function k(r){if(typeof r.uid!=="number"||!Number.isSafeInteger(r.uid)||r.uid<=0)throw new J("Set up a background service as your own user, not with sudo.","worker_service_root_user");return`gui/${r.uid}`}function Hs(r){let{config:e,launcher:n,host:t}=r,i=r.kind??"serve",s=te(e,t,i),a=s!==null&&t.insideService?.(s.label)===!0,o=f(e,t,i,a?N:b);if(!o)throw new J(ee);if(t.platform==="darwin")k(t);if(t.platform==="linux"&&t.command("systemctl",["--user","show-environment"])!==0)throw new J("No background service here: this computer has no systemd user session.","worker_service_manager_missing");let l=t.platform==="darwin"?ie(e,i,o,n,t,r.path):null;if(W(o.definition,l?l.plist:t.platform==="win32"?B(se(e,i,o,n)):oe(e,i,o,n,t.home,r.path)),le(e,t,o,a?null:s),l)return l.identity?o:{...o,identityProblem:Ae};if(t.platform==="win32")return o;return{...o,lingering:t.command("loginctl",["enable-linger"])===0}}function le(r,e,n,t){if(e.platform==="darwin"){let a=k(e);if(t)e.command("/bin/launchctl",["bootout",`${a}/${t.label}`]);if(ce(r,n,e)){if(t)u(t.definition,{force:!0});return}if(u(n.definition,{force:!0}),t)e.command("/bin/launchctl",["bootstrap",a,t.definition]);throw new J("Could not start the background service (launchctl bootstrap failed).","worker_service_start_failed")}if(e.platform==="win32"){if(t)v(t,e,!0);if(e.command("schtasks",j(n.label,n.definition))===0){if(ae(n,e,e.insideService?.(n.label)!==!0),e.command("schtasks",["/Run","/TN",n.label])===0)return}throw v(n,e,!0),new J("Could not start the background service (schtasks failed).")}let i=`${n.label}.service`,s=t?`${t.label}.service`:null;if(e.command("systemctl",["--user","daemon-reload"])!==0||s!==null&&e.command("systemctl",["--user","disable","--now",s])!==0||e.command("systemctl",["--user","enable",i])!==0||e.command("systemctl",["--user","restart",i])!==0){if(e.command("systemctl",["--user","disable",i]),u(n.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"]),s)e.command("systemctl",["--user","enable","--now",s]);throw new J("Could not start the background service (systemctl --user failed).","worker_service_start_failed")}if(t)u(t.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"])}function ce(r,e,n){let t=k(n);n.command("/bin/launchctl",["bootout",`${t}/${e.label}`]);let i=(Math.ceil(r.shutdownGraceMs/1000)+10)*1000;for(let s=0,a=100;;a=Math.min(a*2,2000)){if(n.command("/bin/launchctl",["bootstrap",t,e.definition])===0)return!0;if(s>=i)return!1;n.sleep(a),s+=a}}function Wr(r,e,n){let t=Ye(r,e,n);if(!t)return null;let i=e.insideService?.(t.label)===!0;if(e.platform==="darwin"&&!i)Pe(t.definition,e);let s=f(r,e,n);if(s&&t.label!==s.label&&!i)return W(s.definition,p(t.definition,"utf8").replaceAll(t.label,s.label)),le(r,e,s,t),s;let a=e.platform==="darwin"&&i,o;if(e.platform==="win32")ae(t,e,!i),o=e.command("schtasks",["/Run","/TN",t.label])===0;else if(a)o=e.command("/bin/launchctl",["kickstart","-k",`${k(e)}/${t.label}`])===0;else if(e.platform==="darwin")o=ce(r,t,e);else e.command("systemctl",["--user","enable",`${t.label}.service`]),o=e.command("systemctl",["--user","restart",`${t.label}.service`])===0;if(!o)throw new J(`Could not restart the background service ${t.label}.`,"worker_service_restart_failed");if(s&&t.label===s.label)rs(r,e,n);return t}function zs(r,e,n,t){let i=Ye(r,n,t),s=f(e,n,t);if(n.platform!=="darwin"||!i||!s)return;let a=`<string>${d(i.logs)}</string>`,o=p(i.definition,"utf8");if(o.includes(a))W(i.definition,o.replaceAll(a,`<string>${d(s.logs)}</string>`))}function qs(r,e,n="serve"){let t=ne(r,e,n);for(let i of t){if(e.platform==="win32"){v(i,e,e.insideService?.(i.label,!1)!==!0);continue}if(e.platform==="darwin"){if(typeof e.uid==="number"&&e.uid>0)e.command("/bin/launchctl",["bootout",`gui/${e.uid}/${i.label}`]);u(i.definition,{force:!0});continue}e.command("systemctl",["--user","disable","--now",`${i.label}.service`]),u(i.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"])}return t[0]??null}
105
- export{qr,xe,J,Kn,Fs,Co,js,Ye,rs,Jn,Us,Hs,Wr,zs,qs};
104
+ `}function se(r,e,n,t){let i=L(r,e);return U({description:i.description,schedule:"logon",script:K({name:n.label,program:t,args:i.args,environment:{[qr]:n.label,...i.environment},log:n.logs,keepAlive:!0})})}function ae(r,e,n){e.command("powershell.exe",E(r.label,{tree:n,keepWrapper:!n}))}function v(r,e,n){e.command("schtasks",["/Delete","/F","/TN",r.label]),e.command("powershell.exe",E(r.label,{tree:n,keepWrapper:!1})),u(r.definition,{force:!0})}function W(r,e){$e(We(r),{recursive:!0,mode:448});let n=`${r}.${Se()}.tmp`;try{be(n,e,{mode:384,flag:"wx"}),we(n,384),ye(n,r)}finally{u(n,{force:!0})}}function k(r){if(typeof r.uid!=="number"||!Number.isSafeInteger(r.uid)||r.uid<=0)throw new J("Set up a background service as your own user, not with sudo.","worker_service_root_user");return`gui/${r.uid}`}function zs(r){let{config:e,launcher:n,host:t}=r,i=r.kind??"serve",s=te(e,t,i),a=s!==null&&t.insideService?.(s.label)===!0,o=f(e,t,i,a?N:b);if(!o)throw new J(ee);if(t.platform==="darwin")k(t);if(t.platform==="linux"&&t.command("systemctl",["--user","show-environment"])!==0)throw new J("No background service here: this computer has no systemd user session.","worker_service_manager_missing");let l=t.platform==="darwin"?ie(e,i,o,n,t,r.path):null;if(W(o.definition,l?l.plist:t.platform==="win32"?B(se(e,i,o,n)):oe(e,i,o,n,t.home,r.path)),le(e,t,o,a?null:s),l)return l.identity?o:{...o,identityProblem:Ae};if(t.platform==="win32")return o;return{...o,lingering:t.command("loginctl",["enable-linger"])===0}}function le(r,e,n,t){if(e.platform==="darwin"){let a=k(e);if(t)e.command("/bin/launchctl",["bootout",`${a}/${t.label}`]);if(ce(r,n,e)){if(t)u(t.definition,{force:!0});return}if(u(n.definition,{force:!0}),t)e.command("/bin/launchctl",["bootstrap",a,t.definition]);throw new J("Could not start the background service (launchctl bootstrap failed).","worker_service_start_failed")}if(e.platform==="win32"){if(t)v(t,e,!0);if(e.command("schtasks",j(n.label,n.definition))===0){if(ae(n,e,e.insideService?.(n.label)!==!0),e.command("schtasks",["/Run","/TN",n.label])===0)return}throw v(n,e,!0),new J("Could not start the background service (schtasks failed).")}let i=`${n.label}.service`,s=t?`${t.label}.service`:null;if(e.command("systemctl",["--user","daemon-reload"])!==0||s!==null&&e.command("systemctl",["--user","disable","--now",s])!==0||e.command("systemctl",["--user","enable",i])!==0||e.command("systemctl",["--user","restart",i])!==0){if(e.command("systemctl",["--user","disable",i]),u(n.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"]),s)e.command("systemctl",["--user","enable","--now",s]);throw new J("Could not start the background service (systemctl --user failed).","worker_service_start_failed")}if(t)u(t.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"])}function ce(r,e,n){let t=k(n);n.command("/bin/launchctl",["bootout",`${t}/${e.label}`]);let i=(Math.ceil(r.shutdownGraceMs/1000)+10)*1000;for(let s=0,a=100;;a=Math.min(a*2,2000)){if(n.command("/bin/launchctl",["bootstrap",t,e.definition])===0)return!0;if(s>=i)return!1;n.sleep(a),s+=a}}function Wr(r,e,n){let t=Ye(r,e,n);if(!t)return null;let i=e.insideService?.(t.label)===!0;if(e.platform==="darwin"&&!i)Pe(t.definition,e);let s=f(r,e,n);if(s&&t.label!==s.label&&!i)return W(s.definition,p(t.definition,"utf8").replaceAll(t.label,s.label)),le(r,e,s,t),s;let a=e.platform==="darwin"&&i,o;if(e.platform==="win32")ae(t,e,!i),o=e.command("schtasks",["/Run","/TN",t.label])===0;else if(a)o=e.command("/bin/launchctl",["kickstart","-k",`${k(e)}/${t.label}`])===0;else if(e.platform==="darwin")o=ce(r,t,e);else e.command("systemctl",["--user","enable",`${t.label}.service`]),o=e.command("systemctl",["--user","restart",`${t.label}.service`])===0;if(!o)throw new J(`Could not restart the background service ${t.label}.`,"worker_service_restart_failed");if(s&&t.label===s.label)ns(r,e,n);return t}function qs(r,e,n,t){let i=Ye(r,n,t),s=f(e,n,t);if(n.platform!=="darwin"||!i||!s)return;let a=`<string>${d(i.logs)}</string>`,o=p(i.definition,"utf8");if(o.includes(a))W(i.definition,o.replaceAll(a,`<string>${d(s.logs)}</string>`))}function Ws(r,e,n="serve"){let t=ne(r,e,n);for(let i of t){if(e.platform==="win32"){v(i,e,e.insideService?.(i.label,!1)!==!0);continue}if(e.platform==="darwin"){if(typeof e.uid==="number"&&e.uid>0)e.command("/bin/launchctl",["bootout",`gui/${e.uid}/${i.label}`]);u(i.definition,{force:!0});continue}e.command("systemctl",["--user","disable","--now",`${i.label}.service`]),u(i.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"])}return t[0]??null}
105
+ export{qr,xe,J,Jn,js,Ao,Us,Ye,ns,Zn,Hs,zs,Wr,qs,Ws};
@@ -0,0 +1,52 @@
1
+ // @bun
2
+ import{_,No,ke}from"./vm-hands-entry-lite-nqdstx24.js";import{l,Wt,Ke,Nr,Vt,Mr,pt}from"./vm-hands-entry-lite-gc7550c0.js";import{wt,or}from"./vm-hands-entry-lite-9wa2y4x0.js";import{dn}from"./vm-hands-entry-lite-sqqw5ftm.js";import{B,m,te,Ue}from"./vm-hands-entry-lite-7yyx4qf9.js";import{F}from"./vm-hands-entry-lite-4egbv7sp.js";import{Oo}from"./vm-hands-entry-lite-ht7fk059.js";import{xe,Ye,Zn,Wr}from"./vm-hands-entry-lite-jc8dwrgp.js";import{f,v,h}from"./vm-hands-entry-lite-f69t48dj.js";import{a}from"./vm-hands-entry-lite-swrymqj9.js";import{Uo,nn,y,t,k,Et,o,d,Oe,u,i,c,g,as,s,n,on}from"./vm-hands-entry-lite-a1xa7s06.js";import{closeSync as Uh,existsSync as Fh,mkdirSync as jh,openSync as qh,readdirSync as zh,realpathSync as pe,rmSync as Kh}from"fs";import{dirname as Jh,join as J,resolve as Gh}from"path";import{createHash as It}from"crypto";import{platform as Ot}from"os";import{join as Tt}from"path";var Mt=g("store",[c({version:n(1),store:n("keychain")}),c({version:n(1),store:n("file"),api_key:t().min(1).max(4096)})]),We=(e)=>Tt(e,"api-key.json");function Ne(e){let r=It("sha256").update(`reason-connect-api-key
3
+ ${e}`).digest("hex");return new Ke(Wt(),Ot(),r)}function we(e,r=Ne(e)){if(!f(We(e)))return null;let p=Mt.parse(JSON.parse(h(We(e))));if(p.store==="file")return p.api_key;try{let b=r.loadBinding();return b?new TextDecoder().decode(b):null}catch(b){if(!(b instanceof l))throw b;throw Error("worker_api_key_unreadable")}}import{readdirSync as Zt,renameSync as Go,rmSync as Yo}from"fs";import{join as ee}from"path";import{createHash as Nt}from"crypto";import{platform as Ht}from"os";import{join as N}from"path";function w(e){return{state:N(m(e),"device.json"),control:N(m(e),"control.json"),lock:N(m(e),"lifecycle.lock"),socket:N(m(e),"control.sock"),daemon:N(m(e),"daemon.json"),releaseCheck:N(m(e),"release-check.json"),updateDeferral:N(m(e),"update-deferral.json"),firstHeartbeat:N(m(e),"first-heartbeat.json")}}var lo=i({version:n(1),device_id:t().min(1).max(160),offer:Oe().optional(),enrollment_ms:o().int().nonnegative().max(or).optional()});function z(e,r=!1){v(m(e),r);let p=["local-device.key","local-device.binding","device.json"].filter((b)=>{let R=N(m(e),b);if(!f(R))return!1;return h(R),!0});return e.lifetime==="persistent"&&p.join()==="device.json"?$t(e):new Nr(m(e))}function $t(e){return new Ke(Wt(),Ht(),Bt(e))}function Bt(e){let r=jt(e);return Nt("sha256").update(`reason-worker
4
+ ${r?.directory??m(e)}`).digest("hex")}var Ut="keychain-scope.json";var Ft=c({version:n(1),directory:t().min(1),devicePublicKey:t().min(1)});function jt(e){let r=N(m(e),Ut);if(!f(r))return null;let p=Ft.safeParse(JSON.parse(h(r))),b=w(e).state;if(!p.success||!f(b))return null;return JSON.parse(h(b))?.devicePublicKey===p.data.devicePublicKey?p.data:null}function M(e){if(!f(m(e)))return null;let r=Mr(w(e).state,{proofStore:z(e),repair:!1}),p=r!==null&&No(e.apiOrigin,r.apiOrigin),b=p?[te(e),te({...e,apiOrigin:r.apiOrigin})]:[te(e)];if(r&&(!b.includes(r.worker?.configDigest??"")||r.worker.lifetime!==e.lifetime||r.apiOrigin!==e.apiOrigin&&!p||r.roots.length>32||r.roots[0]?.path!==e.workspaceRoot||r.handsSlots!==e.slots))throw Error("worker_config_binding_mismatch");return r}var qt=c({version:n(1),drained:d(),revoked:d()});function H(e){let r=w(e).control;return f(r)?qt.parse(JSON.parse(h(r))):{version:1,drained:!1,revoked:!1}}var Kt=c({read:d(),write:d(),execute:d(),discover_environment:d(),expose_mcp:n(!1)}),Jt=c({version:n(1),organization_id:t().min(1).max(160),enrollment_ticket:t().min(1).max(4096),code_verifier:t().regex(/^[A-Za-z0-9._~-]{43,128}$/),root_fingerprint_key:t().regex(/^[a-f0-9]{64}$/),root:c({path_fingerprint:t().regex(/^[a-f0-9]{64}$/),permissions:Kt,execution_mode:s(["confined","host"]).default("confined")}),folders:u(c({path_fingerprint:t().regex(/^[a-f0-9]{64}$/)})).min(1).max(31).optional()}),So=i({device_id:t().min(1).max(160),organization_id:t().min(1).max(160),auth_scheme:n("p256"),protocol_version:n(2),roots:u(i({id:t().min(1),label:t(),path_fingerprint:t()})).min(1).max(32),headless:i({lifecycle:s(["persistent","ephemeral"]),expires_at:y.datetime({offset:!0})}),first_heartbeat:Oe().optional()});var qo=c({version:n(1),install_id:k(),fingerprint_key:t().regex(/^[a-f0-9]{64}$/)}),zo=i({enrollment_ticket:t().min(1).max(4096),expires_at:y.datetime({offset:!0}),device_kind:n("headless"),lifecycle:s(["persistent","ephemeral"]),device_expires_at:y.datetime({offset:!0})});var Ko=i({credentialKind:s(["oauth","api_key"]).optional(),apiOrigin:Et(),clientId:t(),accessToken:t().min(1).max(32768),refreshToken:t().max(32768),expiresAt:y.datetime({offset:!0}),scopes:u(t().max(128)).max(128),orgId:t().min(1).max(160)});var je=8;var Qt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,_e=(e)=>ee(m(e),"workspaces"),er="account.json",tr=(e)=>f(ee(e,er));function Se(e){let r;try{r=Zt(_e(e))}catch{return[]}return r.filter((p)=>Qt.test(p)).sort().map((p)=>{let b=ee(_e(e),p),R=ee(b,"worker.json"),S=null;try{let P=B.safeParse(JSON.parse(h(R)));if(P.success&&P.data.stateDirectory===b)S=P.data}catch{}return{organizationId:p,directory:b,configPath:R,config:S,account:tr(b)}})}var rr=(e)=>ee(_e(e),"listed.json");function nr(e){try{let r=JSON.parse(h(rr(e))),p=r.names&&typeof r.names==="object"&&!Array.isArray(r.names)?Object.fromEntries(Object.entries(r.names).filter((R)=>typeof R[1]==="string")):{},b=r.refused&&typeof r.refused==="object"?r.refused:null;return{listed:r.listed===!0,reason:r.reason==="sign_in"?"sign_in":null,blocked:Array.isArray(r.blocked)?r.blocked.filter((R)=>typeof R==="string"):[],names:p,...b&&typeof b.device==="string"&&typeof b.roots==="string"&&typeof b.at==="number"&&Number.isFinite(b.at)&&typeof b.count==="number"&&Number.isInteger(b.count)&&b.count>=1?{refused:{device:b.device,roots:b.roots,at:b.at,count:b.count}}:{}}}catch{return null}}function qe(e,r){let p=Se(e),b=p.filter((C)=>C.account),R=p.filter((C)=>!C.account),S=nr(e),P=S&&!S.listed?S.reason:null,E=P||R.length===0&&S&&!S.listed?[]:R;if(b.length===0&&E.length===0&&(P||S&&!S.listed))return{workspaces:null,off:P};return{off:P,workspaces:[...b,...E].map(({organizationId:C,config:T,account:I})=>{let A=!1,D=null,L=!1,he=null;try{A=T?H(T).revoked:!1,D=T&&!A?M(T):null;let Le=T?pt(w(T).daemon):null;L=r&&!!D&&Le?.state==="connected",he=L?Vt(Le,D):null}catch{}return{...he?{permission_recovery:he}:{},organization_id:C,device_id:D?.deviceId??null,name:S?.names?.[C]??null,root:D?.roots[0]?{id:D.roots[0].id,permissions:D.roots[0].permissions}:null,state:A?"removed":L?"connected":"not_running",blocked:!I&&!A&&!L&&(S?.blocked.includes(C)??!1),...I?{account:!0}:{}}})}}import{readFileSync as ar}from"fs";function lr(e){try{let r=JSON.parse(ar(`${e}.keep-awake.json`,"utf8"));return r!==null&&typeof r==="object"&&"version"in r&&r.version===1&&"enabled"in r&&r.enabled===!0?"battery_and_ac":void 0}catch(r){return r.code==="ENOENT"?"battery_and_ac":void 0}}import{chmodSync as ji,lstatSync as Ze,mkdtempSync as qi,realpathSync as sr,rmdirSync as zi,rmSync as Ki,unlinkSync as Vi}from"fs";import{createConnection as cr,createServer as Gi}from"net";import{basename as Je,dirname as Ge,join as ne}from"path";var dr=s(["status","drain","resume","stop","reload_roots"]),ur=c({version:n(1),instanceId:t(),deviceId:t(),phase:s(["starting","running","reconnecting","stopping"]),drained:d(),activeClaims:o().int().nonnegative(),activeSessions:o().int().nonnegative().optional(),executionEligible:d(),supportedOperations:u(s(wt)).max(wt.length).optional(),capabilityReadiness:as(s(wt),d()).optional(),lastHeartbeat:t().nullable(),expiresAt:t()}),ta=c({nonce:t(),action:dr}),fr=i({nonce:k()}),mr=c({version:n(1),nonce:k(),socketPath:t().max(100)});function pr(e){return ne(w(e).lock,"control.json")}function Qe(e){return v(w(e).lock),fr.parse(JSON.parse(h(ne(w(e).lock,"owner.json"))))}function Xe(e){if(!f(e))return!1;let r=Ze(e);if(!r.isSocket()||r.uid!==process.getuid?.()||(r.mode&63)!==0)throw Error("worker_control_socket_not_private");return!0}function et(e,r){let p=pr(e);if(!f(p)){let S=w(e).socket;if(!f(S)||!Ze(S).isSocket())return null;return Xe(S)?S:null}let b=mr.parse(JSON.parse(h(p)));if(b.nonce!==r)throw Error("worker_instance_changed");if(process.platform==="win32"){if(!hr.test(b.socketPath))throw Error("worker_control_endpoint_invalid");return b.socketPath}let R=Ge(b.socketPath);if(Ge(R)!==sr("/tmp")||!/^(?:reason|ara)-worker-[A-Za-z0-9]{6}$/.test(Je(R))||Je(b.socketPath)!=="control.sock"||Buffer.byteLength(b.socketPath)>100)throw Error("worker_control_endpoint_invalid");if(!f(R))return null;return v(R),Xe(b.socketPath)?b.socketPath:null}var hr=/^\\\\\.\\pipe\\reason-worker-[0-9a-f-]{36}$/;function gr(e,r){try{let p=JSON.parse(h(ne(w(e).lock,"owner.json"))),b=p&&typeof p==="object"?p[r]:void 0;return typeof b==="string"?b:null}catch{return null}}function tt(e){return gr(e,"runtime_version")}function rt(e,r){if(r)return r.message==="worker_control_timeout"?"socket_timeout":"bad_reply";try{if(!f(ne(w(e).lock,"owner.json")))return"no_lock";return et(e,Qe(e).nonce)?"socket_refused":"no_socket"}catch{return"bad_reply"}}var ra=c({instance:t().nullable(),since:o().int().nonnegative()});async function G(e,r){let p=w(e);if(!f(ne(p.lock,"owner.json")))return null;let b=Qe(e),R=et(e,b.nonce);if(!R)return null;return new Promise((S,P)=>{let E=cr(R),C="",T=!1,I=(A,D)=>{if(T)return;if(T=!0,E.destroy(),D)P(D);else S(A)};E.setTimeout(2000,()=>E.destroy(Error("worker_control_timeout"))),E.on("connect",()=>E.write(JSON.stringify({nonce:b.nonce,action:r})+`
5
+ `)),E.on("data",(A)=>{if(C+=A.toString(),Buffer.byteLength(C)>16384)E.destroy(Error("worker_control_oversize"))}),E.on("error",(A)=>{if("code"in A&&["ECONNREFUSED","ENOENT"].includes(String(A.code)))I(null);else I(null,A.message==="worker_control_timeout"?A:Error("worker_control_unavailable"))}),E.on("end",()=>{try{let A=ur.parse(JSON.parse(C));if(A.instanceId!==b.nonce)throw Error("worker_instance_changed");I(A)}catch{I(null,Error("worker_control_invalid_response"))}}),E.once("close",()=>I(null,Error("worker_control_unavailable")))})}import{realpathSync as br}from"fs";import{constants as Re}from"fs";import{open as wr}from"fs/promises";var la={platform:process.platform,home:a,async openFile(e){let r=await wr(e,Re.O_RDONLY|Re.O_NOFOLLOW|Re.O_NONBLOCK);return{isFile:async()=>(await r.stat()).isFile(),close:()=>r.close()}}};var qa=Oo(br(process.execPath));var _s=Buffer.from([0,255,3,4]);import{execFile as an}from"child_process";import{promisify as sn}from"util";var Er=/#w=(\d{1,5})&h=(\d{1,5})$/;function at(e){return typeof e==="number"&&Number.isInteger(e)&&e>0&&e<=32768?e:void 0}function st(e){let r=Er.exec(e);if(!r)return;let p=at(Number(r[1])),b=at(Number(r[2]));return p&&b?{width:p,height:b}:void 0}var ct="[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}",Pr=new RegExp(`^/media/pr-screenshots/(${ct})/(${ct})/([a-z0-9][a-z0-9._-]*)\\.(png|jpe?g|gif|webp|webm|mp4)$`,"i");var Cr=new Set(["png","jpg","jpeg","gif","webp"]),Ar=new Set(["webm","mp4"]);function xr(e){if(!e)return null;try{return new URL(e).origin}catch{return null}}function Ir(e){let r=st(e);return Boolean(r&&e===`#w=${r.width}&h=${r.height}`)}function lt(e,r){let p;try{p=new URL(e)}catch{return null}let b=xr(r),R=p.hostname==="ara.so"||p.hostname.endsWith(".ara.so")||p.hostname==="reasonmachines.ai"||p.hostname.endsWith(".reasonmachines.ai")||p.hostname==="reasonmachines.com"||p.hostname.endsWith(".reasonmachines.com");if(p.protocol!=="https:"||!R&&p.origin!==b||p.username||p.password||p.port||p.search||p.hash&&!Ir(p.hash))return null;let S=Pr.exec(p.pathname);if(!S)return null;let P=S[1]?.toLowerCase(),E=S[2]?.toLowerCase(),C=S[3]?.toLowerCase(),T=S[4]?.toLowerCase();if(!P||!E||!C||!T)return null;let I=Cr.has(T)?"image":Ar.has(T)?"video":null;if(!I)return null;let A=/^(before|after)[\s:_-]+/.exec(C),D=p.pathname.replace(/^\/media\//,"");return{url:p.toString(),storagePath:D,runId:P,artifactId:E,fileName:`${C}.${T}`,kind:I,phase:A?.[1]==="before"||A?.[1]==="after"?A[1]:null}}var Or=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,dt=(e)=>Boolean(e&&typeof e==="object"&&!Array.isArray(e)),K=()=>{throw Error("cloud_browser_media_request_invalid")};function Pe(e){if(!dt(e)||Object.keys(e).some((S)=>!["runId","configuredMediaOrigin","media"].includes(S))||typeof e.runId!=="string"||!Or.test(e.runId)||typeof e.configuredMediaOrigin!=="string"||e.configuredMediaOrigin.length>2048||!Array.isArray(e.media)||e.media.length<1||e.media.length>8)return K();let r;try{r=new URL(e.configuredMediaOrigin)}catch{return K()}if(r.protocol!=="https:"||r.username||r.password||r.port||!Ue(r.origin,{mode:"public_web"}).allowed)return K();let p=e.runId.toLowerCase(),b=new Set,R=e.media.map((S)=>{if(!dt(S)||Object.keys(S).some((E)=>!["url","sourceUrl","kind"].includes(E))||typeof S.url!=="string"||S.url.length>2048||typeof S.sourceUrl!=="string"||S.sourceUrl.length>8192||!["image","video"].includes(String(S.kind)))return K();let P=lt(S.url,r.origin);if(!P||new URL(P.url).origin!==r.origin||P.runId!==p||P.kind!==S.kind||P.url!==S.url||b.has(S.url))return K();if(b.add(S.url),S.sourceUrl!==S.url){let E;try{E=new URL(S.sourceUrl)}catch{return K()}let C=/^\/(?:[a-f0-9]{40}|[a-f0-9]{64})\/([a-f0-9]+)$/.exec(E.pathname)?.[1];if(S.kind!=="image"||E.origin!=="https://camo.githubusercontent.com"||E.username||E.password||E.search||E.hash||!C||C.length%2!==0||Buffer.from(C,"hex").toString("utf8")!==S.url)return K()}return{url:S.url,sourceUrl:S.sourceUrl,kind:S.kind}});return{runId:e.runId,configuredMediaOrigin:r.origin,media:R}}var x=t().uuid(),X=t().regex(/^[a-f0-9]{64}$/),V=y.datetime({precision:3}),Ce=t().regex(/^[a-zA-Z0-9_-]{1,160}$/),mt=t().max(2048).regex(/^https:\/\/github\.com\/[A-Za-z0-9_-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/).refine((e)=>![".",".."].includes(e.split("/")[4])),U=i({kind:n("primary_mac"),version:n(1),organizationId:Ce,userId:Ce,sessionId:Ce,runId:x,deviceId:x,rootId:x,rootRevision:t().min(1).max(64),binding:s(["workspace_source","mcp_control"]),targetRevision:o().int().nonnegative(),generation:x,profile:t().regex(/^(Default|Profile [0-9]+)$/),extensionInstanceId:t().min(1).max(1024)}).strict().refine((e)=>e.binding!=="workspace_source"||e.targetRevision===0),Tr=on().transform((e,r)=>{try{return dn(e)}catch{return r.addIssue({code:"custom",message:"proof_visual_contract_invalid"}),Uo}}),ue=i({version:n(1),owner:U,contextId:x,preparedAt:V,expiresAt:V,prUrl:mt,headSha:t().regex(/^[a-f0-9]{40}$/),skillDigest:X,evidenceKind:s(["image","video"]),visualPlan:Tr.optional(),uploadOrigin:t().url().refine((e)=>{let r=new URL(e);return r.protocol==="https:"&&r.origin===e&&!r.username&&!r.password}).optional()}).strict().refine((e)=>Date.parse(e.expiresAt)>Date.parse(e.preparedAt)&&Date.parse(e.expiresAt)-Date.parse(e.preparedAt)<=300000),Dr=i({version:n(1),producer:n("primary_mac"),context:ue,captureId:x,operationId:x,attemptId:x,tabId:o().int().positive(),startedAt:V,finishedAt:V,sha256:X,media:g("contentType",[i({contentType:n("image/png"),sizeBytes:o().int().min(24).max(8388608),width:o().int().min(1).max(4096),height:o().int().min(1).max(4096)}).strict(),i({contentType:n("video/webm"),sizeBytes:o().int().min(128).max(10485760),durationSeconds:o().min(0.05).max(15),frameCount:o().int().min(1).max(450),receivedFrameCount:o().int().min(1).max(2000)}).strict()])}).strict().superRefine((e,r)=>{let p=Date.parse(e.startedAt),b=Date.parse(e.finishedAt);if(p<Date.parse(e.context.preparedAt)||b<p||b>Date.parse(e.context.expiresAt)||b-p>30000||e.media.contentType==="video/webm"&&(e.media.receivedFrameCount<e.media.frameCount||Math.abs((b-p)/1000-e.media.durationSeconds)>0.1))r.addIssue({code:"custom",message:"mac_pr_proof_capture_chronology_invalid"})}),yc=g("action",[i({action:n("screenshot"),context_id:x,tab_id:o().int().positive()}).strict(),i({action:n("start_video"),context_id:x,tab_id:o().int().positive(),seconds:o().int().min(1).max(15)}).strict(),i({action:n("stop_video"),recording_operation_id:x}).strict()]),fe=i({login:t().regex(/^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?$/),id:t().regex(/^[1-9][0-9]{0,19}$/).nullable()}).strict(),ce=t().regex(/^[1-9][0-9]{0,19}$/),le=i({version:n(1),owner:U,expectedActorId:ce.nullable(),repositoryId:ce,repositoryFullName:t().max(200).regex(/^[A-Za-z0-9_-]+\/[A-Za-z0-9_.-]+$/).refine((e)=>![".",".."].includes(e.split("/")[1]))}).strict(),Lr=["browser_unavailable","github_page_unavailable","identity_check_failed","operation_incomplete","attachment_unavailable"],Hr=g("status",[le.extend({status:n("ready"),observedActor:fe,checkedAt:V}),le.extend({status:n("not_ready"),reason:s(["authentication_required","identity_mismatch","authority_lost","unavailable"]),cause:s(Lr).optional()})]).refine((e)=>e.status!=="ready"||e.expectedActorId===null||e.observedActor.id===e.expectedActorId),Y=i({version:n(1),owner:U,expectedActorId:ce.nullable(),authenticatedActor:fe,attemptId:x,captureId:x,prUrl:mt,repositoryId:ce,headSha:t().regex(/^[a-f0-9]{40}$/),sha256:X,sizeBytes:o().int().min(128).max(10485760),contentType:n("video/webm")}).strict(),ht=t().regex(/^https:\/\/github\.com\/user-attachments\/assets\/[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/),$r=g("status",[Y.extend({status:n("not_attempted"),reason:s(["authentication_required","attachment_unavailable","identity_mismatch","capture_invalid","authority_lost"])}),Y.extend({status:n("uncertain"),reason:n("upload_outcome_unknown")}),Y.extend({status:n("uploaded"),observedActor:fe,nativeUrl:ht,uploadedAt:V})]).refine((e)=>(e.expectedActorId===null||e.authenticatedActor.id===e.expectedActorId)&&(e.status!=="uploaded"||e.observedActor.id===e.authenticatedActor.id&&e.observedActor.login===e.authenticatedActor.login)),de=Y.extend({nativeUrl:ht,observedActor:fe,bodySha256:X}),Br=g("status",[de.extend({status:n("incomplete"),reason:s(["authentication_required","identity_mismatch","playback_unverified","authority_lost"])}),de.extend({status:n("verified"),sourceSha256:X,width:o().int().min(1).max(4096),height:o().int().min(1).max(4096),durationSeconds:o().positive().max(30),advancedSeconds:o().min(0.05).max(10),advancedFrames:o().int().positive(),playbackRestored:n(!0),verifiedAt:V})]).refine((e)=>(e.expectedActorId===null||e.authenticatedActor.id===e.expectedActorId)&&e.observedActor.id===e.authenticatedActor.id&&e.observedActor.login===e.authenticatedActor.login&&(e.status!=="verified"||e.sourceSha256===e.sha256)),Ur=on().transform((e,r)=>{try{let p=Pe(e);if(p.media.some((b)=>b.kind!=="image"))throw Error();return p}catch{return r.addIssue({code:"custom",message:"proof_media_request_invalid"}),Uo}}),Fr=g("action",[i({action:n("auth_check"),input:le}).strict(),i({action:n("prepare"),context:ue}).strict(),i({action:n("capture_png"),owner:U,contextId:x,tabId:o().int().positive()}).strict(),i({action:n("start_video"),owner:U,contextId:x,tabId:o().int().positive(),seconds:o().int().min(1).max(15)}).strict(),i({action:n("inspect_capture"),owner:U,captureId:x}).strict(),i({action:n("publish_video"),input:Y}).strict(),i({action:n("verify_png_media"),owner:U,media:Ur}).strict().refine((e)=>e.media.runId===e.owner.runId),i({action:n("verify_saved_media"),input:de}).strict(),i({action:n("publish_png"),owner:U,attemptId:x,captureId:x,sha256:X,sizeBytes:o().int().min(24).max(8388608),storagePath:t().max(512),uploadUrl:t().url().max(8192)}).strict()]);var jr=i({requestId:x,command:Fr}).strict();var qr={type:"object",required:["action"],properties:{action:{type:"string",enum:["screenshot","start_video","stop_video"]},context_id:{type:"string",format:"uuid"},tab_id:{type:"integer",minimum:1},seconds:{type:"integer",minimum:1,maximum:15},recording_operation_id:{type:"string",format:"uuid"}},additionalProperties:!1},ut={type:"string",format:"uuid",description:"capture_context_id from tools.pr.prepareProof."},ft={type:"integer",minimum:1,description:"An already-owned tab's id."},_c={...qr,oneOf:[{type:"object",required:["action","context_id","tab_id"],additionalProperties:!1,properties:{action:{type:"string",const:"screenshot"},context_id:ut,tab_id:ft}},{type:"object",required:["action","context_id","tab_id","seconds"],additionalProperties:!1,properties:{action:{type:"string",const:"start_video"},context_id:ut,tab_id:ft,seconds:{type:"integer",minimum:1,maximum:15}}},{type:"object",required:["action","recording_operation_id"],additionalProperties:!1,properties:{action:{type:"string",const:"stop_video"},recording_operation_id:{type:"string",format:"uuid",description:"The recording_operation_id start_video returned."}}}]};var Rc=i({operationId:t().uuid(),attemptId:t().uuid(),contextId:t().uuid(),tabId:o().int().positive()}).strict();var zr=String.raw`async (media) => {
6
+ const deadline = (promise) => {
7
+ let timer;
8
+ return Promise.race([promise, new Promise((_, reject) => {
9
+ timer = setTimeout(() => reject(new Error("media_decode_timeout")), 12000);
10
+ })]).finally(() => clearTimeout(timer));
11
+ };
12
+ const items = await Promise.all(media.map(async (item) => {
13
+ const element = document.createElement(item.kind === "image" ? "img" : "video");
14
+ document.body.append(element);
15
+ try {
16
+ if (item.kind === "image") {
17
+ element.src = item.sourceUrl;
18
+ await deadline(element.decode());
19
+ if (!element.complete || !element.naturalWidth || !element.naturalHeight) throw new Error("media_image_not_decoded");
20
+ return { ...item, width: element.naturalWidth, height: element.naturalHeight };
21
+ }
22
+ element.muted = true;
23
+ element.playsInline = true;
24
+ element.preload = "auto";
25
+ const loaded = new Promise((resolve, reject) => {
26
+ element.addEventListener("loadeddata", resolve, { once: true });
27
+ element.addEventListener("error", () => reject(new Error("media_video_not_decoded")), { once: true });
28
+ });
29
+ element.src = item.sourceUrl;
30
+ await deadline(loaded);
31
+ if (!element.videoWidth || !element.videoHeight || !Number.isFinite(element.duration) || element.duration <= 0) throw new Error("media_video_not_decoded");
32
+ const initial = element.currentTime;
33
+ await deadline(element.play());
34
+ await deadline(new Promise((resolve, reject) => {
35
+ let timer;
36
+ const check = () => {
37
+ if (element.error) { clearTimeout(timer); reject(new Error("media_video_not_decoded")); return; }
38
+ if (element.currentTime - initial >= 0.05) { clearTimeout(timer); resolve(); return; }
39
+ timer = setTimeout(check, 25);
40
+ };
41
+ element.addEventListener("pause", () => { clearTimeout(timer); reject(new Error("media_video_not_advancing")); }, { once: true });
42
+ check();
43
+ }));
44
+ return { ...item, width: element.videoWidth, height: element.videoHeight, advancedSeconds: element.currentTime - initial };
45
+ } finally {
46
+ if (item.kind === "video") element.pause();
47
+ element.removeAttribute("src");
48
+ element.remove();
49
+ }
50
+ }));
51
+ return { verified: true, items };
52
+ }`;import{execFile as Kr}from"child_process";import{promisify as Vr}from"util";var Ic=Vr(Kr);var Vc=g("ok",[i({ok:n(!0),actor:i({login:t(),id:t().nullable()}).strict()}).strict(),i({ok:n(!1),reason:s(["authentication_required","identity_mismatch","attachment_unavailable"])}).strict()]),Jc=i({version:n("0.1.42"),metadata:i({extensionId:t(),extensionInstanceId:t(),nativeHostName:t()})});var Xc=i({version:n(1),recording_operation_id:t().uuid(),proof_ready:n(!1),acknowledged_at:y.datetime()}).strict(),me=i({action:n("start"),request_id:t().uuid(),profile:t().regex(/^(Default|Profile [0-9]+)$/),tab_id:o().int().positive(),seconds:o().int().min(1).max(15)}).strict(),gt=i({action:n("inspect"),recording_operation_id:t().uuid()}).strict(),Zc=g("action",[me,gt]),yt=i({recording_operation_id:t().uuid()}).strict(),Ie={device_id:t().uuid(),root_id:t().uuid()},Gr=g("action",[me.extend(Ie),gt.extend(Ie),yt.extend({...Ie,action:n("stop")})]),Qc=nn(Gr),el=i({version:n(1),recordingId:t().uuid(),proofReady:n(!1),capture:i({captureId:t().uuid(),contentType:n("video/webm"),sha256:t().regex(/^[a-f0-9]{64}$/),sizeBytes:o().int().min(128).max(10485760),startedAt:y.datetime(),finishedAt:y.datetime(),durationSeconds:o().min(0.05).max(15),frameCount:o().int().min(1).max(450),receivedFrameCount:o().int().min(1).max(2000),owner:i({runId:t().uuid(),deviceId:t().uuid(),rootId:t().uuid(),rootRevision:t().max(64),profile:t().regex(/^(Default|Profile [0-9]+)$/),extensionInstanceId:t().min(1).max(1024),generation:t().uuid(),browserScope:t().max(128),tabId:o().int().positive()}).strict()}).strict().refine((e)=>e.receivedFrameCount>=e.frameCount&&Math.abs((Date.parse(e.finishedAt)-Date.parse(e.startedAt))/1000-e.durationSeconds)<=0.1)}).strict();var dl=me.extend({action:s(["start","inspect"]),recording_boot_generation:t().uuid(),recording_operation_id:t().uuid().optional(),recording_attempt_id:t().uuid().optional()}).strict();import{execFile as Yr}from"child_process";import{promisify as Xr}from"util";var pl=Xr(Yr);var Zr=s(["recording_failed","authority_lost","browser_timeout","cleanup_failed","no_frames","encoding_invalid","frame_invalid","timestamp_invalid","capture_bound","ack_failed","cancelled","detached","browser_changed","tab_not_owned","encoding_frames_failed","encoding_encode_failed","encoding_output_failed","encoding_probe_failed","encoding_probe_streams_failed","encoding_probe_dimensions_failed","encoding_probe_duration_failed","encoding_probe_frames_failed","encoding_probe_format_failed","encoding_decode_failed","encoding_pin_failed"]);var j=t().min(1).max(1024),_t=i({path:j,sha256:t().regex(/^[a-f0-9]{64}$/)}).strict(),Qr=i({owner:i({runId:j,deviceId:j,rootId:j,rootRevision:j,profile:t().regex(/^(Default|Profile [0-9]+)$/),extensionInstanceId:j,generation:j,browserScope:j,tabId:o().int().positive()}).strict(),socketPath:j,extensionId:t().regex(/^[a-p]{32}$/),nativeHostName:j,seconds:o().int().min(1).max(15),encoder:i({ffmpeg:_t,ffprobe:_t}).strict()}).strict();var Ll=i({version:n("0.1.42"),metadata:i({extensionId:t(),extensionInstanceId:t(),nativeHostName:t()})});var Vl=i({operationId:t().uuid()}).strict();var fd=sn(an);var md=i({version:n("0.1.42"),metadata:i({extensionId:n(F),extensionInstanceId:t().min(1).max(1024)})});var Te=1;var Lf=c({type:n("configure"),protocol:n(Te),version:t(),config:B}),Wf=c({type:n("ticket"),organizationId:t().min(1).max(160),receipt:Oe()}),Nf=c({type:s(["ping","stop"])});var Qf=c({type:n("hello"),protocol:n(Te),version:t(),platform:s(["linux","darwin"]),architecture:s(["arm64","x64"]),enrolled:d()}),em=c({type:n("ticket-request"),request:c({install_id:k(),code_challenge:t().regex(/^[A-Za-z0-9_-]{43}$/),lifecycle:s(["persistent","ephemeral"]),roots:u(c({path_fingerprint:t().regex(/^[a-f0-9]{64}$/),execution_mode:s(["confined","host"]),permissions:c({read:n(!0),write:n(!0),execute:n(!0),discover_environment:n(!0),expose_mcp:n(!1)})})).length(1)})}),tm=g("type",[c({type:n("running"),deviceId:t().min(1).max(160),expiresAt:y.datetime({offset:!0}),lifetime:s(["persistent","ephemeral"]),supervision:n("ssh-foreground")}),c({type:n("pong")}),c({type:n("stopped")})]);var Rn=1;var Z=k(),En=c({kind:n("install_only"),authorityId:Z,organizationId:Z,userId:Z,connectionId:Z,attemptId:Z,purpose:n("install"),generation:o().int().positive(),transport:n("reverse_ssh"),expiresAt:y.datetime({offset:!0}),maxDurationMs:n(300000),maxChannels:n(1),allowTcpForwarding:n(!1),allowPty:n(!1)}),Pn=t().max(2048).superRefine((e,r)=>{let p;try{p=new URL(e)}catch{r.addIssue({code:"custom",message:"invalid relay url"});return}if(p.protocol!=="ws:"&&p.protocol!=="wss:"){r.addIssue({code:"custom",message:"invalid relay protocol"});return}if(p.username||p.password||p.search||p.hash){r.addIssue({code:"custom",message:"relay credentials or modifiers are not allowed"});return}let b=p.pathname.split("/");if(b.length!==4||b[1]!=="device"||!Z.safeParse(b[2]).success||!/^[a-f0-9]{64}$/.test(b[3]??""))r.addIssue({code:"custom",message:"invalid device relay path"});if(p.protocol==="ws:"&&!["127.0.0.1","[::1]"].includes(p.hostname))r.addIssue({code:"custom",message:"plaintext relay must be loopback"})});var om=c({protocol:n(Rn),type:n("ssh_install_relay"),authorityToken:t().regex(/^(?:reason|ara)_ssh_install_[A-Za-z0-9_-]{43}$/),authority:En,relayUrl:Pn,endpoint:c({host:n("127.0.0.1"),port:n(22)})});class At extends Error{}function Be(e){if(!f(e))return null;let r=new At(`${e} is not a valid worker config. Remove it to start over.`),p;try{p=JSON.parse(h(e))}catch(R){if(R instanceof SyntaxError)throw r;throw R}let b=B.safeParse(p);if(!b.success)throw r;return b.data}var Ln=200;var Zp=c({version:n(1),session_ids:u(t().min(1).max(200)).max(Ln)});function nt(e,r,p=!1){let b=Wn(e,r,p);return b.length===1?b[0]:J(ke(J(e,".config")),...xt(r,p))}var xt=(e,r)=>[...e==="production"?[]:[e],r?"connect-once":"connect"];function Wn(e,r,p=!1){let b=e;try{b=pe(e)}catch{}return["ara","reason"].map((R)=>J(b,".config",R,...xt(r,p))).filter(Nn)}function Nn(e){try{if(pe(e)!==e)return!1;return Be(J(e,"worker.json"))?.stateDirectory===e}catch{return!1}}var Hn="disconnected.json";function ds(e,r){return f(J(nt(e,r),Hn))}function $n(e,r){return r==="darwin"&&e.userChrome!==!1}var xg=i({root:i({id:t().min(1).max(160),label:t().max(160),path_fingerprint:t()})});var Ig=Symbol("serve here");async function ps(e={}){let r=pe(e.home??a()),p=Be(J(nt(r,e.channel??_()),"worker.json"));if(!p)return null;let b,R=await(e.controlWorker??G)(p,"status").catch((L)=>(b=L instanceof Error?L:Error(String(L)),null)),S=R?tt(p):null,P=e.serviceHost??xe(r),E=Ye(p,P,"connect"),C=H(p).revoked,T=!C&&!R,I=(()=>{try{return M(p)}catch{return null}})(),{workspaces:A,off:D}=C||we(p.stateDirectory)!==null?{workspaces:null,off:null}:qe(p,R?.phase==="running");return{workspaces:A,workspaces_off:D,workspaces_max:je+(A?.filter((L)=>L.account).length??0),name:p.name,device_id:I?.deviceId??null,organization_id:I?.orgId??null,folder:p.workspaceRoot,mode:p.executionMode,sessions_max:null,user_chrome:$n(p,P.platform),cloud_sessions:p.cloudSessions===!0,root:I?.roots[0]?{id:I.roots[0].id,permissions:I.roots[0].permissions}:null,roots:I?.roots.map((L)=>({id:L.id,folder:L.path,permissions:L.permissions}))??[],state:C?"removed":R?R.phase==="running"?"connected":R.phase:"not_running",not_running_reason:T?rt(p,b):null,worker_alive:T&&E?Zn(E,P):null,sessions_running:R?.activeSessions??null,version:S,service:E?{label:E.label,logs:E.logs}:null}}function hs(e={}){let r=pe(e.home??a()),p=Be(J(nt(r,e.channel??_()),"worker.json"));if(!p)return null;return Wr(p,e.serviceHost??xe(r),"connect")?.label??null}export{w,M,lr,Be,nt,ds,ps,hs};