@reason-machines/cli-linux-x64 0.2.567 → 0.2.569

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 (71) hide show
  1. package/bin/reason +1 -1
  2. package/bin/vm-hands/agent-network-wnhby2hh.js +2 -0
  3. package/bin/vm-hands/{api-credentials-h4neeejt.js → api-credentials-5av6jdtt.js} +1 -1
  4. package/bin/vm-hands/api-j7g5mxg0.js +2 -0
  5. package/bin/vm-hands/{ask-relay-c0v30hh6.js → ask-relay-q93yfzy6.js} +2 -2
  6. package/bin/vm-hands/connect-cli-fn0ek2c4.js +2 -0
  7. package/bin/vm-hands/{credentials-nfx99zxr.js → credentials-gwh93z0q.js} +1 -1
  8. package/bin/vm-hands/{custom-endpoint-device-5047vdn3.js → custom-endpoint-device-yvjz40qq.js} +1 -1
  9. package/bin/vm-hands/{desktop-components-7ngf8byq.js → desktop-components-gsqad6xm.js} +1 -1
  10. package/bin/vm-hands/{hands-worker-source-8a4kh44t.js → hands-worker-source-j4yz7x6h.js} +1 -1
  11. package/bin/vm-hands/{install-receipt-rckwjqmt.js → install-receipt-7hvy0181.js} +1 -1
  12. package/bin/vm-hands/local-automation-zjrnxdh7.js +2 -0
  13. package/bin/vm-hands/local-capabilities-ka01z0mb.js +2 -0
  14. package/bin/vm-hands/local-display-session-vbsgwq8z.js +2 -0
  15. package/bin/vm-hands/local-display-video-yb4bh3t9.js +2 -0
  16. package/bin/vm-hands/local-managed-process-52qasdaq.js +2 -0
  17. package/bin/vm-hands/{local-pty-session-w0yhjdvz.js → local-pty-session-hnxtqd5m.js} +1 -1
  18. package/bin/vm-hands/{managed-runtime-4s8q8r7f.js → managed-runtime-80xhqysb.js} +1 -1
  19. package/bin/vm-hands/{network-auto-update-wep7067g.js → network-auto-update-3036s9xr.js} +2 -2
  20. package/bin/vm-hands/{network-contract-ht0psj5j.js → network-contract-3jfjnv65.js} +1 -1
  21. package/bin/vm-hands/{network-sign-in-rdnerhpz.js → network-sign-in-dx5eg0xz.js} +1 -1
  22. package/bin/vm-hands/{permissions-mmg1gbdx.js → permissions-8egc93sd.js} +1 -1
  23. package/bin/vm-hands/{reason-hands-protocol-9r62swp0.js → reason-hands-protocol-wz7z9pzz.js} +1 -1
  24. package/bin/vm-hands/{serve-service-k3mpxpj6.js → serve-service-cdfwh6pg.js} +1 -1
  25. package/bin/vm-hands/{status-2s3zjapg.js → status-0td77s7a.js} +6 -6
  26. package/bin/vm-hands/{version-41q9twfs.js → version-6m3prwm9.js} +1 -1
  27. package/bin/vm-hands/{vm-hands-entry-lite-vvhfaxpd.js → vm-hands-entry-lite-1bdtt81g.js} +3 -3
  28. package/bin/vm-hands/{vm-hands-entry-lite-vedb5r12.js → vm-hands-entry-lite-2dx59pgq.js} +1 -1
  29. package/bin/vm-hands/{vm-hands-entry-lite-298kzt93.js → vm-hands-entry-lite-2zf4bqx9.js} +86 -86
  30. package/bin/vm-hands/{vm-hands-entry-lite-ax2w9ywb.js → vm-hands-entry-lite-3929hmh0.js} +2 -2
  31. package/bin/vm-hands/{vm-hands-entry-lite-r131db1f.js → vm-hands-entry-lite-39anhpg6.js} +1 -1
  32. package/bin/vm-hands/{vm-hands-entry-lite-cy8yc9gb.js → vm-hands-entry-lite-5ypg0t3q.js} +14 -14
  33. package/bin/vm-hands/{vm-hands-entry-lite-1as6h9ed.js → vm-hands-entry-lite-73tecmk2.js} +4 -4
  34. package/bin/vm-hands/{vm-hands-entry-lite-dzdjwa06.js → vm-hands-entry-lite-7vg80fmc.js} +1 -1
  35. package/bin/vm-hands/{vm-hands-entry-lite-dfphra23.js → vm-hands-entry-lite-8tjr2pqm.js} +2 -2
  36. package/bin/vm-hands/{vm-hands-entry-lite-crjaacc2.js → vm-hands-entry-lite-9c0g9ykw.js} +1 -1
  37. package/bin/vm-hands/{vm-hands-entry-lite-0xfme8gg.js → vm-hands-entry-lite-a4fn6ye1.js} +2 -2
  38. package/bin/vm-hands/{vm-hands-entry-lite-6g9we34r.js → vm-hands-entry-lite-bpc8z6p7.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-3r063pb4.js → vm-hands-entry-lite-cr3hypam.js} +2 -2
  40. package/bin/vm-hands/{vm-hands-entry-lite-9gn7k5rp.js → vm-hands-entry-lite-d7gepm66.js} +11 -11
  41. package/bin/vm-hands/{vm-hands-entry-lite-vha0pf8k.js → vm-hands-entry-lite-ea3cts1t.js} +1 -1
  42. package/bin/vm-hands/{vm-hands-entry-lite-4kb5rq3d.js → vm-hands-entry-lite-hnsdwskm.js} +3 -3
  43. package/bin/vm-hands/{vm-hands-entry-lite-3594pdj0.js → vm-hands-entry-lite-htrswrf0.js} +1 -1
  44. package/bin/vm-hands/{vm-hands-entry-lite-bbjsnjct.js → vm-hands-entry-lite-jjv6s3mx.js} +1 -1
  45. package/bin/vm-hands/vm-hands-entry-lite-kc8p21xt.js +10 -0
  46. package/bin/vm-hands/{vm-hands-entry-lite-zaj1vnnd.js → vm-hands-entry-lite-kvxf67qp.js} +7 -7
  47. package/bin/vm-hands/{vm-hands-entry-lite-1cdtev4n.js → vm-hands-entry-lite-mkvey48j.js} +1 -1
  48. package/bin/vm-hands/{vm-hands-entry-lite-bt6skt4h.js → vm-hands-entry-lite-n31pta3n.js} +2 -2
  49. package/bin/vm-hands/{vm-hands-entry-lite-bc9zq8gx.js → vm-hands-entry-lite-n6q8033g.js} +1 -1
  50. package/bin/vm-hands/{vm-hands-entry-lite-rmcdfbkk.js → vm-hands-entry-lite-nrr68p5x.js} +14 -14
  51. package/bin/vm-hands/{vm-hands-entry-lite-dtw6cj95.js → vm-hands-entry-lite-nsaa15dt.js} +1 -1
  52. package/bin/vm-hands/{vm-hands-entry-lite-07wr95rz.js → vm-hands-entry-lite-p0gtjbkp.js} +1 -1
  53. package/bin/vm-hands/{vm-hands-entry-lite-tv5mcw97.js → vm-hands-entry-lite-qb0tvsw7.js} +1 -1
  54. package/bin/vm-hands/{vm-hands-entry-lite-n5jyzccm.js → vm-hands-entry-lite-sqp59sgh.js} +1 -1
  55. package/bin/vm-hands/{vm-hands-entry-lite-b3mfma12.js → vm-hands-entry-lite-x81fqstd.js} +1 -1
  56. package/bin/vm-hands/{vm-hands-entry-lite-8twdd0ff.js → vm-hands-entry-lite-yqzy5wp8.js} +1 -1
  57. package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
  58. package/bin/vm-hands/{vm-hands-executor-31ea40aw.js → vm-hands-executor-n3q4gj7p.js} +1 -1
  59. package/bin/vm-hands/{vm-hands-op-runner-6r390v3d.js → vm-hands-op-runner-jtd2nfyk.js} +1 -1
  60. package/bin/vm-hands/vm-hands-runtime-912jvj9s.js +4 -0
  61. package/package.json +1 -1
  62. package/bin/vm-hands/agent-network-0sng03r6.js +0 -2
  63. package/bin/vm-hands/api-mr6xds10.js +0 -2
  64. package/bin/vm-hands/connect-cli-jc4m755k.js +0 -2
  65. package/bin/vm-hands/local-automation-3mdhfw08.js +0 -2
  66. package/bin/vm-hands/local-capabilities-6e0gkrqq.js +0 -2
  67. package/bin/vm-hands/local-display-session-r6s0wghh.js +0 -2
  68. package/bin/vm-hands/local-display-video-61peg1pj.js +0 -2
  69. package/bin/vm-hands/local-managed-process-p8xd7m5f.js +0 -2
  70. package/bin/vm-hands/vm-hands-entry-lite-xd393rm3.js +0 -10
  71. package/bin/vm-hands/vm-hands-runtime-z9m50n9p.js +0 -4
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{w}from"./vm-hands-entry-lite-0xfme8gg.js";import{existsSync as T,mkdirSync as k,readFileSync as d,rmSync as y,writeFileSync as b}from"fs";import{homedir as l,hostname as M}from"os";import{dirname as N,join as h}from"path";function f(t){let e=t.trim().slice(t.trim().indexOf("#")+1),o=["rn1-","tincan1"].find((a)=>e.startsWith(a));if(!o)return null;let n=Buffer.from(e.slice(o.length),"base64url"),r=32,i=(a)=>(r+=a,r<=n.length),m=()=>{let a=n[r];if(a===void 0||!i(1))return!1;if(a!==255)return i(a);let s=n[r];return s!==void 0&&i(1)&&i(s)};if(n.length<32||!m()||!m()||!m())return null;let u=n[r];if(u===void 0||!i(1))return null;for(let a=0;a<u;a+=1){let s=n[r];if(!i(1)||!i(s===4?4:s===6?16:Number.NaN)||!i(2))return null}let g=[];for(;r+32<=n.length;r+=32)g.push(n.subarray(r,r+32).toString("hex"));return{team:n.subarray(0,16).toString("hex"),name:n.subarray(33,33+n[32]).toString("utf8"),secret:n.subarray(16,32).toString("hex"),machines:g}}var p=(t)=>h(t,".reason","ask.json");function A(t){try{let e=JSON.parse(d(p(t),"utf8"));if(typeof e.orgId!=="string"||typeof e.team!=="string")return null;let o=e.pendingRotation;return{orgId:e.orgId,team:e.team,...typeof e.checkedAt==="number"?{checkedAt:e.checkedAt}:{},...o&&typeof o.link==="string"&&typeof o.team==="string"&&typeof o.replaces==="string"?{pendingRotation:o}:{}}}catch{return null}}var c=(t)=>{let e=w();return h(t,".reason",e==="production"?"network-team.json":`network-team.${e}.json`)};function ka(t=l()){return c(t).replace(/\.json$/,"-login.json")}function xa(t=l()){try{let e=JSON.parse(d(c(t),"utf8"));return typeof e.team==="string"?{team:e.team,setupDone:e.setupDone===!0,registered:typeof e.registered==="string"?e.registered:null,account:typeof e.account==="string"?e.account:null}:null}catch{return null}}function Ca(t,e=l()){k(N(c(e)),{recursive:!0}),b(c(e),`${JSON.stringify(t)}
2
+ import{w}from"./vm-hands-entry-lite-a4fn6ye1.js";import{existsSync as T,mkdirSync as k,readFileSync as d,rmSync as y,writeFileSync as b}from"fs";import{homedir as l,hostname as M}from"os";import{dirname as N,join as h}from"path";function f(t){let e=t.trim().slice(t.trim().indexOf("#")+1),o=["rn1-","tincan1"].find((a)=>e.startsWith(a));if(!o)return null;let n=Buffer.from(e.slice(o.length),"base64url"),r=32,i=(a)=>(r+=a,r<=n.length),m=()=>{let a=n[r];if(a===void 0||!i(1))return!1;if(a!==255)return i(a);let s=n[r];return s!==void 0&&i(1)&&i(s)};if(n.length<32||!m()||!m()||!m())return null;let u=n[r];if(u===void 0||!i(1))return null;for(let a=0;a<u;a+=1){let s=n[r];if(!i(1)||!i(s===4?4:s===6?16:Number.NaN)||!i(2))return null}let g=[];for(;r+32<=n.length;r+=32)g.push(n.subarray(r,r+32).toString("hex"));return{team:n.subarray(0,16).toString("hex"),name:n.subarray(33,33+n[32]).toString("utf8"),secret:n.subarray(16,32).toString("hex"),machines:g}}var p=(t)=>h(t,".reason","ask.json");function A(t){try{let e=JSON.parse(d(p(t),"utf8"));if(typeof e.orgId!=="string"||typeof e.team!=="string")return null;let o=e.pendingRotation;return{orgId:e.orgId,team:e.team,...typeof e.checkedAt==="number"?{checkedAt:e.checkedAt}:{},...o&&typeof o.link==="string"&&typeof o.team==="string"&&typeof o.replaces==="string"?{pendingRotation:o}:{}}}catch{return null}}var c=(t)=>{let e=w();return h(t,".reason",e==="production"?"network-team.json":`network-team.${e}.json`)};function ka(t=l()){return c(t).replace(/\.json$/,"-login.json")}function xa(t=l()){try{let e=JSON.parse(d(c(t),"utf8"));return typeof e.team==="string"?{team:e.team,setupDone:e.setupDone===!0,registered:typeof e.registered==="string"?e.registered:null,account:typeof e.account==="string"?e.account:null}:null}catch{return null}}function Ca(t,e=l()){k(N(c(e)),{recursive:!0}),b(c(e),`${JSON.stringify(t)}
3
3
  `,{mode:384}),y(p(e),{force:!0})}function Kr(t=l()){let e=A(t);return e?{orgId:e.orgId,team:e.team}:null}function Jr(t){let e=f(t);return e&&e.machines.length>0?{teamId:e.team,teamName:e.name,secret:e.secret}:null}
4
4
  export{ka,xa,Ca,Kr,Jr};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{w,ye}from"./vm-hands-entry-lite-0xfme8gg.js";import{wt}from"./vm-hands-entry-lite-peyr9y6z.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 Q(r=process.env,n=y()){let e=r.XDG_CONFIG_HOME?.trim()||o(n,".config"),t=w({env:r})==="staging"?["staging"]:[];return o(wt(e,...t),"credentials.json")}function so(r,n=Q()){return u(S(n),{recursive:!0,mode:448}),d(n,`${JSON.stringify(r,null,2)}
3
- `,{mode:384}),c(n,384),n}function ve(r=Q()){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=ye(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)}
2
+ import{w,we}from"./vm-hands-entry-lite-a4fn6ye1.js";import{wt}from"./vm-hands-entry-lite-peyr9y6z.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 Q(r=process.env,n=y()){let e=r.XDG_CONFIG_HOME?.trim()||o(n,".config"),t=w({env:r})==="staging"?["staging"]:[];return o(wt(e,...t),"credentials.json")}function so(r,n=Q()){return u(S(n),{recursive:!0,mode:448}),d(n,`${JSON.stringify(r,null,2)}
3
+ `,{mode:384}),c(n,384),n}function Se(r=Q()){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=we(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 ao(r=Q()){if(!a(r))return!1;return l(r),!0}
5
- export{Q,so,ve,ao};
5
+ export{Q,so,Se,ao};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{te}from"./vm-hands-entry-lite-hpw27zfb.js";import{_r}from"./vm-hands-entry-lite-bc9zq8gx.js";import{_n}from"./vm-hands-entry-lite-dh87ysh2.js";import{Se}from"./vm-hands-entry-lite-1as6h9ed.js";import{Ge}from"./vm-hands-entry-lite-tzv8s0e7.js";import{Ot}from"./vm-hands-entry-lite-wnqqjsew.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{existsSync as D,realpathSync as W,statSync as J}from"fs";import{platform as h}from"os";import{isAbsolute as q,sep as X}from"path";import{existsSync as F}from"fs";import{createRequire as H}from"module";var k=Ot(_n)(()=>H(import.meta.url)("bun:ffi"),F);function yi(){return process.platform==="win32"&&typeof globalThis.Bun<"u"&&k.available()}function E(e=process.env){return k.defaultShell(e)}function C(e){return k.shellArgs(e)}function M(e){let n=k.spawn({...e,env:e.environment});return n.exited.then(()=>n.close()),{write:(o)=>n.write(o),resize:(o,t)=>n.resize(o,t),kill:()=>n.close(),exited:n.exited}}var wi=43200000,hn=_r,bi=4,Y=/^[A-Za-z0-9._:-]{1,160}$/,K=1000;function z(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function P(e,n){if(typeof e!=="number"||!Number.isFinite(e)||e<=0)return n;return Math.min(K,Math.max(1,Math.floor(e)))}function G(e,n=Date.now()){let o=["relay_url","session_id","expires_at"],t=new Set([...o,"cols","rows","cwd","workspace"]);if(!z(e)||o.some((b)=>!(b in e))||Object.keys(e).some((b)=>!t.has(b)))throw new r("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:c,session_id:m,expires_at:g}=e;if(typeof c!=="string")throw new r("invalid_pty_request","Reason terminal relay URL is missing.");let d;try{d=new URL(c)}catch{throw new r("invalid_pty_request","Reason terminal relay URL is invalid.")}if(d.protocol!=="wss:"&&d.protocol!=="ws:"||d.username||d.password)throw new r("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof m!=="string"||!Y.test(m))throw new r("invalid_pty_request","Reason terminal session identity is invalid.");let p=typeof g==="string"?Date.parse(g):Number.NaN;if(!Number.isFinite(p)||p<=n)throw new r("invalid_pty_request","Reason terminal session has already expired.");if(e.cwd!==void 0&&typeof e.cwd!=="string")throw new r("invalid_pty_request","Reason terminal working directory is invalid.");let a=e.workspace===void 0?void 0:te(e.workspace);if(a===null||a&&e.cwd!==void 0)throw new r("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:c,session_id:m,expires_at:new Date(Math.min(p,n+wi)).toISOString(),cols:P(e.cols,80),rows:P(e.rows,24),...e.cwd===void 0?{}:{cwd:e.cwd},...a?{workspace:a}:{}}}function Q(e,n){if(h()==="win32")[e,n]=[e.toLowerCase(),n.toLowerCase()];return n===e||n.startsWith(e+X)}function N(e,n){if(n===void 0)return e;if(!q(n))throw new r("pty_cwd_invalid","Reason terminal working directory must be absolute.");let o;try{o=W(n)}catch{throw new r("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!Q(e,o))throw new r("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!J(o).isDirectory())throw new r("pty_cwd_invalid","Reason terminal working directory is not a directory.");return o}function il(e=process.env){if(h()==="win32")return E(e);let n=e.SHELL;if(n&&q(n)&&D(n))return n;for(let o of h()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(D(o))return o;return"/bin/sh"}function V(){let e=globalThis.Bun;if(!e)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");return e.spawn}function Fo(){if(h()==="win32")return yi();return typeof globalThis.Bun<"u"}var Z=(e)=>{if(h()==="win32")try{return M({...e,file:e.shell,args:C(e.shell),environment:{...e.environment,TERM:"xterm-256color"}})}catch{throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}let n=V()({cmd:[e.shell,"-i","-l"],cwd:e.cwd,env:{...e.environment,TERM:"xterm-256color"},terminal:{cols:e.cols,rows:e.rows,data:(t,c)=>{e.onData(c)}}}),o=n.terminal;if(!o){try{n.kill()}catch{}throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(t)=>o.write(t),resize:(t,c)=>o.resize(t,c),kill:()=>{try{n.kill()}catch{}},exited:n.exited.then((t)=>typeof t==="number"?t:null,()=>null)}},vi=(e,n)=>n===void 0?new WebSocket(e):new WebSocket(e,{proxy:n}),v=new Set;function ee(e){if(v.size>=bi||v.has(e))return null;v.add(e);let n=!1;return()=>{if(n)return;n=!0,v.delete(e)}}async function jo(e,n={}){let o=n.now??Date.now,t=G(e.payload,o()),c=ee(e.operationId);if(!c)throw new r("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let m=o(),g,d,p;try{let a=t.workspace?Ge(e.root,t.workspace):void 0;g=a?N(D(a.boundary)?W(a.boundary):a.boundary,a.path):N(e.root,t.cwd),d=n.environment??process.env,p=n.shellPath??il(d)}catch(a){throw c(),a}return await new Promise((a,b)=>{let w=null,i=null,S=!1,x=!1,y=!1,T=null,U=0,B=0,O=[],R=0,A=null,l=(s)=>{if(y)return;if(y=!0,A)clearTimeout(A);e.signal.removeEventListener("abort",L);try{w?.kill()}catch{}try{i?.close(1000,"pty_session_over")}catch{}if(c(),s.kind==="rejected"){b(s.error);return}let u={reason:s.reason,exit_code:T,output_bytes:U,input_bytes:B,duration_ms:Math.max(0,o()-m)};e.emitEvent("pty.stopped",{...u}).catch(()=>{return}),a({...u})},L=()=>{let s=e.signal.reason;l({kind:"rejected",error:s instanceof r?s:new r("cancelled","Reason closed the terminal session.")})};if(e.signal.aborted){L();return}e.signal.addEventListener("abort",L,{once:!0}),A=setTimeout(()=>l({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(t.expires_at)-o()));let I=(s)=>{if(U+=s.byteLength,!S||!i){if(O.push(s),R+=s.byteLength,R>hn)l({kind:"resolved",reason:"output_backpressure"});return}try{i.send(s)}catch{l({kind:"resolved",reason:"relay_closed"});return}if(i.bufferedAmount>hn)l({kind:"resolved",reason:"output_backpressure"})};try{w=(n.spawnPty??Z)({shell:p,args:["-i","-l"],cwd:g,cols:t.cols,rows:t.rows,environment:d,onData:(s)=>{if(!y)I(s)}})}catch(s){l({kind:"rejected",error:s instanceof r?s:new r("pty_spawn_failed","Reason could not start the terminal shell.")});return}w.exited.then((s)=>{if(y)return;if(T=s,S&&i)try{i.send(JSON.stringify({t:"exit",code:s}))}catch{}l({kind:"resolved",reason:"shell_exited"})});let j=(n.loadProxy??Se)()?.url;try{i=(n.connect??vi)(t.relay_url,j)}catch{l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}i.binaryType="arraybuffer",i.onopen=()=>{if(y||!i)return;S=!0;try{i.send(JSON.stringify({t:"open",cols:t.cols,rows:t.rows}));for(let s of O.splice(0))i.send(s);R=0}catch{l({kind:"resolved",reason:"relay_closed"});return}x=!0,e.emitEvent("pty.ready",{session_id:t.session_id,cols:t.cols,rows:t.rows}).catch(()=>{return})},i.onmessage=(s)=>{if(y||!w)return;let u=s.data;if(typeof u==="string"){let f;try{f=JSON.parse(u)}catch{return}if(!z(f))return;if(f.t==="resize"){try{w.resize(P(f.cols,t.cols),P(f.rows,t.rows))}catch{}return}if(f.t==="close")l({kind:"resolved",reason:"client_closed"});return}let _=u instanceof ArrayBuffer?new Uint8Array(u):ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):null;if(!_||_.byteLength===0)return;B+=_.byteLength;try{w.write(_)}catch{}},i.onclose=()=>{if(y)return;if(!x){l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}l({kind:"resolved",reason:"relay_closed"})},i.onerror=()=>{if(y||x)return;l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
2
+ import{te}from"./vm-hands-entry-lite-hpw27zfb.js";import{_r}from"./vm-hands-entry-lite-n6q8033g.js";import{_n}from"./vm-hands-entry-lite-dh87ysh2.js";import{Ee}from"./vm-hands-entry-lite-73tecmk2.js";import{Ge}from"./vm-hands-entry-lite-tzv8s0e7.js";import{Ot}from"./vm-hands-entry-lite-wnqqjsew.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{existsSync as D,realpathSync as W,statSync as J}from"fs";import{platform as h}from"os";import{isAbsolute as q,sep as X}from"path";import{existsSync as F}from"fs";import{createRequire as H}from"module";var k=Ot(_n)(()=>H(import.meta.url)("bun:ffi"),F);function yi(){return process.platform==="win32"&&typeof globalThis.Bun<"u"&&k.available()}function E(e=process.env){return k.defaultShell(e)}function C(e){return k.shellArgs(e)}function M(e){let n=k.spawn({...e,env:e.environment});return n.exited.then(()=>n.close()),{write:(o)=>n.write(o),resize:(o,t)=>n.resize(o,t),kill:()=>n.close(),exited:n.exited}}var wi=43200000,hn=_r,bi=4,Y=/^[A-Za-z0-9._:-]{1,160}$/,K=1000;function z(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function P(e,n){if(typeof e!=="number"||!Number.isFinite(e)||e<=0)return n;return Math.min(K,Math.max(1,Math.floor(e)))}function G(e,n=Date.now()){let o=["relay_url","session_id","expires_at"],t=new Set([...o,"cols","rows","cwd","workspace"]);if(!z(e)||o.some((b)=>!(b in e))||Object.keys(e).some((b)=>!t.has(b)))throw new r("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:c,session_id:m,expires_at:g}=e;if(typeof c!=="string")throw new r("invalid_pty_request","Reason terminal relay URL is missing.");let d;try{d=new URL(c)}catch{throw new r("invalid_pty_request","Reason terminal relay URL is invalid.")}if(d.protocol!=="wss:"&&d.protocol!=="ws:"||d.username||d.password)throw new r("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof m!=="string"||!Y.test(m))throw new r("invalid_pty_request","Reason terminal session identity is invalid.");let p=typeof g==="string"?Date.parse(g):Number.NaN;if(!Number.isFinite(p)||p<=n)throw new r("invalid_pty_request","Reason terminal session has already expired.");if(e.cwd!==void 0&&typeof e.cwd!=="string")throw new r("invalid_pty_request","Reason terminal working directory is invalid.");let a=e.workspace===void 0?void 0:te(e.workspace);if(a===null||a&&e.cwd!==void 0)throw new r("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:c,session_id:m,expires_at:new Date(Math.min(p,n+wi)).toISOString(),cols:P(e.cols,80),rows:P(e.rows,24),...e.cwd===void 0?{}:{cwd:e.cwd},...a?{workspace:a}:{}}}function Q(e,n){if(h()==="win32")[e,n]=[e.toLowerCase(),n.toLowerCase()];return n===e||n.startsWith(e+X)}function N(e,n){if(n===void 0)return e;if(!q(n))throw new r("pty_cwd_invalid","Reason terminal working directory must be absolute.");let o;try{o=W(n)}catch{throw new r("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!Q(e,o))throw new r("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!J(o).isDirectory())throw new r("pty_cwd_invalid","Reason terminal working directory is not a directory.");return o}function il(e=process.env){if(h()==="win32")return E(e);let n=e.SHELL;if(n&&q(n)&&D(n))return n;for(let o of h()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(D(o))return o;return"/bin/sh"}function V(){let e=globalThis.Bun;if(!e)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");return e.spawn}function Fo(){if(h()==="win32")return yi();return typeof globalThis.Bun<"u"}var Z=(e)=>{if(h()==="win32")try{return M({...e,file:e.shell,args:C(e.shell),environment:{...e.environment,TERM:"xterm-256color"}})}catch{throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}let n=V()({cmd:[e.shell,"-i","-l"],cwd:e.cwd,env:{...e.environment,TERM:"xterm-256color"},terminal:{cols:e.cols,rows:e.rows,data:(t,c)=>{e.onData(c)}}}),o=n.terminal;if(!o){try{n.kill()}catch{}throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(t)=>o.write(t),resize:(t,c)=>o.resize(t,c),kill:()=>{try{n.kill()}catch{}},exited:n.exited.then((t)=>typeof t==="number"?t:null,()=>null)}},vi=(e,n)=>n===void 0?new WebSocket(e):new WebSocket(e,{proxy:n}),v=new Set;function ee(e){if(v.size>=bi||v.has(e))return null;v.add(e);let n=!1;return()=>{if(n)return;n=!0,v.delete(e)}}async function jo(e,n={}){let o=n.now??Date.now,t=G(e.payload,o()),c=ee(e.operationId);if(!c)throw new r("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let m=o(),g,d,p;try{let a=t.workspace?Ge(e.root,t.workspace):void 0;g=a?N(D(a.boundary)?W(a.boundary):a.boundary,a.path):N(e.root,t.cwd),d=n.environment??process.env,p=n.shellPath??il(d)}catch(a){throw c(),a}return await new Promise((a,b)=>{let w=null,i=null,S=!1,x=!1,y=!1,T=null,U=0,B=0,O=[],R=0,A=null,l=(s)=>{if(y)return;if(y=!0,A)clearTimeout(A);e.signal.removeEventListener("abort",L);try{w?.kill()}catch{}try{i?.close(1000,"pty_session_over")}catch{}if(c(),s.kind==="rejected"){b(s.error);return}let u={reason:s.reason,exit_code:T,output_bytes:U,input_bytes:B,duration_ms:Math.max(0,o()-m)};e.emitEvent("pty.stopped",{...u}).catch(()=>{return}),a({...u})},L=()=>{let s=e.signal.reason;l({kind:"rejected",error:s instanceof r?s:new r("cancelled","Reason closed the terminal session.")})};if(e.signal.aborted){L();return}e.signal.addEventListener("abort",L,{once:!0}),A=setTimeout(()=>l({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(t.expires_at)-o()));let I=(s)=>{if(U+=s.byteLength,!S||!i){if(O.push(s),R+=s.byteLength,R>hn)l({kind:"resolved",reason:"output_backpressure"});return}try{i.send(s)}catch{l({kind:"resolved",reason:"relay_closed"});return}if(i.bufferedAmount>hn)l({kind:"resolved",reason:"output_backpressure"})};try{w=(n.spawnPty??Z)({shell:p,args:["-i","-l"],cwd:g,cols:t.cols,rows:t.rows,environment:d,onData:(s)=>{if(!y)I(s)}})}catch(s){l({kind:"rejected",error:s instanceof r?s:new r("pty_spawn_failed","Reason could not start the terminal shell.")});return}w.exited.then((s)=>{if(y)return;if(T=s,S&&i)try{i.send(JSON.stringify({t:"exit",code:s}))}catch{}l({kind:"resolved",reason:"shell_exited"})});let j=(n.loadProxy??Ee)()?.url;try{i=(n.connect??vi)(t.relay_url,j)}catch{l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}i.binaryType="arraybuffer",i.onopen=()=>{if(y||!i)return;S=!0;try{i.send(JSON.stringify({t:"open",cols:t.cols,rows:t.rows}));for(let s of O.splice(0))i.send(s);R=0}catch{l({kind:"resolved",reason:"relay_closed"});return}x=!0,e.emitEvent("pty.ready",{session_id:t.session_id,cols:t.cols,rows:t.rows}).catch(()=>{return})},i.onmessage=(s)=>{if(y||!w)return;let u=s.data;if(typeof u==="string"){let f;try{f=JSON.parse(u)}catch{return}if(!z(f))return;if(f.t==="resize"){try{w.resize(P(f.cols,t.cols),P(f.rows,t.rows))}catch{}return}if(f.t==="close")l({kind:"resolved",reason:"client_closed"});return}let _=u instanceof ArrayBuffer?new Uint8Array(u):ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):null;if(!_||_.byteLength===0)return;B+=_.byteLength;try{w.write(_)}catch{}},i.onclose=()=>{if(y)return;if(!x){l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}l({kind:"resolved",reason:"relay_closed"})},i.onerror=()=>{if(y||x)return;l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
3
3
  export{yi,wi,hn,bi,il,Fo,vi,jo};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{zi,qi,Wi,Bn}from"./vm-hands-entry-lite-hpw27zfb.js";import{hc,fc,F,ki,xi,Ho,_r,Uo,Ci,qt,_t,zo,Wt,He,Vt,yt,wn,Ai,Pi,Wo}from"./vm-hands-entry-lite-bc9zq8gx.js";import{zn}from"./vm-hands-entry-lite-h7f5a5mb.js";import{_n}from"./vm-hands-entry-lite-dh87ysh2.js";import{vt}from"./vm-hands-entry-lite-hpe54h0b.js";var r=["cgroup_membership_read_failed","cgroup_v2_membership_absent","cgroup_scope_invalid","cgroup_root_unavailable","cgroup_directory_unavailable","cgroup_limit_read_failed","cgroup_events_read_failed","cgroup_current_read_failed","cgroup_stat_read_failed","boot_id_read_failed","boot_id_invalid","guest_meminfo_read_failed","guest_vmstat_read_failed","memory_counter_invalid","memory_field_missing","memory_capacity_invalid"];var o=String.raw`(function(fs, path) {
2
+ import{zi,qi,Wi,Bn}from"./vm-hands-entry-lite-hpw27zfb.js";import{hc,fc,F,ki,xi,Ho,_r,Uo,Ci,qt,_t,zo,Wt,He,Vt,yt,wn,Ai,Pi,Wo}from"./vm-hands-entry-lite-n6q8033g.js";import{zn}from"./vm-hands-entry-lite-h7f5a5mb.js";import{_n}from"./vm-hands-entry-lite-dh87ysh2.js";import{vt}from"./vm-hands-entry-lite-hpe54h0b.js";var r=["cgroup_membership_read_failed","cgroup_v2_membership_absent","cgroup_scope_invalid","cgroup_root_unavailable","cgroup_directory_unavailable","cgroup_limit_read_failed","cgroup_events_read_failed","cgroup_current_read_failed","cgroup_stat_read_failed","boot_id_read_failed","boot_id_invalid","guest_meminfo_read_failed","guest_vmstat_read_failed","memory_counter_invalid","memory_field_missing","memory_capacity_invalid"];var o=String.raw`(function(fs, path) {
3
3
  const fail = (message, reasonCode) => { throw Object.assign(Error(message), {reasonCode}); };
4
4
  const read = (p, reasonCode, trim=true) => { try { const text=fs.readFileSync(p, "utf8"); return trim?text.trim():text; }
5
5
  catch { fail("memory_read", reasonCode); } };
@@ -0,0 +1,10 @@
1
+ // @bun
2
+ import{oo}from"./vm-hands-entry-lite-39anhpg6.js";import{spawnSync as d}from"child_process";import{createHash as ge}from"crypto";import{chmodSync as de,closeSync as pe,existsSync as w,linkSync as me,lstatSync as he,mkdirSync as Q,mkdtempSync as we,openSync as ye,readdirSync as Ee,readFileSync as ke,readSync as Ne,realpathSync as Se,renameSync as k,rmSync as N,statSync as Y,symlinkSync as W,writeFileSync as C}from"fs";import{connect as be}from"net";import{homedir as f}from"os";import{basename as Z,dirname as v,join as u}from"path";import{inflateRawSync as _e}from"zlib";var oe=new Set(["<","\u02C2","\u1438","\u2039","\u3008","\u276C","\u276E","\u2770","\u16B2","\u2D66","\uD800\uDF2D","\uD81A\uDEEC","\uD834\uDE36","\u27E8","\u27EA","\u29FC","\u3008","\u300A","\uFE64","\uFF1C"]),D=(e)=>e===" "||e==="\t"||e===`
3
+ `||e==="\f"||e==="\r",ie=(e)=>e.length===1&&e>="!"&&e<="~",J=(e)=>e.length===1&&/[A-Za-z]/.test(e);function U(e){let n=Array.from(e),t=(r)=>{let s=r+Math.min(n.length-r,64),o=r;while(o<s&&(D(n[o])||n[o]==="/"))o+=1;let i=o-r,a=[];while(o<s&&!D(n[o])&&n[o]!==">"&&n[o]!=="\uFF1E")a.push(n[o++]);return i+a.length===s-r&&n.length-r>64||!a.every(ie)||ae(a)};return n.map((r,s)=>oe.has(r)&&t(s+1)?"[":r).join("")}function ae(e){let n=1;for(let t of e){let r=t==="0"?"o":t==="3"?"e":t==="4"||t==="@"?"a":t==="5"||t==="$"?"s":J(t)?t.toLowerCase():t,s="reason".indexOf(r),o=s<0?0:1<<s;if(n=1|(J(t)?0:n)|(n&o)<<1,n&64)return!0}return!1}var ce=/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g;function j(e){return U(e.replace(ce," ").replace(/[\u2028\u2029]/g," "))}var le=["CLAUDECODE","CLAUDE_CODE_SESSION_ID","CODEX_THREAD_ID","CODEX_SESSION_ID","GROK_SESSION_ID","GROK_WORKSPACE_ROOT","GEMINI_CLI","CURSOR_AGENT","OPENCODE","COPILOT_CLI","COPILOT_AGENT_SESSION_ID","AI_AGENT"];function ue(e=process.env,n=Boolean(process.stderr.isTTY)){let t=le.some((r)=>e[r]!==void 0)||Object.keys(e).some((r)=>r.startsWith("CODEX_SANDBOX"))||Boolean(e.REASON_NETWORK_AGENT)||Boolean(e.TINCAN_AGENT);return n&&!t}function Fe(e,n=ue()){return n?e:j(e)}class fe extends Error{}var m="reason-network",p="0.12.11",Re={"aarch64-apple-darwin":"4626279ee457d15566bcee47ba11ce270d545bd1137c48208e0df3878606197b","x86_64-apple-darwin":"17ea926bce47913882c7b3ba0ae42d03694a7720518ee726e4ae3028bb293f62","aarch64-unknown-linux-musl":"3bc31d0db0263ac27020ac4598415e3e16cfb672d6a9a9ca093775d300ef4fc2","x86_64-unknown-linux-musl":"0ab91ac33af6704f4836bbedc5b55bed4b0a9fdfdc8da1a1d16db8a07d2fc1c4","aarch64-pc-windows-msvc":"91c4c06ebbae929af5494efe9b506b6abc8bdd2989c5d246515bc5133932e5bd","x86_64-pc-windows-msvc":"ff01324b27ebcac0f698df59d2fdc8ef6e3094ead09210c6fa39238cd4cdbee7"},ve="https://reasonmachines.com/cli/engine",S="REASON_AGENT_NETWORK_BIN";function $e(e=process.platform,n=process.arch){let t=n==="arm64"?"aarch64":n==="x64"?"x86_64":null,r=e==="darwin"?"apple-darwin":e==="linux"?"unknown-linux-musl":e==="win32"?"pc-windows-msvc":null;return t&&r?`${t}-${r}`:null}function ee(e){return`${m}-${e}${e.endsWith("-windows-msvc")?".zip":".tar.gz"}`}function xe(e){let n=Re[e];return n?{url:`${ve}/${p}/${ee(e)}`,sha256:n}:null}function A(e){let n=d(e,["--version"],{encoding:"utf8",timeout:5000}),[t,r]=n.status===0?n.stdout.trim().split(/\s+/):[];return t===m?r??null:null}function R(e,n){let t=e.split(".").map(Number),r=n.split(".").map(Number);for(let s=0;s<3;s+=1)if((t[s]??0)!==(r[s]??0))return(t[s]??0)>(r[s]??0);return!0}function b(e=f(),n=process.platform){return u(e,".reason","bin",`${m}${n==="win32"?".exe":""}`)}var x=process.platform==="win32"?`~\\.local\\bin\\${m}.exe`:`~/.local/bin/${m}`;async function Pe(e=process.env,n=()=>{}){if(e[S])return e[S];let t=b(),r=P(),s=r?.path===t&&E(t)===r.fingerprint?r:null,o=s?.kept,i=G(e)?null:Oe(o);if(s?.version===p&&!i)return t;let a=w(t)?A(t):null;if(i){let c=A(i.path),g=a&&R(a,p)?a:p;if(!c||!R(g,c)){if(c)n(`Reason Network: ${x} (${c}) is newer than the version \`reason network\` keeps up to date (${g}), so it was left as it is.`);o=i.fingerprint,i=null}}if(s?.version===p&&!i)return H(t,o);if(!a||!R(a,p))await ne(t);let l=d(t,["setup",...G(e)?["--no-service"]:[]],{env:await M(e),encoding:"utf8",timeout:60000});if(l.status!==0){let c=_((l.stderr||l.stdout||"").trim().split(`
4
+ `).pop()??"");if(s)return B(f(),{...s,fingerprint:E(t)??s.fingerprint,...o?{kept:o}:{}}),n(i?`Reason Network: couldn't move your agents off ${x}${c?` (${c})`:""}; they keep using it. Run reason network to try again.`:`Reason Network: couldn't finish setting up on this computer${c?` (${c})`:""}. Run reason network to try again.`),t;throw new fe(`Couldn't connect this computer's agents to the network${c?` (${c})`:""}. Run reason network to try again.`)}if(i)o=Te(i,t,n);return H(t,o),d(t,["stop"],{env:e,stdio:"ignore",timeout:15000}),t}function Oe(e){let n=u(f(),".local","bin",Z(b())),t;try{t=he(n)}catch{return null}let r=`${t.size}:${t.mtimeMs}:${t.ino}`;if(!t.isFile()||r===e)return null;try{let s=Y(b());if(s.ino===t.ino&&s.dev===t.dev)return null}catch{}try{let s=Buffer.alloc(2),o=ye(n,"r");try{Ne(o,s,0,2,0)}finally{pe(o)}if(s.toString("latin1")==="#!")return null}catch{return null}return{path:n,fingerprint:r}}function Te(e,n,t){let r=`${e.path}.reason-${process.pid}`;try{if(N(r,{force:!0}),process.platform==="win32"){try{W(n,r,"file")}catch{me(n,r)}te(r,e.path,"win32")}else W(n,r),k(r,e.path);t(`Reason Network: your agents on this computer now use the version \`reason network\` keeps up to date (${x} points to it). Restart a running agent to pick it up.`);return}catch(s){return N(r,{force:!0}),t(`Reason Network: your agents on this computer now use the version \`reason network\` keeps up to date, but ${x} couldn't be pointed to it (${s instanceof Error?s.message:String(s)}). Remove that copy so it can't take them back.`),e.fingerprint}}async function fl(e={}){let n=e.env??process.env,t=e.home??f(),r=b(t),s=P(t);if(n[S]||s?.path!==r||E(r)!==s.fingerprint)return!1;if(s.version===p)return!1;let o=A(r);if(o&&R(o,p))return!1;return await ne(r),B(t,{...s,fingerprint:E(r)??""}),e.beforeRestart?.(),d(r,["stop"],{env:n,stdio:"ignore",timeout:15000}),!0}async function M(e){if(e[F])return e;try{let{defaultWorkerServiceHost:n,workerServiceLauncher:t}=await import("./serve-service-cdfwh6pg.js");return{...e,[F]:t(n(f()),e)}}catch{return e}}var F="REASON_NETWORK_REASON_BIN";function G(e=process.env){return Boolean(e.REASON_NETWORK_NO_SERVICE||e.TINCAN_NO_SERVICE)}var L=(e)=>u(e,".reason","ask-engine.json");function E(e){try{let n=Y(e);return`${n.size}:${n.mtimeMs}:${n.ino}`}catch{return null}}function ml(e=f()){return P(e)?.version??null}function P(e=f()){try{let n=JSON.parse(ke(L(e),"utf8"));if(typeof n.path!=="string"||typeof n.fingerprint!=="string"||typeof n.version!=="string")return null;return{path:n.path,fingerprint:n.fingerprint,version:n.version,...typeof n.kept==="string"?{kept:n.kept}:{}}}catch{return null}}function B(e,n){Q(v(L(e)),{recursive:!0}),C(L(e),JSON.stringify(n))}function H(e,n){let t=E(e);if(t)B(f(),{path:e,fingerprint:t,version:p,...n?{kept:n}:{}});return e}async function ne(e){let n=$e(),t=n?xe(n):null;if(!n||!t)throw new fe(`Reason Network runs on macOS, Linux and Windows (arm64 or x64); this is ${process.platform} ${process.arch}.`);let{url:r,sha256:s}=t,o;try{let a=await fetch(r,{signal:AbortSignal.timeout(120000)});if(!a.ok)throw Error(`HTTP ${a.status}`);o=Buffer.from(await a.arrayBuffer())}catch(a){let l=a instanceof Error&&a.name==="TimeoutError"?"no download within 2 minutes":a instanceof Error?a.message.replace(/\.$/,""):String(a);throw new fe(`Couldn't download Reason Network from ${new URL(r).host} (${l}). Check the connection and run reason network again.`)}if(ge("sha256").update(o).digest("hex")!==s)throw new fe("The Reason Network download didn't match its checksum, so it wasn't installed.");Ie(o,n,e)}var K="Couldn't unpack the Reason Network download.";function Ie(e,n,t,r=process.platform){Q(v(t),{recursive:!0});let s=we(u(v(t),".reason-engine-"));try{let o=u(s,m);if(ee(n).endsWith(".zip"))o=u(s,`${m}.exe`),C(o,Ce(e,`${m}.exe`));else{C(u(s,"engine.tar.gz"),e);let i=d("tar",["--no-same-owner","-xzf",u(s,"engine.tar.gz"),"-C",s],{encoding:"utf8"});if(i.status!==0||!w(o)){let a=(i.stderr??"").trim().split(`
5
+ `).slice(-3).join("; "),l=i.error?`tar failed: ${i.error.message}`:i.signal?`tar was stopped by ${i.signal}`:i.status!==0?`tar exited ${i.status}${a?`: ${a}`:""}`:`no ${m} in it`;throw new fe(`Couldn't unpack the Reason Network download (${l}).`)}}de(o,493),te(o,t,r)}finally{N(s,{recursive:!0,force:!0})}}function Ce(e,n){let t=e.lastIndexOf(Buffer.from("PK\x05\x06","latin1"));if(t<0||t+22>e.length)throw new fe(K);let r=e.readUInt32LE(t+16);for(let s=e.readUInt16LE(t+10);s>0;s-=1){if(r+46>e.length||e.readUInt32LE(r)!==33639248)break;let o=e.readUInt16LE(r+28);if(e.toString("utf8",r+46,r+46+o)===n){let i=e.readUInt16LE(r+10),a=e.readUInt32LE(r+20),l=e.readUInt32LE(r+24),c=e.readUInt32LE(r+42);if(c+30>e.length||e.readUInt32LE(c)!==67324752)break;let g=c+30+e.readUInt16LE(c+26)+e.readUInt16LE(c+28);if(g+a>e.length)break;let h=e.subarray(g,g+a),O;try{O=i===0?Buffer.from(h):i===8?_e(h):Buffer.alloc(0)}catch{break}if(i!==0&&i!==8||O.length!==l)break;return O}r+=46+o+e.readUInt16LE(r+30)+e.readUInt16LE(r+32)}throw new fe(K)}function te(e,n,t){if(t!=="win32"||!w(n)){k(e,n);return}let r=v(n),s=(i)=>i.startsWith(`${Z(n)}.`)&&i.endsWith(".old");for(let i of Ee(r).filter(s))try{N(u(r,i),{force:!0})}catch{}let o=`${n}.${process.pid}-${Date.now()}.old`;k(n,o);try{k(e,n)}catch(i){throw k(o,n),i}try{N(o,{force:!0})}catch{}}function Ae(e=process.env,n=f()){let t=e.REASON_NETWORK_HOME?.trim()||e.TINCAN_HOME?.trim();if(t)return t;let r=u(n,".reason","network"),s=u(n,".tincan");return!z(r)&&z(s)?s:r}var z=(e)=>w(u(e,"network.db"))||w(u(e,"tincan.db"));function Me(e,n=process.platform,t=Se.native){let r=w(u(e,"network.db"))||!w(u(e,"tincan.db"));if(n==="win32"){let o=e;try{o=t(e),o=o.startsWith("\\\\?\\")?o.slice(4):o.startsWith("\\\\")?`UNC\\${o.slice(2)}`:o}catch{}return`\\\\.\\pipe\\${r?"reason-network":"tincan"}-${V(o)}`}let s=u(e,r?"network.sock":"tincan.sock");if(Buffer.byteLength(s)<100)return s;return u("/tmp",`${r?"reason-network":"tincan"}-${process.getuid?.()??0}`,`${V(s)}.sock`)}function V(e){let n=0xcbf29ce484222325n;for(let t of Buffer.from(e))n=BigInt.asUintN(64,(n^BigInt(t))*0x100000001b3n);return n.toString(16).padStart(16,"0")}class Xr extends Error{code;constructor(e,n){super(e);this.code=n}}function Qi(e){return e instanceof Xr&&/isn't registered/.test(e.message)}var re="not_in_team",se=15000,Ge=new Set(["who","team","inbox","unread","held"]),Le=90000,Be="Reason Network on this computer closed the connection";class y{socket;nextId=1;buffer="";pending=new Map;closed=null;hungUp=!1;constructor(e){this.socket=e;e.setEncoding("utf8"),e.on("data",(t)=>this.read(t));let n=(t)=>{this.closed=t;for(let r of this.pending.values())r.reject(t);this.pending.clear()};e.on("error",(t)=>n(t)),e.on("close",()=>n(Error(this.hungUp?"the connection to Reason Network on this computer was closed here":Be)))}static open(e){return new Promise((n,t)=>{let r=be(e);r.once("connect",()=>n(new y(r))),r.once("error",t)})}read(e){this.buffer+=e;let n=this.buffer.indexOf(`
6
+ `);while(n>=0){let t=this.buffer.slice(0,n);if(this.buffer=this.buffer.slice(n+1),n=this.buffer.indexOf(`
7
+ `),!t.trim())continue;let r;try{r=JSON.parse(t)}catch{continue}if(typeof r.id!=="number")continue;let s=this.pending.get(r.id);if(!s)continue;if(this.pending.delete(r.id),r.ok){s.resolve(r.result);continue}let o=r.error??"Reason Network on this computer refused the request",i=typeof r.code==="string"?r.code:/not (in|connected to) a team/i.test(o)?re:null;s.reject(new Xr(_(o),i))}}call(e,n={},t=se){if(this.closed)return Promise.reject(this.closed);let r=this.nextId++;return this.socket.write(`${JSON.stringify({id:r,op:e,...n})}
8
+ `),new Promise((s,o)=>{let i=setTimeout(()=>{this.pending.delete(r),o(Error(`Reason Network on this computer didn't answer ${e} within ${Math.round(t/1000)}s`))},t);this.pending.set(r,{resolve:(a)=>{clearTimeout(i),s(a)},reject:(a)=>{clearTimeout(i),o(a)}})})}get isClosed(){return this.closed!==null}close(){this.hungUp=!0,this.socket.end()}}var T=/^(Claude Code|Grok|Codex) \u00B7 (.*)$/,De={"Claude Code":"claude-code",Grok:"grok",Codex:"codex"},Je=/^ask-[0-9a-f]{6}$/;function q(e){return{id:e.id,from:e.from,fromAgent:e.from_agent,to:e.to,replyTo:e.reply_to,body:e.body,sentAt:e.sent_at}}function X(e){return{person:e.person,machine:e.machine,isMe:e.is_me,online:e.online,link:e.link,rttMs:e.rtt_ms}}class Nt{engine;env;connection=null;connectionOpening=null;generation=0;waits=new Set;constructor(e,n){this.engine=e;this.env=n}static async open(e=process.env,n){let t=new Nt(await Pe(e,n),e);try{return await t.getConnection(),t}catch(r){throw t.close(),r}}static openInstalled(e=process.env){if(e[S])return new Nt(e[S],e);let n=b(),t=P();return t?.path===n&&E(n)===t.fingerprint?new Nt(n,e):null}socketPath(){return Me(Ae(this.env))}assertGeneration(e){if(e!==this.generation)throw Error("the connection to Reason Network on this computer was closed here")}async open(e){let n;try{return await y.open(this.socketPath())}catch(s){n=s,this.assertGeneration(e)}let t=d(this.engine,["who","--json"],{env:this.env,encoding:"utf8",timeout:15000});if(t.status===0&&!t.error)try{return await y.open(this.socketPath())}catch(s){n=s}this.assertGeneration(e),await this.setupAgentsForRecovery(e),this.assertGeneration(e);let r=d(this.engine,["who","--json"],{env:this.env,encoding:"utf8",timeout:15000});if(r.status!==0||r.error)throw new fe(`Couldn't start Reason Network on this computer${I(r)}${r.error?` (${r.error.message})`:""}.`);try{return await y.open(this.socketPath())}catch(s){throw new fe(`Couldn't connect to Reason Network on this computer (${String(s||n)}).`)}}async getConnection(){if(this.connection&&!this.connection.isClosed)return this.connection;if(this.connectionOpening)return this.connectionOpening;let e=this.generation,n=this.open(e).then((t)=>{if(e!==this.generation)throw t.close(),Error("the connection to Reason Network on this computer was closed here");return this.connection=t,t}).finally(()=>{if(this.connectionOpening===n)this.connectionOpening=null});return this.connectionOpening=n,n}async call(e,n={},t){let r=this.generation,s=await this.getConnection();this.assertGeneration(r);try{return await s.call(e,n,t)}catch(o){if(this.assertGeneration(r),!/closed|ECONNRESET|EPIPE/.test(String(o)))throw o;if(s=await this.getConnection(),this.assertGeneration(r),!Ge.has(e))throw o;return await s.call(e,n)}}async waitOn(e,n){let t=this.generation;await this.getConnection(),this.assertGeneration(t);let r=await y.open(this.socketPath());if(t!==this.generation)throw r.close(),Error("the connection to Reason Network on this computer was closed here");this.waits.add(r);try{return await r.call(e,n,n.wait_secs*1000+se)}finally{this.waits.delete(r),r.close()}}closeConnections(){this.connection?.close(),this.connection=null;for(let e of this.waits)e.close();this.waits.clear()}close(){this.generation+=1,this.connectionOpening=null,this.closeConnections()}async team(){try{let{team_id:e,messages:n,...t}=await this.call("team"),r=t.machines.find((o)=>o.is_me)?.endpoint,s=Array.isArray(n)?n.flatMap((o)=>{let i=oo.safeParse(o);return i.success?[i.data]:[]}):null;return{...t,...typeof e==="string"&&e?{teamId:e}:{},machines:t.machines.map(X),...typeof r==="string"&&r?{endpoint:r}:{},...s?{messageCounts:s}:{}}}catch(e){if(e instanceof Xr&&e.code===re)return null;throw e}}async snapshot(e={}){let n=await this.call("who",{all:Boolean(e.all),...e.filter?{filter:e.filter}:{}}),t=new Set(n.sessions.filter((s)=>T.test(s.doing??"")).map((s)=>`${s.person}/${s.machine}:${s.cwd}`)),r=n.sessions.filter((s)=>e.all||!Je.test(s.name)).filter((s)=>T.test(s.doing??"")||!t.has(`${s.person}/${s.machine}:${s.cwd}`)).map((s)=>{let o=T.exec(s.doing??"");return{address:s.address,name:s.name,person:s.person,machine:s.machine,agent:o?De[o[1]]:s.agent,cwd:s.cwd,repo:s.repo,branch:s.branch,status:o?o[2]==="ready for work"?"idle":o[2]==="stopped"?"offline":"busy":s.status,since:s.since,doing:o?o[2]:s.doing,isMe:s.is_me,worker:Boolean(o),tier:s.tier??null}});return{team:n.team,person:n.person,machine:n.machine,machines:n.machines.map(X),sessions:r}}async send(e,n,t={}){if(!t.from)await this.call("hook",{agent:"cli",event:"stop",session_id:"terminal",name:"terminal",cwd:process.cwd(),mail:!1});let r=await this.call("send",{from:t.from??"cli:terminal",to:e,body:n,...t.replyTo?{reply_to:t.replyTo}:{},wake:t.wake??!0,...t.notify?{notify:!0}:{}});return{ids:r.ids,recipients:r.recipients.map((s)=>s.address),deliveries:r.recipients.map((s)=>({address:s.address,state:s.state,note:s.note??""}))}}async session(e,n={}){let t=n.agent??"cli",r=(a,l={})=>this.call("hook",{agent:t,event:a,session_id:e,name:e,cwd:process.cwd(),mail:!1,...l}),s=await r("stop"),o=`${t}:${e}`,i=s.address??e;return{name:e,get address(){return i},next:async(a)=>(await this.waitOn("inbox",{key:o,wait_secs:a,peek:!0})).messages.map(q),ack:async(a)=>{if(a.length)await this.call("delivered",{key:o,ids:a})},busy:async(a)=>{if(await r("prompt"),a)await r("doing",{doing:a})},idle:async(a)=>{if(await r("stop"),a)await r("doing",{doing:a})},doing:async(a)=>{await r("doing",{doing:a})},end:async()=>{await r("end")},rename:async(a)=>{i=(await this.call("set_status",{key:o,name:a})).address},send:(a,l,c,g)=>this.send(a,l,{from:o,...c?{replyTo:c}:{},...g?.notify?{notify:!0}:{}})}}async inbox(e={}){let t=(await this.waitOn("inbox",{key:"cli:terminal",wait_secs:e.waitSeconds??0,peek:!0}).catch((r)=>{if(/isn't registered/.test(String(r)))return{messages:[]};throw r})).messages.map(q);if(t.length&&!e.peek)await this.call("delivered",{key:"cli:terminal",ids:t.map((r)=>r.id)});return t}async link(e={}){return await this.call("link",{new:Boolean(e.new)})}async changeTeam(e,n){try{return await this.call(e,n,Le)}finally{this.close()}}async changeOntoTeam(e,n){try{await this.changeTeam(e,n)}catch(t){if(!/closed|ECONNRESET|EPIPE/.test(String(t)))throw t;if(await this.team())return;await this.changeTeam(e,n)}}async createTeam(e,n){await this.changeOntoTeam("create_team",{name:e,person:n})}async join(e,n){await this.changeOntoTeam("join",{ticket:e,person:n})}async leave(){return await this.changeTeam("leave",{force:!0})}async remove(e){return await this.call("remove",{who:e})}endpoint(){let e=d(this.engine,["endpoint"],{encoding:"utf8",env:this.env,timeout:30000}),n=e.status===0?e.stdout.trim():"";if(!n)throw new fe(`Reason Network on this computer couldn't say its endpoint${I(e)}.`);return n}async enterTeam(e,n,t){let r=t?{proof:t}:{},[s,o]="create"in e?["create_team",{name:e.create,person:n,...r}]:["join",{ticket:e.join,person:n,...r}],i=null;for(let a=0;a<2&&!i?.person;a+=1)try{i=await this.changeTeam(s,o)}catch(l){let c=String(l),g=l instanceof Xr&&l.code?l.code:/\(same_account_needs_owner\)/.test(c)?"same_account_needs_owner":/already in this team/.test(c)?"name_taken":null;if(g==="same_account_needs_owner")return{state:"needs_owner"};if(g==="name_taken")return{state:"name_taken"};if(!/closed|ECONNRESET|EPIPE/.test(c))throw l;let h=await this.team();if(h)i={name:h.name,person:h.person,machine:h.machine}}if(!i?.person)throw new fe("Reason Network on this computer didn't join the team. Run reason network again.");return{state:"entered",teamId:i.team_id??"",teamName:i.team_name||i.name||"",person:i.person??n,machine:i.machine??""}}async setupAgents(){return this.close(),this.runSetupAgents()}async setupAgentsForRecovery(e){this.assertGeneration(e),this.closeConnections(),await this.runSetupAgents(e)}async runSetupAgents(e){let n=await M(this.env);if(e!==void 0)this.assertGeneration(e);let t=d(this.engine,["setup",...G(this.env)?["--no-service"]:[]],{encoding:"utf8",env:n,timeout:60000});if(t.status!==0||t.error)throw new fe(`Couldn't connect this computer's agents to the network${I(t)}${t.error?` (${t.error.message})`:""}.`);return[...(t.stdout??"").matchAll(/^ {2}([^:\n]+): (?!skipped)/gm)].map((r)=>r[1]).filter((r)=>r!=="service")}async setup(e,n={}){return this.passthrough(["setup",...e],n,await M(this.env))}passthrough(e,n={},t=this.env){this.close();let r=d(this.engine,e,{stdio:["inherit","pipe",n.person?"inherit":"pipe"],encoding:"utf8",env:t});if(!n.quiet||r.status!==0)process.stdout.write(Fe(_(r.stdout??""))),process.stderr.write(Fe(_(r.stderr??"")));return r.status??1}}function I(e){let n=_(((e.stderr||e.stdout)??"").trim().split(`
9
+ `).pop()??"");return n?` (${n})`:""}function _(e){return e.replace(/not in a team yet:[^\n]*/g,"this computer isn't on a network yet: run `reason network`").replace(/`tincan (\w+)/g,"`reason network $1").replace(/\btincan (who|send|inbox|invite|join|team|link|setup|doctor|remove|leave|listen)\b/g,"reason network $1").replace(/(?<![\w./-])tincan(?![\w./-])/gi,"Reason Network")}
10
+ export{Fe,fe,fl,ml,Xr,Qi,Nt};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{R}from"./vm-hands-entry-lite-ys4jhf7n.js";import{w}from"./vm-hands-entry-lite-0xfme8gg.js";import{ot,cs,Mi,We}from"./vm-hands-entry-lite-8twdd0ff.js";import{ms,$n,jc}from"./vm-hands-entry-lite-tv5mcw97.js";import{B}from"./vm-hands-entry-lite-04nx5y4f.js";import{spawnSync as v}from"child_process";import{createHash as Se,randomUUID as we}from"crypto";import{chmodSync as $e,existsSync as T,mkdirSync as ye,readdirSync as Fe,readFileSync as p,renameSync as ve,rmSync as u,statSync as be,writeFileSync as Ae}from"fs";import{dirname as xe,isAbsolute as q,join as g}from"path";import{spawnSync as ue}from"child_process";import{readFileSync as me}from"fs";import{userInfo as O}from"os";import{join as fe}from"path";var ge="REASON_SCHEDULED_TASK";function Ni(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 D(r){if(!/^[A-Za-z0-9._-]+$/.test(r))throw Error(`Invalid Windows Scheduled Task name: ${r}`);return`$env:${ge}=${S(r)};`}function H(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[D(r.name),...e,"$ErrorActionPreference='Continue';",r.keepAlive?`do { ${n} if ($c) { Start-Sleep -Seconds 10 } } while ($c)`:`${n} exit $c`].join(" ")}function I(r){return r.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function pe(){let r=process.env.USERDOMAIN?.trim();return r?`${r}\\${O().username}`:O().username}function M(r){let e=I(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{R}from"./vm-hands-entry-lite-ys4jhf7n.js";import{w}from"./vm-hands-entry-lite-a4fn6ye1.js";import{ot,cs,Mi,We}from"./vm-hands-entry-lite-yqzy5wp8.js";import{ms,$n,jc}from"./vm-hands-entry-lite-qb0tvsw7.js";import{B}from"./vm-hands-entry-lite-04nx5y4f.js";import{spawnSync as v}from"child_process";import{createHash as ke,randomUUID as Se}from"crypto";import{chmodSync as we,existsSync as T,mkdirSync as $e,readdirSync as Fe,readFileSync as p,renameSync as ye,rmSync as u,statSync as ve,writeFileSync as be}from"fs";import{dirname as Ae,isAbsolute as q,join as g}from"path";import{spawnSync as ue}from"child_process";import{readFileSync as me}from"fs";import{userInfo as O}from"os";import{join as fe}from"path";var ge="REASON_SCHEDULED_TASK";function Ni(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 D(r){if(!/^[A-Za-z0-9._-]+$/.test(r))throw Error(`Invalid Windows Scheduled Task name: ${r}`);return`$env:${ge}=${S(r)};`}function H(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[D(r.name),...e,"$ErrorActionPreference='Continue';",r.keepAlive?`do { ${n} if ($c) { Start-Sleep -Seconds 10 } } while ($c)`:`${n} exit $c`].join(" ")}function I(r){return r.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function pe(){let r=process.env.USERDOMAIN?.trim();return r?`${r}\\${O().username}`:O().username}function M(r){let e=I(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>${I(r.description)}</Description>
@@ -42,12 +42,12 @@ import{R}from"./vm-hands-entry-lite-ys4jhf7n.js";import{w}from"./vm-hands-entry-
42
42
  `)}function V(r,e){return["/Create","/TN",r,"/XML",e,"/F"]}function x(r){return["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(r,"utf16le").toString("base64")]}function E(r){return`'*${D(r).replaceAll("'","''")}*'`}function _(r,e){return x(["$all = @(Get-CimInstance Win32_Process)",`$wrappers = @($all | ? { $_.ProcessId -ne $PID -and $_.CommandLine -like ${E(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 x(["$all = @(Get-CimInstance Win32_Process)",`$wrappers = @($all | ? { $_.ProcessId -ne $PID -and $_.CommandLine -like ${E(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=ue(B("powershell.exe"),x(["$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 ${E(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 ke="REASON_WORKER_SERVICE",Ee="worker_identity_unavailable";function de(r){return{platform:process.platform,home:r,uid:process.getuid?.(),command:(e,n)=>v(B(e),[...n],{stdio:"ignore"}).status??1,read:(e,n)=>{let t=v(B(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)=>jc(r,e),insideService:(e,n)=>_e(e,process.platform,process.getuid?.(),n)}}function _e(r,e,n,t=!0){if(process.env[ke]===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=v("/bin/launchctl",["print",`gui/${n}/${r}`],{encoding:"utf8",timeout:5000});if(i.status===Te)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=v("/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 Te=113;class j extends Error{code;constructor(r,e){super(r);this.code=e}}function ze(r,e){if(!ee(r.home,r.platform))throw new j(Q);if(r.platform==="darwin")k(r);let n=We(ot(e,r.home)),t=w({env:e})==="staging",i=t?"ara-staging":"ara",s=[n?cs(n):null,R(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)&&be(a).isFile())return Mi(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 P=/(<key>ProgramArguments<\/key>\s*<array>\n)((?:\s*<string>[^<]*<\/string>\n)*)(\s*<\/array>)/,y=new RegExp(`(\\n\\s*<key>${$n}</key>\\s*<string>)[^<]*(</string>)`),Pe=/(<key>EnvironmentVariables<\/key>\s*<dict>[\s\S]*?)(\n\s*<\/dict>)/;function Re(r){return r.replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&amp;","&")}function Y(r){let e=[...(P.exec(r)?.[2]??"").matchAll(/<string>([^<]*)<\/string>/g)].map((t)=>Re(t[1])),n=e[1]==="--run-worker"?e.slice(2):e;return n[0]?{launcher:n[0],args:n.slice(1)}:null}function J(r,e,n){let t=n.workerIdentity?.(r)??null;return{program:t?[t.executable,"--run-worker",r,...e]:[r,...e],identity:t}}function C(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 xe="REASON_WORKER_SERVICE",Ee="worker_identity_unavailable";function de(r){return{platform:process.platform,home:r,uid:process.getuid?.(),command:(e,n)=>v(B(e),[...n],{stdio:"ignore"}).status??1,read:(e,n)=>{let t=v(B(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)=>jc(r,e),insideService:(e,n)=>_e(e,process.platform,process.getuid?.(),n)}}function _e(r,e,n,t=!0){if(process.env[xe]===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=v("/bin/launchctl",["print",`gui/${n}/${r}`],{encoding:"utf8",timeout:5000});if(i.status===Te)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=v("/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 Te=113;class j extends Error{code;constructor(r,e){super(r);this.code=e}}function ze(r,e){if(!ee(r.home,r.platform))throw new j(Q);if(r.platform==="darwin")k(r);let n=We(ot(e,r.home)),t=w({env:e})==="staging",i=t?"ara-staging":"ara",s=[n?cs(n):null,R(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 Mi(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 P=/(<key>ProgramArguments<\/key>\s*<array>\n)((?:\s*<string>[^<]*<\/string>\n)*)(\s*<\/array>)/,y=new RegExp(`(\\n\\s*<key>${$n}</key>\\s*<string>)[^<]*(</string>)`),Pe=/(<key>EnvironmentVariables<\/key>\s*<dict>[\s\S]*?)(\n\s*<\/dict>)/;function Re(r){return r.replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&amp;","&")}function Y(r){let e=[...(P.exec(r)?.[2]??"").matchAll(/<string>([^<]*)<\/string>/g)].map((t)=>Re(t[1])),n=e[1]==="--run-worker"?e.slice(2):e;return n[0]?{launcher:n[0],args:n.slice(1)}:null}function J(r,e,n){let t=n.workerIdentity?.(r)??null;return{program:t?[t.executable,"--run-worker",r,...e]:[r,...e],identity:t}}function C(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)?Mi(t.launcher):t.launcher,{program:s,identity:a}=J(i,t.args,e),o=n.replace(P,(l,c,m,L)=>`${c}${C(s)}
47
47
  ${L}`);if(!a)o=o.replace(y,"");else if(y.test(o))o=o.replace(y,(l,c,m)=>`${c}${d(a.app)}${m}`);else o=o.replace(Pe,(l,c,m)=>`${c}
48
48
  <key>${$n}</key>
49
- <string>${d(a.app)}</string>${m}`);return o===n?null:o}function Ce(r,e){let n=z(r,e);if(n!==null)A(r,n)}function is(r,e,n){if(e.platform!=="darwin")return!1;let t=qe(r,e,n);return t!==null&&z(t.definition,e)!==null}var W="com.reasonmachines.worker.",h="so.reason.worker.",Z=[W,h];function kn(r,e=W){return`${e}connect${r==="production"?"":`.${r}`}`}function os(r,e){return Z.some((n)=>r===kn(e,n))}function he(r,e,n){if(e==="connect")return kn(r.channel,n);let t=Se("sha256").update(r.workspaceRoot).digest("hex").slice(0,8);return`${n}${r.name.toLowerCase()}.${t}`}var Q="A background service needs macOS (launchd), Linux (systemd --user) or Windows (Task Scheduler).";function ee(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:Ni(r),suffix:".xml"};return null}function f(r,e,n,t=W){let i=he(r,n,t),s=ee(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 qe(r,e,n="serve"){return re(r,e,n)[0]??null}function re(r,e,n){return Z.map((t)=>f(r,e,n,t)).filter((t)=>t!==null&&T(t.definition))}function ne(r,e,n){let t=f(r,e,n,h);return t&&T(t.definition)?t:null}function Li(r,e,n){let t=f(r,e,n),i=ne(r,e,n);if(!t||!i||!T(t.definition)||e.insideService?.(i.label))return null;if(!Ne(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 b(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 Ne(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&&Le.has(e.read("systemctl",["--user","show","--property=ActiveState","--value",n])?.trim()??"")}var Le=new Set(["active","activating","reloading"]);function $i(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 ss(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"?U(s.definition):p(s.definition,"utf8")}catch{return!1}if(t.platform==="win32")return a===oe(e,i,s,n);if(t.platform!=="darwin")return a===ie(e,i,s,n,t.home,r.path);let o=Y(a);return a.replace(y,"").replace(P,(c,m,L,ce)=>`${m}${o?`${C([o.launcher,...o.args])}
50
- `:""}${ce}`)===te(e,i,s,n,{...t,workerIdentity:()=>null},r.path).plist}function N(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 te(r,e,n,t,i,s){let a=N(r,e),o=J(t,a.args,i),l={HOME:i.home,PATH:s,[ke]:n.label,...a.environment,...o.identity?{[$n]:o.identity.app}:{}};return{identity:o.identity,plist:`<?xml version="1.0" encoding="UTF-8"?>
49
+ <string>${d(a.app)}</string>${m}`);return o===n?null:o}function Ce(r,e){let n=z(r,e);if(n!==null)A(r,n)}function is(r,e,n){if(e.platform!=="darwin")return!1;let t=qe(r,e,n);return t!==null&&z(t.definition,e)!==null}var W="com.reasonmachines.worker.",h="so.reason.worker.",Z=[W,h];function kn(r,e=W){return`${e}connect${r==="production"?"":`.${r}`}`}function os(r,e){return Z.some((n)=>r===kn(e,n))}function he(r,e,n){if(e==="connect")return kn(r.channel,n);let t=ke("sha256").update(r.workspaceRoot).digest("hex").slice(0,8);return`${n}${r.name.toLowerCase()}.${t}`}var Q="A background service needs macOS (launchd), Linux (systemd --user) or Windows (Task Scheduler).";function ee(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:Ni(r),suffix:".xml"};return null}function f(r,e,n,t=W){let i=he(r,n,t),s=ee(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 qe(r,e,n="serve"){return re(r,e,n)[0]??null}function re(r,e,n){return Z.map((t)=>f(r,e,n,t)).filter((t)=>t!==null&&T(t.definition))}function ne(r,e,n){let t=f(r,e,n,h);return t&&T(t.definition)?t:null}function Li(r,e,n){let t=f(r,e,n),i=ne(r,e,n);if(!t||!i||!T(t.definition)||e.insideService?.(i.label))return null;if(!Ne(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 b(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 Ne(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&&Le.has(e.read("systemctl",["--user","show","--property=ActiveState","--value",n])?.trim()??"")}var Le=new Set(["active","activating","reloading"]);function $i(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 ss(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"?U(s.definition):p(s.definition,"utf8")}catch{return!1}if(t.platform==="win32")return a===oe(e,i,s,n);if(t.platform!=="darwin")return a===ie(e,i,s,n,t.home,r.path);let o=Y(a);return a.replace(y,"").replace(P,(c,m,L,ce)=>`${m}${o?`${C([o.launcher,...o.args])}
50
+ `:""}${ce}`)===te(e,i,s,n,{...t,workerIdentity:()=>null},r.path).plist}function N(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 te(r,e,n,t,i,s){let a=N(r,e),o=J(t,a.args,i),l={HOME:i.home,PATH:s,[xe]:n.label,...a.environment,...o.identity?{[$n]: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">
53
53
  <dict>
@@ -93,7 +93,7 @@ Description=${a.description}
93
93
 
94
94
  [Service]
95
95
  ExecStart=${[t,...a.args].map((o)=>G(o,!0)).join(" ")}
96
- Environment=${[`HOME=${i}`,`PATH=${s}`,`${ke}=${n.label}`,...Object.entries(a.environment).map(([o,l])=>`${o}=${l}`)].map((o)=>G(o)).join(" ")}
96
+ Environment=${[`HOME=${i}`,`PATH=${s}`,`${xe}=${n.label}`,...Object.entries(a.environment).map(([o,l])=>`${o}=${l}`)].map((o)=>G(o)).join(" ")}
97
97
  Restart=on-failure
98
98
  RestartSec=10
99
99
  TimeoutStopSec=${Math.ceil(r.shutdownGraceMs/1000)+10}
@@ -101,5 +101,5 @@ UMask=0077
101
101
 
102
102
  [Install]
103
103
  WantedBy=default.target
104
- `}function oe(r,e,n,t){let i=N(r,e);return M({description:i.description,schedule:"logon",script:H({name:n.label,program:t,args:i.args,environment:{[ke]:n.label,...i.environment},log:n.logs,keepAlive:!0})})}function se(r,e,n){e.command("powershell.exe",_(r.label,{tree:n,keepWrapper:!n}))}function b(r,e,n){e.command("schtasks",["/Delete","/F","/TN",r.label]),e.command("powershell.exe",_(r.label,{tree:n,keepWrapper:!1})),u(r.definition,{force:!0})}function A(r,e){ye(xe(r),{recursive:!0,mode:448});let n=`${r}.${we()}.tmp`;try{Ae(n,e,{mode:384,flag:"wx"}),$e(n,384),ve(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 xn(r){let{config:e,launcher:n,host:t}=r,i=r.kind??"serve",s=ne(e,t,i),a=s!==null&&t.insideService?.(s.label)===!0,o=f(e,t,i,a?h:W);if(!o)throw new j(Q);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"?te(e,i,o,n,t,r.path):null;if(A(o.definition,l?l.plist:t.platform==="win32"?K(oe(e,i,o,n)):ie(e,i,o,n,t.home,r.path)),ae(e,t,o,a?null:s),l)return l.identity?o:{...o,identityProblem:Ee};if(t.platform==="win32")return o;return{...o,lingering:t.command("loginctl",["enable-linger"])===0}}function ae(r,e,n,t){if(e.platform==="darwin"){let a=k(e);if(t)e.command("/bin/launchctl",["bootout",`${a}/${t.label}`]);if(le(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)b(t,e,!0);if(e.command("schtasks",V(n.label,n.definition))===0){if(se(n,e,e.insideService?.(n.label)!==!0),e.command("schtasks",["/Run","/TN",n.label])===0)return}throw b(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 le(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 Ie(r,e,n){let t=qe(r,e,n);if(!t)return null;let i=e.insideService?.(t.label)===!0;if(e.platform==="darwin"&&!i)Ce(t.definition,e);let s=f(r,e,n);if(s&&t.label!==s.label&&!i)return A(s.definition,p(t.definition,"utf8").replaceAll(t.label,s.label)),ae(r,e,s,t),s;let a=e.platform==="darwin"&&i,o;if(e.platform==="win32")se(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=le(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)Li(r,e,n);return t}function as(r,e,n,t){let i=qe(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))A(i.definition,o.replaceAll(a,`<string>${d(s.logs)}</string>`))}function Cn(r,e,n="serve"){let t=re(r,e,n);for(let i of t){if(e.platform==="win32"){b(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{Ni,ke,de,j,ze,is,kn,os,qe,Li,$i,ss,xn,Ie,as,Cn};
104
+ `}function oe(r,e,n,t){let i=N(r,e);return M({description:i.description,schedule:"logon",script:H({name:n.label,program:t,args:i.args,environment:{[xe]:n.label,...i.environment},log:n.logs,keepAlive:!0})})}function se(r,e,n){e.command("powershell.exe",_(r.label,{tree:n,keepWrapper:!n}))}function b(r,e,n){e.command("schtasks",["/Delete","/F","/TN",r.label]),e.command("powershell.exe",_(r.label,{tree:n,keepWrapper:!1})),u(r.definition,{force:!0})}function A(r,e){$e(Ae(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 xn(r){let{config:e,launcher:n,host:t}=r,i=r.kind??"serve",s=ne(e,t,i),a=s!==null&&t.insideService?.(s.label)===!0,o=f(e,t,i,a?h:W);if(!o)throw new j(Q);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"?te(e,i,o,n,t,r.path):null;if(A(o.definition,l?l.plist:t.platform==="win32"?K(oe(e,i,o,n)):ie(e,i,o,n,t.home,r.path)),ae(e,t,o,a?null:s),l)return l.identity?o:{...o,identityProblem:Ee};if(t.platform==="win32")return o;return{...o,lingering:t.command("loginctl",["enable-linger"])===0}}function ae(r,e,n,t){if(e.platform==="darwin"){let a=k(e);if(t)e.command("/bin/launchctl",["bootout",`${a}/${t.label}`]);if(le(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)b(t,e,!0);if(e.command("schtasks",V(n.label,n.definition))===0){if(se(n,e,e.insideService?.(n.label)!==!0),e.command("schtasks",["/Run","/TN",n.label])===0)return}throw b(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 le(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 Ie(r,e,n){let t=qe(r,e,n);if(!t)return null;let i=e.insideService?.(t.label)===!0;if(e.platform==="darwin"&&!i)Ce(t.definition,e);let s=f(r,e,n);if(s&&t.label!==s.label&&!i)return A(s.definition,p(t.definition,"utf8").replaceAll(t.label,s.label)),ae(r,e,s,t),s;let a=e.platform==="darwin"&&i,o;if(e.platform==="win32")se(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=le(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)Li(r,e,n);return t}function as(r,e,n,t){let i=qe(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))A(i.definition,o.replaceAll(a,`<string>${d(s.logs)}</string>`))}function Cn(r,e,n="serve"){let t=re(r,e,n);for(let i of t){if(e.platform==="win32"){b(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{Ni,xe,de,j,ze,is,kn,os,qe,Li,$i,ss,xn,Ie,as,Cn};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{t,o,n,we,$e,c,i}from"./vm-hands-entry-lite-bt6skt4h.js";var rr="inference.custom.v1",Br=32768,Un=67108864,Ki=16384,Fr=4194304,h=204800,jr=2*Fr+65536,pa=600000,E=["content-type","anthropic-version","user-agent"],m=c(["openai-completions","openai-responses","anthropic-messages"]),f=new Set(E),C=$e(t(),t().max(2048)).refine((e)=>Object.keys(e).every((s)=>f.has(s))&&Object.values(e).every((s)=>!/[\r\n\0]/.test(s)),"Only non-secret custom endpoint request headers are permitted");function u(e){try{let s=new URL(e);return["http:","https:"].includes(s.protocol)&&!s.username&&!s.password&&!s.search&&!s.hash?s:null}catch{return null}}function Ji(e,s){let r=u(e.baseUrl),d=u(s.baseUrl),a=u(e.url);if(!r||!d||!a||e.method!=="POST"||s.execution!=="device")return!1;let l=(p)=>p.origin+p.pathname.replace(/\/+$/,"");if(l(r)!==l(d)||a.origin!==r.origin)return!1;let _=s.api==="openai-completions"?"/chat/completions":s.api==="openai-responses"?"/responses":"/v1/messages";return a.pathname===r.pathname.replace(/\/+$/,"")+_}var ha=n({baseUrl:t().max(2048),url:t().max(4096),method:i("POST"),body:t().refine((e)=>new TextEncoder().encode(e).byteLength<=Fr).optional(),headers:C,credentialOrganizationId:t().uuid(),accountKey:t().min(1).max(256).optional()}).strict().refine((e)=>m.options.some((s)=>Ji(e,{baseUrl:e.baseUrl,api:s,execution:"device"})),"Invalid custom endpoint inference URL"),D=n({status:o().int().min(200).max(599),statusText:t().max(256).refine((e)=>!/[\r\n\0]/.test(e)),headers:$e(t(),t().max(4096)).refine((e)=>Object.keys(e).every((s)=>["content-type","retry-after","x-request-id","request-id"].includes(s))&&Object.values(e).every((s)=>!/[\r\n\0]/.test(s)))}).strict(),y=we([n({eof:i(!0)}).strict(),n({eof:i(!1),data:t().max(Math.ceil(Br/3)*4).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/).refine((e)=>e.length>0&&e.length*3/4-(e.endsWith("==")?2:e.endsWith("=")?1:0)<=Br)}).strict()]),x=n({bytes:o().int().min(0).max(Un),chunks:o().int().min(0).max(Ki)}).strict(),fa=n({apiKey:t().min(1).max(16384).refine((e)=>!/[\r\n\0]/.test(e)),api:m}).strict(),S=["custom_endpoint_host_not_found","custom_endpoint_connection_failed","custom_endpoint_tls_failed","custom_endpoint_request_too_large","custom_endpoint_device_update_required"];function Hr(e){return typeof e==="string"&&S.includes(e)}var O="Ollama listens only on 127.0.0.1 unless it is started with OLLAMA_HOST=0.0.0.0.",T={custom_endpoint_host_not_found:"Your computer couldn't resolve your model server's hostname. Check the hostname in the Base URL, and that this computer is on the network or tailnet that resolves it.",custom_endpoint_connection_failed:`Your computer's connection to your model server was refused or timed out. Check that the server is running and listening on the Base URL's address and port. ${O}`,custom_endpoint_tls_failed:"Your computer couldn't make a secure (TLS) connection to your model server. Check the server's https certificate, or use an http:// Base URL for a server on your computer or private network.",custom_endpoint_request_too_large:`This conversation is too long for your computer to send to your model server: the request is over ${Fr/1024/1024} MB, the most it relays. Start a new session to continue, or choose another model.`,custom_endpoint_device_update_required:`Reason on your computer is too old to send this conversation to your model server: it relays requests of at most ${h/1024} KB. Update Reason on that computer (reason update), then send your message again.`,401:"Your model server refused the request (HTTP 401). Check the API key saved for it in Models.",403:"Your model server refused the request (HTTP 403). Ollama refuses requests addressed to a hostname other than localhost, such as a *.ts.net name from tailscale serve or funnel: restart it with OLLAMA_HOST=0.0.0.0, or use http://localhost:11434/v1 when it runs on the session's computer. For another server, check the API key and its access rules.",404:"Your model server answered HTTP 404 (not found). Check that the Base URL is the API root (for Ollama, http://localhost:11434/v1) and that each model ID is one the server lists."};var I=new Set(Object.values(T));export{rr,Br,Un,Ki,Fr,jr,pa,Ji,ha,fa,Hr};
2
+ import{t,o,n,be,$e,c,i}from"./vm-hands-entry-lite-n31pta3n.js";var rr="inference.custom.v1",Br=32768,Un=67108864,Ki=16384,Fr=4194304,h=204800,jr=2*Fr+65536,pa=600000,E=["content-type","anthropic-version","user-agent"],m=c(["openai-completions","openai-responses","anthropic-messages"]),f=new Set(E),C=$e(t(),t().max(2048)).refine((e)=>Object.keys(e).every((s)=>f.has(s))&&Object.values(e).every((s)=>!/[\r\n\0]/.test(s)),"Only non-secret custom endpoint request headers are permitted");function u(e){try{let s=new URL(e);return["http:","https:"].includes(s.protocol)&&!s.username&&!s.password&&!s.search&&!s.hash?s:null}catch{return null}}function Ji(e,s){let r=u(e.baseUrl),d=u(s.baseUrl),a=u(e.url);if(!r||!d||!a||e.method!=="POST"||s.execution!=="device")return!1;let l=(p)=>p.origin+p.pathname.replace(/\/+$/,"");if(l(r)!==l(d)||a.origin!==r.origin)return!1;let _=s.api==="openai-completions"?"/chat/completions":s.api==="openai-responses"?"/responses":"/v1/messages";return a.pathname===r.pathname.replace(/\/+$/,"")+_}var ha=n({baseUrl:t().max(2048),url:t().max(4096),method:i("POST"),body:t().refine((e)=>new TextEncoder().encode(e).byteLength<=Fr).optional(),headers:C,credentialOrganizationId:t().uuid(),accountKey:t().min(1).max(256).optional()}).strict().refine((e)=>m.options.some((s)=>Ji(e,{baseUrl:e.baseUrl,api:s,execution:"device"})),"Invalid custom endpoint inference URL"),D=n({status:o().int().min(200).max(599),statusText:t().max(256).refine((e)=>!/[\r\n\0]/.test(e)),headers:$e(t(),t().max(4096)).refine((e)=>Object.keys(e).every((s)=>["content-type","retry-after","x-request-id","request-id"].includes(s))&&Object.values(e).every((s)=>!/[\r\n\0]/.test(s)))}).strict(),y=be([n({eof:i(!0)}).strict(),n({eof:i(!1),data:t().max(Math.ceil(Br/3)*4).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/).refine((e)=>e.length>0&&e.length*3/4-(e.endsWith("==")?2:e.endsWith("=")?1:0)<=Br)}).strict()]),x=n({bytes:o().int().min(0).max(Un),chunks:o().int().min(0).max(Ki)}).strict(),fa=n({apiKey:t().min(1).max(16384).refine((e)=>!/[\r\n\0]/.test(e)),api:m}).strict(),S=["custom_endpoint_host_not_found","custom_endpoint_connection_failed","custom_endpoint_tls_failed","custom_endpoint_request_too_large","custom_endpoint_device_update_required"];function Hr(e){return typeof e==="string"&&S.includes(e)}var O="Ollama listens only on 127.0.0.1 unless it is started with OLLAMA_HOST=0.0.0.0.",T={custom_endpoint_host_not_found:"Your computer couldn't resolve your model server's hostname. Check the hostname in the Base URL, and that this computer is on the network or tailnet that resolves it.",custom_endpoint_connection_failed:`Your computer's connection to your model server was refused or timed out. Check that the server is running and listening on the Base URL's address and port. ${O}`,custom_endpoint_tls_failed:"Your computer couldn't make a secure (TLS) connection to your model server. Check the server's https certificate, or use an http:// Base URL for a server on your computer or private network.",custom_endpoint_request_too_large:`This conversation is too long for your computer to send to your model server: the request is over ${Fr/1024/1024} MB, the most it relays. Start a new session to continue, or choose another model.`,custom_endpoint_device_update_required:`Reason on your computer is too old to send this conversation to your model server: it relays requests of at most ${h/1024} KB. Update Reason on that computer (reason update), then send your message again.`,401:"Your model server refused the request (HTTP 401). Check the API key saved for it in Models.",403:"Your model server refused the request (HTTP 403). Ollama refuses requests addressed to a hostname other than localhost, such as a *.ts.net name from tailscale serve or funnel: restart it with OLLAMA_HOST=0.0.0.0, or use http://localhost:11434/v1 when it runs on the session's computer. For another server, check the API key and its access rules.",404:"Your model server answered HTTP 404 (not found). Check that the Base URL is the API root (for Ollama, http://localhost:11434/v1) and that each model ID is one the server lists."};var I=new Set(Object.values(T));export{rr,Br,Un,Ki,Fr,jr,pa,Ji,ha,fa,Hr};