@reason-machines/cli-linux-x64 0.2.553 → 0.2.554

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 (76) hide show
  1. package/bin/reason +1 -1
  2. package/bin/vm-hands/api-1dsd0n4x.js +2 -0
  3. package/bin/vm-hands/api-credentials-gtrz9r3n.js +2 -0
  4. package/bin/vm-hands/connect-cli-jbwaswpq.js +2 -0
  5. package/bin/vm-hands/{desktop-account-d7x4xn27.js → desktop-account-t0afsge2.js} +1 -1
  6. package/bin/vm-hands/{hands-worker-source-wc8a2nhs.js → hands-worker-source-qj7s9dk5.js} +1 -1
  7. package/bin/vm-hands/local-automation-c75g446p.js +2 -0
  8. package/bin/vm-hands/local-capabilities-1kcxmz0s.js +2 -0
  9. package/bin/vm-hands/{local-desktop-users-tjcpyakd.js → local-desktop-users-5scb9930.js} +1 -1
  10. package/bin/vm-hands/local-display-mac-pft73te9.js +2 -0
  11. package/bin/vm-hands/local-display-session-hvbp46qx.js +2 -0
  12. package/bin/vm-hands/local-display-video-yh6hfavd.js +2 -0
  13. package/bin/vm-hands/local-managed-process-g6vsy02z.js +2 -0
  14. package/bin/vm-hands/local-pty-session-njd0tprg.js +2 -0
  15. package/bin/vm-hands/{managed-runtime-9p83xxgg.js → managed-runtime-htxs6v4q.js} +1 -1
  16. package/bin/vm-hands/permissions-mhd63yr2.js +2 -0
  17. package/bin/vm-hands/reason-hands-protocol-g54rtrhd.js +2 -0
  18. package/bin/vm-hands/{serve-service-83tm7ky3.js → serve-service-38k4j5rf.js} +1 -1
  19. package/bin/vm-hands/{status-mtmtkbbp.js → status-m1crm0qs.js} +2 -2
  20. package/bin/vm-hands/version-qp2wr1ds.js +2 -0
  21. package/bin/vm-hands/{vm-hands-entry-lite-645wzfhr.js → vm-hands-entry-lite-0wsr8edk.js} +2 -2
  22. package/bin/vm-hands/{vm-hands-entry-lite-3dccjjq2.js → vm-hands-entry-lite-1pp7czc0.js} +24 -24
  23. package/bin/vm-hands/{vm-hands-entry-lite-kmtz5h74.js → vm-hands-entry-lite-1yv5qqew.js} +22 -22
  24. package/bin/vm-hands/{vm-hands-entry-lite-k9vk84wa.js → vm-hands-entry-lite-2v4zh9ze.js} +5 -5
  25. package/bin/vm-hands/vm-hands-entry-lite-3mn5c8wd.js +3 -0
  26. package/bin/vm-hands/{vm-hands-entry-lite-72nj66ab.js → vm-hands-entry-lite-46pwqvpf.js} +2 -2
  27. package/bin/vm-hands/{vm-hands-entry-lite-55ja13pk.js → vm-hands-entry-lite-6qq4f3v5.js} +1 -1
  28. package/bin/vm-hands/{vm-hands-entry-lite-ycddfgr4.js → vm-hands-entry-lite-8mttvhef.js} +8 -8
  29. package/bin/vm-hands/{vm-hands-entry-lite-0yvkh3bg.js → vm-hands-entry-lite-a6brf7zp.js} +1 -1
  30. package/bin/vm-hands/{vm-hands-entry-lite-9azmqs47.js → vm-hands-entry-lite-ak0hd94p.js} +1 -1
  31. package/bin/vm-hands/{vm-hands-entry-lite-2hfrcr50.js → vm-hands-entry-lite-bpamn7ny.js} +1 -1
  32. package/bin/vm-hands/{vm-hands-entry-lite-w29d7ey0.js → vm-hands-entry-lite-dgfx0rbn.js} +4 -4
  33. package/bin/vm-hands/{vm-hands-entry-lite-hq76nmrc.js → vm-hands-entry-lite-drggrrr8.js} +15 -15
  34. package/bin/vm-hands/{vm-hands-entry-lite-qdrmhn3f.js → vm-hands-entry-lite-g8md08wv.js} +2 -2
  35. package/bin/vm-hands/{vm-hands-entry-lite-8s4namcq.js → vm-hands-entry-lite-ggyexab2.js} +1 -1
  36. package/bin/vm-hands/{vm-hands-entry-lite-5tnma5qb.js → vm-hands-entry-lite-gje7xvy9.js} +1 -1
  37. package/bin/vm-hands/{vm-hands-entry-lite-hfx1q0b0.js → vm-hands-entry-lite-h1qjggz0.js} +1 -1
  38. package/bin/vm-hands/{vm-hands-entry-lite-y9jarm7q.js → vm-hands-entry-lite-h2rq71rj.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-6pqfr3w2.js → vm-hands-entry-lite-h78c4zxd.js} +2 -2
  40. package/bin/vm-hands/{vm-hands-entry-lite-zrkw5syq.js → vm-hands-entry-lite-jha299pc.js} +3 -3
  41. package/bin/vm-hands/{vm-hands-entry-lite-sb7b4z8t.js → vm-hands-entry-lite-n7bd44rm.js} +1 -1
  42. package/bin/vm-hands/{vm-hands-entry-lite-gezw3967.js → vm-hands-entry-lite-pg2czhxb.js} +1 -1
  43. package/bin/vm-hands/{vm-hands-entry-lite-13s0mfpr.js → vm-hands-entry-lite-q2h781jg.js} +1 -1
  44. package/bin/vm-hands/{vm-hands-entry-lite-xe0benev.js → vm-hands-entry-lite-qd46yhvz.js} +1 -1
  45. package/bin/vm-hands/vm-hands-entry-lite-qdzbd077.js +2 -0
  46. package/bin/vm-hands/{vm-hands-entry-lite-x3ym5t8r.js → vm-hands-entry-lite-r1n9zhsm.js} +5 -5
  47. package/bin/vm-hands/{vm-hands-entry-lite-y5hv1gjv.js → vm-hands-entry-lite-ravxhygk.js} +1 -1
  48. package/bin/vm-hands/{vm-hands-entry-lite-whfrwyxm.js → vm-hands-entry-lite-rp2twenv.js} +1 -1
  49. package/bin/vm-hands/{vm-hands-entry-lite-8hwmhvyx.js → vm-hands-entry-lite-sqzryt00.js} +16 -16
  50. package/bin/vm-hands/{vm-hands-entry-lite-xrqztkhv.js → vm-hands-entry-lite-wghmyfba.js} +2 -2
  51. package/bin/vm-hands/{vm-hands-entry-lite-e16bhf16.js → vm-hands-entry-lite-x8wjxgwr.js} +1 -1
  52. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  53. package/bin/vm-hands/{vm-hands-executor-n5vw984z.js → vm-hands-executor-0b1azv5m.js} +1 -1
  54. package/bin/vm-hands/{vm-hands-op-runner-91w40a0z.js → vm-hands-op-runner-f2pye28r.js} +1 -1
  55. package/bin/vm-hands/{vm-hands-runtime-08q76986.js → vm-hands-runtime-7cwr0sys.js} +3 -3
  56. package/bin/vm-hands/worker-preview-readiness-gy36ejp9.js +2 -0
  57. package/bin/vm-hands/worker-sandbox-f1tfb3y0.js +2 -0
  58. package/package.json +1 -1
  59. package/bin/vm-hands/api-18f1batz.js +0 -2
  60. package/bin/vm-hands/api-credentials-6jgf7w9q.js +0 -2
  61. package/bin/vm-hands/connect-cli-xgbm9xfg.js +0 -2
  62. package/bin/vm-hands/local-automation-gc28rhzv.js +0 -2
  63. package/bin/vm-hands/local-capabilities-aa7m3ac6.js +0 -2
  64. package/bin/vm-hands/local-display-mac-gtp439kc.js +0 -2
  65. package/bin/vm-hands/local-display-session-wkhda8j7.js +0 -2
  66. package/bin/vm-hands/local-display-video-14fj7scm.js +0 -2
  67. package/bin/vm-hands/local-managed-process-hq1x6wqt.js +0 -2
  68. package/bin/vm-hands/local-pty-session-yr22ryvy.js +0 -2
  69. package/bin/vm-hands/permissions-5dhys0br.js +0 -2
  70. package/bin/vm-hands/reason-hands-protocol-k12sw3vm.js +0 -2
  71. package/bin/vm-hands/version-8z8e46x9.js +0 -2
  72. package/bin/vm-hands/vm-hands-entry-lite-r7tb2z3z.js +0 -3
  73. package/bin/vm-hands/vm-hands-entry-lite-vn7ag8c7.js +0 -2
  74. package/bin/vm-hands/worker-preview-readiness-84stxabw.js +0 -2
  75. package/bin/vm-hands/worker-sandbox-563c5g2f.js +0 -2
  76. /package/bin/vm-hands/{vm-hands-entry-lite-b6gsggvp.js → vm-hands-entry-lite-tyem93c1.js} +0 -0
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{N}from"./vm-hands-entry-lite-48rphbjm.js";import{O,T,b}from"./vm-hands-entry-lite-kmtz5h74.js";import{je,gr,_r,Sn,En,ct}from"./vm-hands-entry-lite-hq76nmrc.js";import{$r}from"./vm-hands-entry-lite-w29d7ey0.js";import{p,ut,An,_e,we}from"./vm-hands-entry-lite-2hfrcr50.js";import{v,h}from"./vm-hands-entry-lite-hfx1q0b0.js";import{a,nr,Wo}from"./vm-hands-entry-lite-8dfw96ym.js";import{an,y,t,k,o,d,ms,Ie,Bi,u,n,W,g,ee,s,i,cn}from"./vm-hands-entry-lite-wzv13c8k.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{se,A}from"./vm-hands-entry-lite-b6gsggvp.js";import{randomUUID as Q}from"crypto";import{spawn as Le}from"child_process";import{existsSync as Z,lstatSync as me,mkdirSync as We,readFileSync as Ne,realpathSync as G,rmSync as Ve,writeFileSync as He}from"fs";import{dirname as Ue,join as j,relative as qe,sep as Je}from"path";var Se=["process.run.v1","process.full.v1"],xe=600000,Pe=1800000,Ee=20000,ne="process.cancel.v1",ie=n({action:i("start"),request_id:t().uuid(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),cwd:t().min(1).max(4096).refine((e)=>!e.includes("\x00")&&!e.startsWith("/")&&!e.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:s(["host","confined"]).default("host"),timeout_ms:o().int().min(1000).max(Pe).default(xe).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),K={device_id:t().uuid(),root_id:t().uuid()},Re=g("action",[ie.extend(K),n({...K,action:i("inspect"),process_id:t().uuid(),after:o().int().min(0).default(0),wait_ms:o().int().min(0).max(Ee).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),n({...K,action:i("cancel"),process_id:t().uuid()}).strict()]),Fe=an(Re,{io:"input"}),Ke=ie.extend({process_brain_fence:t().uuid(),process_expires_at:y.datetime()}).strict(),J=n({version:i(1),process_id:t().uuid(),state:s(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:o().int().nullable(),first_cursor:o().int().min(0),next_cursor:o().int().min(0),truncated:d(),observed_at:y.datetime(),output:u(n({cursor:o().int().min(1),stream:s(["stdout","stderr"]),text:t().max(32768)}).strict()).max(128)}).strict().refine((e)=>{if(Buffer.byteLength(JSON.stringify(e))>1e5||e.next_cursor<e.first_cursor-1)return!1;if((e.state==="starting"||e.state==="running"||e.state==="uncertain")&&e.exit_code!==null)return!1;if(e.state==="exited"&&(e.exit_code===null||e.exit_code<0||e.exit_code>255))return!1;if(e.state==="cancelled"&&e.exit_code!==130||e.state==="expired"&&e.exit_code!==124)return!1;let _=e.first_cursor-1;for(let l of e.output){if(l.cursor<=_||l.cursor>e.next_cursor)return!1;_=l.cursor}return!0});function ae(e){return Se.includes(e)}var Xe=n({operation_constraints:ee(t(),Ie())}),Ye=n({ready:i(!0),version:i(1),execution_mode:s(["host","confined"]),max_timeout_ms:o().int().min(1000).optional()});var De=n({version:i(1),process_id:t().uuid(),state:s(["queued","cancelled_before_start","not_started"]),exit_code:ms(),output:u(Bi()).length(0),first_cursor:i(0),next_cursor:i(0),truncated:i(!1),cancellation_requested:i(!1),reason_code:s(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),Ce=n({...J.shape,state:s(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:y.datetime().optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:d(),reason_code:t().nullable().optional(),execution_authority:i("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:n({cause:i("brain_generation_changed"),terminal_confirmed:d(),next_step:s(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:J.shape.state.or(i("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),$e=an(Ce),Qe=W([J,De.refine((e)=>e.state==="cancelled_before_start")]),X=n({version:i(1),process_id:t().uuid(),state:s(["exited","cancelled","expired"]),exit_code:o().int().min(0).max(255),observed_at:y.datetime()}).strict().refine((e)=>(e.state!=="cancelled"||e.exit_code===130)&&(e.state!=="expired"||e.exit_code===124)),Ze=n({process_terminal_observation:X}).strict();var Xi="preview.serve.v1",Yi=43200000;var ce="preview.open.v1",de=1,_n="gid_proxy_v1",Zi="egress",yn=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,Ae=n({version:i(_n),allowed_domains:u(t().max(260).regex(yn)).max(1024)}).strict(),ke=cn((e)=>N(e)!==null,"invalid workspace"),Oe=n({version:i(1),request_id:k(),session_id:k(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),port:o().int().min(1024).max(65535),workspace:ke,egress:Ae.optional()}).strict(),Qi=Oe.extend({expires_at:y.datetime()}).strict();var Me=4,Te=5000;function Y(e,c,_){let l=null;try{l=ut(e)}catch{}An({deviceRelayUrl:l?.deviceRelayUrl??"",binding:l?.binding??null,jobId:c,port:l?.binding.port??0,reason:l?_:"binding_invalid"})}function le(e){let c=new Map;return{open(_){let l=(x)=>Y(_,e.claim.operation_id,x),I;try{I=ut(_)}catch{return l("binding_invalid")}let{binding:w,deviceRelayUrl:z}=I,E=e.claim.owner;if(!E||w.organizationId!==E.organization_id||w.userId!==E.user_id||w.deviceId!==E.device_id||w.rootId!==e.claim.root_id||w.jobId!==e.claim.operation_id||w.fenceId!==e.claim.operation_id||w.generation!==de||w.expiresAtMs>Math.min(Date.now()+p.lifetimeMs+Te,e.expiresAtMs))return l("binding_mismatch");if(w.expiresAtMs<=Date.now())return l("binding_expired");if(c.get(w.port)?.abort(),c.delete(w.port),c.size>=Me)return l("preview_capacity");let L=new AbortController;c.set(w.port,L);let P=we({binding:w,deniedPorts:e.deniedPorts,readCurrentJob:async()=>{if(L.signal.aborted)return null;let x=await e.inspect();return x?{binding:w,executorLaunchId:e.executorLaunchId,job:x}:null}});_e({binding:w,deviceRelayUrl:z,port:P,signal:L.signal}).then((x)=>x.closed,(x)=>{let R=x instanceof Error?x.message:"preview_failed";if(R!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:w.jobId,port:w.port,reason_code:R})}
3
- `)}).finally(()=>{if(c.get(w.port)===L)c.delete(w.port)})},dispose(){for(let _ of c.values())_.abort();c.clear()}}}class st extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var fe=256,B=new Map,he="preview.serve.v1",H=new Map;function be(e){let c=H.get(e.operation_id);if(c){if(c.claim!==e)throw C("process_authority_lost");return c}if(H.size>=fe)throw C("process_journal_capacity");let _={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return H.set(e.operation_id,_),_}function pe(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ue=(e)=>new Promise((c)=>setTimeout(c,e)),C=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function ze(e=a(),c=Ge()){let _=Ue($r({},e)),l=qe(nr(e),_),[I,...w]=l.split(Je);return{directory:j(c,l,"processes"),previous:[j(_,"processes"),...I==="reason"?[j(c,"ara",...w,"processes")]:[]]}}function Ge(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=Wo();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function fr(e){if(!e.claim.owner||e.signal.aborted||e.expiresAtMs<=Date.now())throw C("process_authority_lost");let c=be(e.claim);if(c.executing)throw C("process_busy");if(c.executing=!0,c.cancelRequested)return c.phase="settling",pe(e.claim.operation_id);c.phase="starting";let _=e.journals??ze();We(_.directory,{recursive:!0,mode:448});let l=gr({runtimeDirectory:G(_.directory),previousRuntimeDirectories:(_.previous??[]).filter((m)=>Z(m)).map((m)=>G(m)),root:e.root,runId:JSON.stringify([e.claim.owner,e.claim.run_id,e.claim.root_id,e.claim.operation_id]),maxScopes:fe,folders:[e.root,e.cwd]});try{for(let m of[e.root,e.cwd])if(!je(G(m),l.journalDirectory))throw new r("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(m){throw l.disposeSocket(),m}let I=me(l.journalDirectory),w=e.claim.capability===he,z=()=>B.set(e.claim.operation_id,{path:l.journalDirectory,ino:I.ino,dev:I.dev,anyCompletion:w}),E=l.launchDirectory,L=j(E,"config.json"),P={url:"",transport:"local_job_ipc",directShell:{mode:e.mode,executable:e.shell,jobId:e.claim.operation_id},workerVersion:O,protocolVersion:2,workerArtifactSha256:b,workerEntrypoint:T,targetGeneration:1,fenceId:Q(),...process.platform==="win32"?{bashExecutable:se()}:{},workRoot:e.root,workspaceAliasPath:e.root,repoPath:e.cwd,jobEnvPath:j(E,"unused.env"),replSocketPath:j(E,"unused.sock"),readyPath:j(E,"ready.json"),directTerminalReceiptPath:j(E,"terminal.json"),launchId:Q(),expiresAtMs:e.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:l.journalDirectory,scopeId:l.scopeId},jobControlSocketPath:l.socketPath,...e.prefix?{bashCommandPrefix:e.prefix}:{},...e.jobsUser?{jobsUser:e.jobsUser}:{}},x;try{He(L,JSON.stringify(P),{mode:384});let m=Sn({configPath:L,root:e.cwd,grantedRoot:e.root,workRoot:e.root,temporaryDirectory:E});x=e.spawnWorker?.(L,P)??Le(m.command,m.args,{...m.options,env:e.environment,stdio:[En,"ignore","ignore"]})}catch(m){throw l.disposeSocket(),m}let R=!1,F=new Promise((m,S)=>{x.once("exit",(f)=>{R=!0,m(f)}),x.once("error",(f)=>{R=!0,S(f)})});F.catch(()=>{});let ge={root:e.root,runId:e.claim.run_id,scopeId:l.scopeId,socketPath:l.socketPath,generation:1,fenceId:P.fenceId,executorLaunchId:P.launchId,expiresAtMs:P.expiresAtMs},V=async(m)=>{let S=await _r(ge,{type:"job",version:2,generation:1,id:Q(),jobId:e.claim.operation_id,...m==="start"?{action:m,input:{script:e.command,leaseExpiresAtMs:e.expiresAtMs}}:m==="inspect"?{action:m,input:{after:0}}:m==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:m,input:{}}},new AbortController().signal);if(!S.ok)throw C(S.error);return S.job},U=!1,q=!1,te,re=()=>{U=!0,ct(x,"SIGTERM")};e.signal.addEventListener("abort",re,{once:!0});let M,oe=0,ve=async(m)=>{let S=[...m.output],f={version:1,process_id:e.claim.operation_id,state:m.state,exit_code:m.exitCode,first_cursor:m.firstCursor,next_cursor:m.nextCursor,truncated:m.truncated,output:S,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(f))>90000&&S.length)S.shift(),f.truncated=!0,f.first_cursor=S[0]?.cursor??f.next_cursor+1;M=J.parse(f),await e.emit(M),oe=Date.now()};try{let m=Math.min(Date.now()+1e4,e.expiresAtMs);while(!Z(P.readyPath)){if(R)throw new r("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if(e.signal.aborted||Date.now()>=m)throw C("process_start_unconfirmed");await ue(25)}let S=JSON.parse(Ne(P.readyPath,"utf8"));if(S.launchId!==P.launchId||S.fenceId!==P.fenceId||S.workerArtifactSha256!==b)throw C();if(e.signal.throwIfAborted(),c.cancelRequested)return pe(e.claim.operation_id);let f;try{q=!0,f=await V("start")}catch(D){if(!(D instanceof r)||D.code!=="hands_job_result_unknown")throw D;f=await V("inspect")}if(c.phase="running",c.cancel=async()=>{await V("cancel")},w&&e.preview)c.tunnels=le({claim:e.claim,executorLaunchId:P.launchId,expiresAtMs:e.expiresAtMs,deniedPorts:e.preview.deniedPorts,inspect:async()=>c.phase==="running"&&!R?await V("probe"):null});if(c.cancelRequested)await c.cancel(),f=await V("inspect");for(;;){if(!["starting","running"].includes(f.state))c.phase="settling",c.cancel=void 0;if(!M||M.state!==f.state||M.next_cursor!==f.nextCursor&&Date.now()-oe>=5000)await ve(f);if(!["starting","running"].includes(f.state))break;if(e.signal.aborted||R)throw C();await ue(1000);try{f=await V("inspect"),te=void 0}catch(D){if(!(D instanceof r)||D.code!=="hands_job_result_unknown"||e.signal.aborted||R||Date.now()-(te??=Date.now())>120000)throw D}}if(!M||M.state==="uncertain")throw C();return M}finally{if(c.phase="settling",c.cancel=void 0,c.tunnels?.dispose(),c.tunnels=void 0,await c.cancelInFlight?.catch(()=>{}),e.signal.removeEventListener("abort",re),!R&&!U)ct(x,"SIGTERM");let m,S=await Promise.race([F.then((f)=>({code:f})),new Promise((f)=>{m=setTimeout(()=>f(null),6000)})]).finally(()=>{clearTimeout(m)});if(!S){try{ct(x,"SIGKILL")}catch{}try{await F}finally{if(R)l.disposeSocket()}throw C("process_cleanup_unconfirmed")}try{if((U||e.signal.aborted)&&S.code===0&&q){v(E);let f=JSON.parse(h(P.directTerminalReceiptPath)),D=X.safeParse(f.observation);if(Object.keys(f).length===4&&f.launch_id===P.launchId&&f.fence_id===P.fenceId&&f.scope_id===l.scopeId&&D.success&&D.data.process_id===e.claim.operation_id){if(w)z();throw new st(D.data)}}}catch(f){if(f instanceof st)throw f}finally{if(R)l.disposeSocket()}if(S.code!==0&&!U&&q)throw C("process_cleanup_unconfirmed");if(!U&&S.code===0&&(M&&["exited","cancelled","expired"].includes(M.state)||!q&&c.cancelRequested)||w&&S.code===0&&!q)z()}}async function js(e,c){if(c.kind===ce&&e.capability===he){let I=H.get(e.operation_id);if(I?.claim===e&&I.tunnels)I.tunnels.open(c.payload);else Y(c.payload,e.operation_id,"server_not_running");return!0}if(c.kind!==ne||!ae(e.capability)||!e.owner||c.payload.process_id!==e.operation_id)return!1;let _=H.get(e.operation_id);if(_&&_.claim!==e)return!1;let l=be(e);if(l.cancelRequested=!0,l.phase==="running"&&l.cancel)l.cancelInFlight??=l.cancel(),await l.cancelInFlight;return!0}function Hs(e,c){H.delete(e);let _=B.get(e);if(!_||c!=="succeeded"&&!_.anyCompletion)return B.delete(e),!1;try{let l=me(_.path);if(!l.isDirectory()||l.isSymbolicLink()||l.ino!==_.ino||l.dev!==_.dev||!A(l)||G(_.path)!==_.path||Z(j(_.path,"owner.lock")))return!1;return Ve(_.path,{recursive:!0}),B.delete(e),!0}catch{return!1}}
2
+ import{N}from"./vm-hands-entry-lite-48rphbjm.js";import{O,T,b}from"./vm-hands-entry-lite-1yv5qqew.js";import{je,gr,_r,Sn,En,ct}from"./vm-hands-entry-lite-drggrrr8.js";import{Or}from"./vm-hands-entry-lite-dgfx0rbn.js";import{p,ut,An,_e,we}from"./vm-hands-entry-lite-bpamn7ny.js";import{v,h}from"./vm-hands-entry-lite-h1qjggz0.js";import{a,nr,Wo}from"./vm-hands-entry-lite-8dfw96ym.js";import{an,y,t,k,o,d,ms,Ie,Bi,u,n,W,g,ee,s,i,cn}from"./vm-hands-entry-lite-wzv13c8k.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{se,A}from"./vm-hands-entry-lite-tyem93c1.js";import{randomUUID as Q}from"crypto";import{spawn as Le}from"child_process";import{existsSync as Z,lstatSync as me,mkdirSync as We,readFileSync as Ne,realpathSync as G,rmSync as Ve,writeFileSync as He}from"fs";import{dirname as Ue,join as j,relative as qe,sep as Je}from"path";var Se=["process.run.v1","process.full.v1"],xe=600000,Pe=1800000,Ee=20000,ne="process.cancel.v1",ie=n({action:i("start"),request_id:t().uuid(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),cwd:t().min(1).max(4096).refine((e)=>!e.includes("\x00")&&!e.startsWith("/")&&!e.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:s(["host","confined"]).default("host"),timeout_ms:o().int().min(1000).max(Pe).default(xe).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),K={device_id:t().uuid(),root_id:t().uuid()},Re=g("action",[ie.extend(K),n({...K,action:i("inspect"),process_id:t().uuid(),after:o().int().min(0).default(0),wait_ms:o().int().min(0).max(Ee).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),n({...K,action:i("cancel"),process_id:t().uuid()}).strict()]),Fe=an(Re,{io:"input"}),Ke=ie.extend({process_brain_fence:t().uuid(),process_expires_at:y.datetime()}).strict(),J=n({version:i(1),process_id:t().uuid(),state:s(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:o().int().nullable(),first_cursor:o().int().min(0),next_cursor:o().int().min(0),truncated:d(),observed_at:y.datetime(),output:u(n({cursor:o().int().min(1),stream:s(["stdout","stderr"]),text:t().max(32768)}).strict()).max(128)}).strict().refine((e)=>{if(Buffer.byteLength(JSON.stringify(e))>1e5||e.next_cursor<e.first_cursor-1)return!1;if((e.state==="starting"||e.state==="running"||e.state==="uncertain")&&e.exit_code!==null)return!1;if(e.state==="exited"&&(e.exit_code===null||e.exit_code<0||e.exit_code>255))return!1;if(e.state==="cancelled"&&e.exit_code!==130||e.state==="expired"&&e.exit_code!==124)return!1;let _=e.first_cursor-1;for(let l of e.output){if(l.cursor<=_||l.cursor>e.next_cursor)return!1;_=l.cursor}return!0});function ae(e){return Se.includes(e)}var Xe=n({operation_constraints:ee(t(),Ie())}),Ye=n({ready:i(!0),version:i(1),execution_mode:s(["host","confined"]),max_timeout_ms:o().int().min(1000).optional()});var De=n({version:i(1),process_id:t().uuid(),state:s(["queued","cancelled_before_start","not_started"]),exit_code:ms(),output:u(Bi()).length(0),first_cursor:i(0),next_cursor:i(0),truncated:i(!1),cancellation_requested:i(!1),reason_code:s(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),Ce=n({...J.shape,state:s(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:y.datetime().optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:d(),reason_code:t().nullable().optional(),execution_authority:i("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:n({cause:i("brain_generation_changed"),terminal_confirmed:d(),next_step:s(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:J.shape.state.or(i("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),$e=an(Ce),Qe=W([J,De.refine((e)=>e.state==="cancelled_before_start")]),X=n({version:i(1),process_id:t().uuid(),state:s(["exited","cancelled","expired"]),exit_code:o().int().min(0).max(255),observed_at:y.datetime()}).strict().refine((e)=>(e.state!=="cancelled"||e.exit_code===130)&&(e.state!=="expired"||e.exit_code===124)),Ze=n({process_terminal_observation:X}).strict();var Xi="preview.serve.v1",Yi=43200000;var ce="preview.open.v1",de=1,_n="gid_proxy_v1",Zi="egress",yn=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,Ae=n({version:i(_n),allowed_domains:u(t().max(260).regex(yn)).max(1024)}).strict(),ke=cn((e)=>N(e)!==null,"invalid workspace"),Oe=n({version:i(1),request_id:k(),session_id:k(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),port:o().int().min(1024).max(65535),workspace:ke,egress:Ae.optional()}).strict(),Qi=Oe.extend({expires_at:y.datetime()}).strict();var Me=4,Te=5000;function Y(e,c,_){let l=null;try{l=ut(e)}catch{}An({deviceRelayUrl:l?.deviceRelayUrl??"",binding:l?.binding??null,jobId:c,port:l?.binding.port??0,reason:l?_:"binding_invalid"})}function le(e){let c=new Map;return{open(_){let l=(x)=>Y(_,e.claim.operation_id,x),I;try{I=ut(_)}catch{return l("binding_invalid")}let{binding:w,deviceRelayUrl:z}=I,E=e.claim.owner;if(!E||w.organizationId!==E.organization_id||w.userId!==E.user_id||w.deviceId!==E.device_id||w.rootId!==e.claim.root_id||w.jobId!==e.claim.operation_id||w.fenceId!==e.claim.operation_id||w.generation!==de||w.expiresAtMs>Math.min(Date.now()+p.lifetimeMs+Te,e.expiresAtMs))return l("binding_mismatch");if(w.expiresAtMs<=Date.now())return l("binding_expired");if(c.get(w.port)?.abort(),c.delete(w.port),c.size>=Me)return l("preview_capacity");let L=new AbortController;c.set(w.port,L);let P=we({binding:w,deniedPorts:e.deniedPorts,readCurrentJob:async()=>{if(L.signal.aborted)return null;let x=await e.inspect();return x?{binding:w,executorLaunchId:e.executorLaunchId,job:x}:null}});_e({binding:w,deviceRelayUrl:z,port:P,signal:L.signal}).then((x)=>x.closed,(x)=>{let R=x instanceof Error?x.message:"preview_failed";if(R!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:w.jobId,port:w.port,reason_code:R})}
3
+ `)}).finally(()=>{if(c.get(w.port)===L)c.delete(w.port)})},dispose(){for(let _ of c.values())_.abort();c.clear()}}}class st extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var fe=256,B=new Map,he="preview.serve.v1",H=new Map;function be(e){let c=H.get(e.operation_id);if(c){if(c.claim!==e)throw C("process_authority_lost");return c}if(H.size>=fe)throw C("process_journal_capacity");let _={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return H.set(e.operation_id,_),_}function pe(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ue=(e)=>new Promise((c)=>setTimeout(c,e)),C=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function ze(e=a(),c=Ge()){let _=Ue(Or({},e)),l=qe(nr(e),_),[I,...w]=l.split(Je);return{directory:j(c,l,"processes"),previous:[j(_,"processes"),...I==="reason"?[j(c,"ara",...w,"processes")]:[]]}}function Ge(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=Wo();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function fr(e){if(!e.claim.owner||e.signal.aborted||e.expiresAtMs<=Date.now())throw C("process_authority_lost");let c=be(e.claim);if(c.executing)throw C("process_busy");if(c.executing=!0,c.cancelRequested)return c.phase="settling",pe(e.claim.operation_id);c.phase="starting";let _=e.journals??ze();We(_.directory,{recursive:!0,mode:448});let l=gr({runtimeDirectory:G(_.directory),previousRuntimeDirectories:(_.previous??[]).filter((m)=>Z(m)).map((m)=>G(m)),root:e.root,runId:JSON.stringify([e.claim.owner,e.claim.run_id,e.claim.root_id,e.claim.operation_id]),maxScopes:fe,folders:[e.root,e.cwd]});try{for(let m of[e.root,e.cwd])if(!je(G(m),l.journalDirectory))throw new r("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(m){throw l.disposeSocket(),m}let I=me(l.journalDirectory),w=e.claim.capability===he,z=()=>B.set(e.claim.operation_id,{path:l.journalDirectory,ino:I.ino,dev:I.dev,anyCompletion:w}),E=l.launchDirectory,L=j(E,"config.json"),P={url:"",transport:"local_job_ipc",directShell:{mode:e.mode,executable:e.shell,jobId:e.claim.operation_id},workerVersion:O,protocolVersion:2,workerArtifactSha256:b,workerEntrypoint:T,targetGeneration:1,fenceId:Q(),...process.platform==="win32"?{bashExecutable:se()}:{},workRoot:e.root,workspaceAliasPath:e.root,repoPath:e.cwd,jobEnvPath:j(E,"unused.env"),replSocketPath:j(E,"unused.sock"),readyPath:j(E,"ready.json"),directTerminalReceiptPath:j(E,"terminal.json"),launchId:Q(),expiresAtMs:e.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:l.journalDirectory,scopeId:l.scopeId},jobControlSocketPath:l.socketPath,...e.prefix?{bashCommandPrefix:e.prefix}:{},...e.jobsUser?{jobsUser:e.jobsUser}:{}},x;try{He(L,JSON.stringify(P),{mode:384});let m=Sn({configPath:L,root:e.cwd,grantedRoot:e.root,workRoot:e.root,temporaryDirectory:E});x=e.spawnWorker?.(L,P)??Le(m.command,m.args,{...m.options,env:e.environment,stdio:[En,"ignore","ignore"]})}catch(m){throw l.disposeSocket(),m}let R=!1,F=new Promise((m,S)=>{x.once("exit",(f)=>{R=!0,m(f)}),x.once("error",(f)=>{R=!0,S(f)})});F.catch(()=>{});let ge={root:e.root,runId:e.claim.run_id,scopeId:l.scopeId,socketPath:l.socketPath,generation:1,fenceId:P.fenceId,executorLaunchId:P.launchId,expiresAtMs:P.expiresAtMs},V=async(m)=>{let S=await _r(ge,{type:"job",version:2,generation:1,id:Q(),jobId:e.claim.operation_id,...m==="start"?{action:m,input:{script:e.command,leaseExpiresAtMs:e.expiresAtMs}}:m==="inspect"?{action:m,input:{after:0}}:m==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:m,input:{}}},new AbortController().signal);if(!S.ok)throw C(S.error);return S.job},U=!1,q=!1,te,re=()=>{U=!0,ct(x,"SIGTERM")};e.signal.addEventListener("abort",re,{once:!0});let M,oe=0,ve=async(m)=>{let S=[...m.output],f={version:1,process_id:e.claim.operation_id,state:m.state,exit_code:m.exitCode,first_cursor:m.firstCursor,next_cursor:m.nextCursor,truncated:m.truncated,output:S,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(f))>90000&&S.length)S.shift(),f.truncated=!0,f.first_cursor=S[0]?.cursor??f.next_cursor+1;M=J.parse(f),await e.emit(M),oe=Date.now()};try{let m=Math.min(Date.now()+1e4,e.expiresAtMs);while(!Z(P.readyPath)){if(R)throw new r("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if(e.signal.aborted||Date.now()>=m)throw C("process_start_unconfirmed");await ue(25)}let S=JSON.parse(Ne(P.readyPath,"utf8"));if(S.launchId!==P.launchId||S.fenceId!==P.fenceId||S.workerArtifactSha256!==b)throw C();if(e.signal.throwIfAborted(),c.cancelRequested)return pe(e.claim.operation_id);let f;try{q=!0,f=await V("start")}catch(D){if(!(D instanceof r)||D.code!=="hands_job_result_unknown")throw D;f=await V("inspect")}if(c.phase="running",c.cancel=async()=>{await V("cancel")},w&&e.preview)c.tunnels=le({claim:e.claim,executorLaunchId:P.launchId,expiresAtMs:e.expiresAtMs,deniedPorts:e.preview.deniedPorts,inspect:async()=>c.phase==="running"&&!R?await V("probe"):null});if(c.cancelRequested)await c.cancel(),f=await V("inspect");for(;;){if(!["starting","running"].includes(f.state))c.phase="settling",c.cancel=void 0;if(!M||M.state!==f.state||M.next_cursor!==f.nextCursor&&Date.now()-oe>=5000)await ve(f);if(!["starting","running"].includes(f.state))break;if(e.signal.aborted||R)throw C();await ue(1000);try{f=await V("inspect"),te=void 0}catch(D){if(!(D instanceof r)||D.code!=="hands_job_result_unknown"||e.signal.aborted||R||Date.now()-(te??=Date.now())>120000)throw D}}if(!M||M.state==="uncertain")throw C();return M}finally{if(c.phase="settling",c.cancel=void 0,c.tunnels?.dispose(),c.tunnels=void 0,await c.cancelInFlight?.catch(()=>{}),e.signal.removeEventListener("abort",re),!R&&!U)ct(x,"SIGTERM");let m,S=await Promise.race([F.then((f)=>({code:f})),new Promise((f)=>{m=setTimeout(()=>f(null),6000)})]).finally(()=>{clearTimeout(m)});if(!S){try{ct(x,"SIGKILL")}catch{}try{await F}finally{if(R)l.disposeSocket()}throw C("process_cleanup_unconfirmed")}try{if((U||e.signal.aborted)&&S.code===0&&q){v(E);let f=JSON.parse(h(P.directTerminalReceiptPath)),D=X.safeParse(f.observation);if(Object.keys(f).length===4&&f.launch_id===P.launchId&&f.fence_id===P.fenceId&&f.scope_id===l.scopeId&&D.success&&D.data.process_id===e.claim.operation_id){if(w)z();throw new st(D.data)}}}catch(f){if(f instanceof st)throw f}finally{if(R)l.disposeSocket()}if(S.code!==0&&!U&&q)throw C("process_cleanup_unconfirmed");if(!U&&S.code===0&&(M&&["exited","cancelled","expired"].includes(M.state)||!q&&c.cancelRequested)||w&&S.code===0&&!q)z()}}async function js(e,c){if(c.kind===ce&&e.capability===he){let I=H.get(e.operation_id);if(I?.claim===e&&I.tunnels)I.tunnels.open(c.payload);else Y(c.payload,e.operation_id,"server_not_running");return!0}if(c.kind!==ne||!ae(e.capability)||!e.owner||c.payload.process_id!==e.operation_id)return!1;let _=H.get(e.operation_id);if(_&&_.claim!==e)return!1;let l=be(e);if(l.cancelRequested=!0,l.phase==="running"&&l.cancel)l.cancelInFlight??=l.cancel(),await l.cancelInFlight;return!0}function Hs(e,c){H.delete(e);let _=B.get(e);if(!_||c!=="succeeded"&&!_.anyCompletion)return B.delete(e),!1;try{let l=me(_.path);if(!l.isDirectory()||l.isSymbolicLink()||l.ino!==_.ino||l.dev!==_.dev||!A(l)||G(_.path)!==_.path||Z(j(_.path,"owner.lock")))return!1;return Ve(_.path,{recursive:!0}),B.delete(e),!0}catch{return!1}}
4
4
  export{Xi,Yi,_n,Zi,yn,Qi,st,fr,js,Hs};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Qe}from"./vm-hands-entry-lite-vn7ag8c7.js";import{a}from"./vm-hands-entry-lite-8dfw96ym.js";import{randomUUID as L}from"crypto";import{spawnSync as b}from"child_process";import{chmodSync as ee,cpSync as te,existsSync as x,lstatSync as A,mkdirSync as Y,readdirSync as ne,readFileSync as w,readlinkSync as re,realpathSync as T,renameSync as E,rmdirSync as ie,rmSync as g,symlinkSync as M,writeFileSync as oe}from"fs";import{dirname as I,join as u,relative as se,resolve as ce}from"path";var Yn="so.ara.cli",k=[Yn,"com.reasonmachines.cli"],F="5LJFSBRY2F";function Gr(e){return`(${e.map((t)=>`identifier "${t}"`).join(" or ")}) and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = "${F}"`}var G="ReasonBackgroundIdentity",$o="Contents/Helpers/ReasonPermissionTile",ae="so.ara.cli.permission-tile",Ne=Gr([ae,"com.reasonmachines.cli.permission-tile"]),v="AraBackgroundIdentity",ue="Reason",Ce=Gr(k),de=`anchor apple generic and (${k.map((e)=>`identifier "${e}"`).join(" or ")}) and certificate leaf[subject.OU] = "${F}"`;class h extends Error{code;constructor(e,t){super(t);this.code=e;this.name="MacOSBackgroundIdentityError"}}var R="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";function le(e=a()){return u(e,"Library","Application Support","Reason","Background","Reason.app")}function O(e=a()){return u(e,"Library","Application Support","Ara","Background","Ara.app")}function fe(e){try{return A(e).isFile()}catch{return!1}}function D(e){return[G,v].map((t)=>u(e,"Contents","MacOS",t)).find(fe)??null}function d(e){try{if(!A(e).isDirectory())return!1;let t=w(u(e,"Contents","Info.plist"),"utf8");return k.some((n)=>t.includes(`<string>${n}</string>`))&&(t.includes(`<string>${ue}</string>`)||t.includes("<string>Ara</string>"))&&D(e)!==null}catch{return!1}}function Kr(e=a()){let t=le(e);if(!d(t))return null;try{let n=w(u(t,"Contents","Info.plist"),"utf8");return/<key>CFBundleVersion<\/key>\s*<string>(\d+\.\d+\.\d+)<\/string>/.exec(n)?.[1]??null}catch{return null}}function pe(e,t=a()){let n=Kr(t);return n===null||j(N(n.split(".")),N(e.split(/[.-]/).slice(0,3)))}var ge=1e4;function K(e,t){return b(e,[...t],{stdio:"ignore",timeout:ge}).status??1}var W=new Set;function H(e){if(process.env.REASON_TEST_REFUSE_REAL_IDENTITY!=="1")return;let t=(n)=>{try{return T(n)}catch{return ce(n)}};if(e!==void 0&&t(e)!==t(a()))return;throw Error("A test tried to change this computer's real Reason background identity; pass a temporary home. Refused by scripts/test-env.ts.")}var V=/\/(?:runtime|CLI)\/versions\/(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$|\/\.(?:ara|reason)(?:-staging)?-worker-(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$/,J=new Set(["ara","ara.exe","reason","reason.exe"]);function N(e){return e.map((t)=>Number(t))}function j(e,t){for(let n=0;n<3;n+=1)if(e[n]!==t[n])return e[n]<t[n];return!1}var ye=[0,2,161];function me(e){if(e===null)return!0;let t=ye,n=null;try{n=T(process.execPath)}catch{}return e.some((r)=>{let i=V.exec(r);if(i){let f=i[1]===void 0?i.slice(4,7):i.slice(1,4);return j(N(f),t)}let o=r.slice(r.lastIndexOf("/")+1);return J.has(o)&&r!==n&&r!==process.execPath})}function Ee(){let e=b("/bin/ps",["-xo","pid=,comm="],{encoding:"utf8",timeout:5000});if(e.status!==0)return null;let t=[];for(let n of e.stdout.split(`
2
+ import{Qe}from"./vm-hands-entry-lite-qdzbd077.js";import{a}from"./vm-hands-entry-lite-8dfw96ym.js";import{randomUUID as L}from"crypto";import{spawnSync as b}from"child_process";import{chmodSync as ee,cpSync as te,existsSync as x,lstatSync as A,mkdirSync as Y,readdirSync as ne,readFileSync as w,readlinkSync as re,realpathSync as T,renameSync as E,rmdirSync as ie,rmSync as g,symlinkSync as M,writeFileSync as oe}from"fs";import{dirname as I,join as u,relative as se,resolve as ce}from"path";var Yn="so.ara.cli",k=[Yn,"com.reasonmachines.cli"],F="5LJFSBRY2F";function Gr(e){return`(${e.map((t)=>`identifier "${t}"`).join(" or ")}) and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = "${F}"`}var G="ReasonBackgroundIdentity",$o="Contents/Helpers/ReasonPermissionTile",ae="so.ara.cli.permission-tile",Ne=Gr([ae,"com.reasonmachines.cli.permission-tile"]),v="AraBackgroundIdentity",ue="Reason",Ce=Gr(k),de=`anchor apple generic and (${k.map((e)=>`identifier "${e}"`).join(" or ")}) and certificate leaf[subject.OU] = "${F}"`;class h extends Error{code;constructor(e,t){super(t);this.code=e;this.name="MacOSBackgroundIdentityError"}}var R="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";function le(e=a()){return u(e,"Library","Application Support","Reason","Background","Reason.app")}function O(e=a()){return u(e,"Library","Application Support","Ara","Background","Ara.app")}function fe(e){try{return A(e).isFile()}catch{return!1}}function D(e){return[G,v].map((t)=>u(e,"Contents","MacOS",t)).find(fe)??null}function d(e){try{if(!A(e).isDirectory())return!1;let t=w(u(e,"Contents","Info.plist"),"utf8");return k.some((n)=>t.includes(`<string>${n}</string>`))&&(t.includes(`<string>${ue}</string>`)||t.includes("<string>Ara</string>"))&&D(e)!==null}catch{return!1}}function Kr(e=a()){let t=le(e);if(!d(t))return null;try{let n=w(u(t,"Contents","Info.plist"),"utf8");return/<key>CFBundleVersion<\/key>\s*<string>(\d+\.\d+\.\d+)<\/string>/.exec(n)?.[1]??null}catch{return null}}function pe(e,t=a()){let n=Kr(t);return n===null||j(N(n.split(".")),N(e.split(/[.-]/).slice(0,3)))}var ge=1e4;function K(e,t){return b(e,[...t],{stdio:"ignore",timeout:ge}).status??1}var W=new Set;function H(e){if(process.env.REASON_TEST_REFUSE_REAL_IDENTITY!=="1")return;let t=(n)=>{try{return T(n)}catch{return ce(n)}};if(e!==void 0&&t(e)!==t(a()))return;throw Error("A test tried to change this computer's real Reason background identity; pass a temporary home. Refused by scripts/test-env.ts.")}var V=/\/(?:runtime|CLI)\/versions\/(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$|\/\.(?:ara|reason)(?:-staging)?-worker-(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$/,J=new Set(["ara","ara.exe","reason","reason.exe"]);function N(e){return e.map((t)=>Number(t))}function j(e,t){for(let n=0;n<3;n+=1)if(e[n]!==t[n])return e[n]<t[n];return!1}var ye=[0,2,161];function me(e){if(e===null)return!0;let t=ye,n=null;try{n=T(process.execPath)}catch{}return e.some((r)=>{let i=V.exec(r);if(i){let f=i[1]===void 0?i.slice(4,7):i.slice(1,4);return j(N(f),t)}let o=r.slice(r.lastIndexOf("/")+1);return J.has(o)&&r!==n&&r!==process.execPath})}function Ee(){let e=b("/bin/ps",["-xo","pid=,comm="],{encoding:"utf8",timeout:5000});if(e.status!==0)return null;let t=[];for(let n of e.stdout.split(`
3
3
  `)){let r=/^\s*(\d+)\s+(\S.*)$/.exec(n);if(!r||Number(r[1])===process.pid)continue;let i=r[2].trimEnd(),o=i.slice(i.lastIndexOf("/")+1);if(!V.test(i)&&J.has(o)){let c=b("/usr/sbin/lsof",["-a","-p",r[1],"-d","txt","-Fn"],{encoding:"utf8",timeout:5000}).stdout?.split(`
4
4
  `).find((l)=>l.startsWith("n/"));if(c)i=c.slice(1)}t.push(i)}return t}function _e(e){if(H(e.home),!d(e.sourceApp))throw new h("identity_invalid","The packaged Reason background identity is missing or invalid.");let t=e.command??K,n=le(e.home),r=I(n);Y(r,{recursive:!0,mode:448}),ee(r,448);let i=T(e.sourceApp),o=null;try{o=T(n)}catch{}if(i!==o){let f=`${process.pid}.${L()}`,c=u(r,`.Reason.app.${f}.tmp`),l=u(r,`.Reason.app.${f}.old`),y=!1;try{if(te(i,c,{recursive:!0,errorOnExist:!0,preserveTimestamps:!0}),!d(c))throw new h("identity_invalid","The copied Reason background identity is invalid.");let _=e.releaseSigned?["--test-requirement",`=${de}`]:[];if(t("/usr/bin/codesign",["--verify","--strict",..._,c])!==0)throw new h("identity_invalid_signature","The installed Reason background identity has an invalid signature.");let S=!1;for(let p=0;p<4;p+=1){let m=!1;try{E(n,l),m=!0,y=!0}catch(s){if(s.code!=="ENOENT")throw s}if(p===0)e.beforePublish?.();try{E(c,n),S=!0}catch(s){let Z=s.code;if(!["EEXIST","ENOTEMPTY"].includes(Z??""))throw s;if(m)g(l,{recursive:!0,force:!0}),y=!1;if(p===3)throw s;continue}if(m)g(l,{recursive:!0,force:!0}),y=!1;break}if(!S)throw Error("Could not publish Reason's background identity.")}catch(_){if(y&&!x(n)&&x(l))E(l,n);throw _}finally{g(c,{recursive:!0,force:!0}),g(l,{recursive:!0,force:!0})}}return z(n,e,{verified:i!==o}),n}function X(e){return u(I(e),".Reason.app.registered")}function q(e){try{let t=A(e);return t.isDirectory()?`${t.ino}:${t.birthtimeMs}`:null}catch{return null}}function C(e){let t=q(e);try{return t!==null&&w(X(e),"utf8")===t}catch{return!1}}function Q(e){if(d(e))return"bundle";try{if(A(u(e,"Contents","Info.plist"),{throwIfNoEntry:!1}))return null;return A(u(e,"Contents","MacOS",v)).isSymbolicLink()?"retired":null}catch{return null}}function z(e,t,n={}){let r=t.command??K;if(!n.verified&&r("/usr/bin/codesign",["--verify","--strict",e])!==0)throw new h("identity_invalid_signature","The installed Reason background identity has an invalid signature.");if(r(R,["-f",e])!==0)throw new h("identity_register_failed","Could not register Reason's macOS background identity.");let i=q(e);try{if(i)oe(X(e),i,{mode:384})}catch{}try{Se(e,t.home,r,t.runningExecutables??Ee)}catch(o){let f=o.code??"unknown";process.stderr.write(`Reason background identity: legacy_identity_retire_failed (${f})
5
5
  `)}}function Se(e,t,n,r){let i=D(e);if(!i)return;let o=O(t),f=I(o),c=(s)=>u(s,"Contents","MacOS",v),l=se(I(c(o)),i),y=`${process.pid}.${L()}`,_=Q(o);if(_===null)return;let S=_==="bundle";if(S)n(R,["-u",o]);let p=u(f,`.Ara.app.${y}.old`);if(!W.has(o)&&!me(r())){if(!S)n(R,["-u",o]);try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}g(p,{recursive:!0,force:!0}),Ie(f);return}if(!S){if(re(c(o))===l)return;let s=`${c(o)}.${y}`;M(l,s);try{E(s,c(o))}finally{g(s,{force:!0})}return}let m=u(f,`.Ara.app.${y}.shim`);Y(I(c(m)),{recursive:!0}),M(l,c(m));try{try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}try{E(m,o)}catch(s){if(x(o))return;throw E(p,o),s}}finally{g(m,{recursive:!0,force:!0}),g(p,{recursive:!0,force:!0})}}function Ie(e){try{if(ne(e).some((n)=>n!==".DS_Store"))return;g(u(e,".DS_Store"),{force:!0}),ie(e)}catch{}}var B=new Map;function Zn(e=a()){let t=B.get(e);if(t)return t;if(process.platform!=="darwin")return[];let n=U(e);if(n===null&&x(I(le(e))))Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100),n=U(e);if(n===null)return[];return B.set(e,n),n}function U(e){let t=le(e),n=O(e);if(!d(t)||!C(t))try{he({home:e,skipWhenSettled:!0})}catch{}let r=d(t)&&(C(t)||!d(n))?t:d(n)?n:null,i=r?D(r):null;if(!i)return null;if(r===n)W.add(n);let o=b(i,["--can-spawn"],{env:{},timeout:2000,encoding:"utf8"});return o.status===0&&o.stdout===`spawn
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{E}from"./vm-hands-entry-lite-72nj66ab.js";import{fe,De,Ne,Le,$e}from"./vm-hands-entry-lite-b6gsggvp.js";import{spawn as y}from"child_process";import{existsSync as p,mkdirSync as T,readFileSync as _,writeFileSync as A}from"fs";import{homedir as m}from"os";import{basename as H,delimiter as g,join as f,win32 as u}from"path";var Cr=process.platform==="win32"?De("win32"):"/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",P=Cr.split(g),R=5000,S=65536,O=new Set(["zsh","bash"]),b=[[".local","bin"],[".bun","bin"],[".cargo","bin"],["go","bin"]],x=(t,e)=>new Promise((n,r)=>{let o;try{o=y(t,[...e],{...Ne(),stdio:["ignore","pipe","ignore"]}),Le(o)}catch(c){r(c);return}let i=[],s=0,a=null,L=(c)=>{a??=Error(c);try{if(o.pid!==void 0)$e(o.pid,"SIGKILL")}catch{}},d=setTimeout(()=>L("login_shell_timeout"),R);o.stdout?.on("data",(c)=>{if(s+=c.length,s>S)L("login_shell_output_too_large");else i.push(c)}),o.once("error",(c)=>{clearTimeout(d),r(c)}),o.once("close",(c)=>{if(clearTimeout(d),a)r(a);else if(c!==0)r(Error("login_shell_exit_nonzero"));else n(Buffer.concat(i).toString("utf8"))})});function w(t){return typeof t==="string"&&t.startsWith("/")&&!t.includes("\x00")&&O.has(H(t))}function h(t){let e=new Set,n=[];for(let r of t){if(e.has(r))continue;e.add(r),n.push(r)}return n}function Ar(t,e=process.platform){let n=e==="win32",r=t.split(`
2
+ import{E}from"./vm-hands-entry-lite-46pwqvpf.js";import{fe,De,Ne,Le,$e}from"./vm-hands-entry-lite-tyem93c1.js";import{spawn as y}from"child_process";import{existsSync as p,mkdirSync as T,readFileSync as _,writeFileSync as A}from"fs";import{homedir as m}from"os";import{basename as H,delimiter as g,join as f,win32 as u}from"path";var Cr=process.platform==="win32"?De("win32"):"/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",P=Cr.split(g),R=5000,S=65536,O=new Set(["zsh","bash"]),b=[[".local","bin"],[".bun","bin"],[".cargo","bin"],["go","bin"]],x=(t,e)=>new Promise((n,r)=>{let o;try{o=y(t,[...e],{...Ne(),stdio:["ignore","pipe","ignore"]}),Le(o)}catch(c){r(c);return}let i=[],s=0,a=null,L=(c)=>{a??=Error(c);try{if(o.pid!==void 0)$e(o.pid,"SIGKILL")}catch{}},d=setTimeout(()=>L("login_shell_timeout"),R);o.stdout?.on("data",(c)=>{if(s+=c.length,s>S)L("login_shell_output_too_large");else i.push(c)}),o.once("error",(c)=>{clearTimeout(d),r(c)}),o.once("close",(c)=>{if(clearTimeout(d),a)r(a);else if(c!==0)r(Error("login_shell_exit_nonzero"));else n(Buffer.concat(i).toString("utf8"))})});function w(t){return typeof t==="string"&&t.startsWith("/")&&!t.includes("\x00")&&O.has(H(t))}function h(t){let e=new Set,n=[];for(let r of t){if(e.has(r))continue;e.add(r),n.push(r)}return n}function Ar(t,e=process.platform){let n=e==="win32",r=t.split(`
3
3
  `).at(-1)??"",o=[];for(let i of r.split(n?";":":")){let s=i.trim();if(n?!u.isAbsolute(s):!s.startsWith("/"))continue;if(s.includes("\x00"))continue;if(E(s))continue;o.push(s)}return h(o)}function xn(t){let e=t?.home??m(),n=t?.directoryExists??p,r=b.map((o)=>f(e,...o)).filter((o)=>{try{return n(o)}catch{return!1}});return h([...r,...process.platform==="win32"?Ar(process.env.PATH??process.env.Path??""):[],...P]).join(g)}async function C(t){let e=t?.shell??process.env.SHELL,n=()=>({path:xn({home:t?.home,directoryExists:t?.directoryExists}),source:"fallback"});if(process.platform==="win32"||!w(e))return n();let r;try{r=await(t?.runLoginShell??x)(e,["-lic",'printf %s "$PATH"'])}catch{return n()}if(Buffer.byteLength(r,"utf8")>S)return n();let o=Ar(r);if(o.length===0)return n();return{path:h([...o,...P]).join(":"),source:"login_shell"}}function uo(t){let e=null;return()=>(e??=C(t),e)}function l(t){if(t===void 0||t.includes("\x00")||Buffer.byteLength(t,"utf8")>32768)return;return t}function Ue(t){let e=t.source??process.env,n={HOME:t.home,PATH:t.path??Cr,TMPDIR:t.temporaryDirectory,SHELL:l(e.SHELL)??"/bin/zsh",LANG:l(e.LANG)??"C.UTF-8",LC_ALL:l(e.LC_ALL)??l(e.LANG)??"C.UTF-8"},r=l(e.LC_CTYPE),o=l(e.TERM),i=l(e.COLORTERM);if(r)n.LC_CTYPE=r;if(o)n.TERM=o;if(i)n.COLORTERM=i;if(process.platform==="win32"){for(let s of I){let a=l(e[s]);if(a)n[s]=a}n.TEMP=n.TMP=t.temporaryDirectory,n.SHELL=fe()??n.SHELL,n.PATH=kn(n.PATH)}return n}function kn(t,e=f(m(),".reason","python3")){let n=(i)=>t.split(u.delimiter).filter((s)=>s&&!/[\\/]WindowsApps[\\/]?$/i.test(s)).map((s)=>u.join(s,i)).find((s)=>p(s)),r=n("python.exe");if(n("python3.exe")||!r)return t;let o=`#!/bin/sh
4
4
  exec "${r.replaceAll("\\","/")}" "$@"
5
5
  `;try{let i=f(e,"python3");if(!p(i)||_(i,"utf8")!==o)T(e,{recursive:!0}),A(i,o)}catch{return t}return[e,t].join(u.delimiter)}var I=["SystemRoot","SystemDrive","windir","ComSpec","PATHEXT","USERPROFILE","USERNAME","USERDOMAIN","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","CommonProgramFiles","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"];
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{A}from"./vm-hands-entry-lite-b6gsggvp.js";import{randomUUID as m}from"crypto";import{closeSync as k,constants as c,fstatSync as u,lstatSync as s,mkdirSync as l,openSync as E,readFileSync as S,realpathSync as a,renameSync as g,unlinkSync as p,writeFileSync as O}from"fs";import{dirname as w,resolve as _}from"path";var d=65536;function f(r){try{return s(r),!0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return!1;throw o}}function v(r,o=!1){if(!f(r)){if(!o)throw Error("worker_state_missing");y(r),l(r,{mode:448})}let e=s(r);if(!e.isDirectory()||e.isSymbolicLink()||!A(e)||a(r)!==_(r))throw Error("worker_state_directory_not_private_or_canonical")}function y(r){let o=w(r);if(!f(o))y(o),l(o,{mode:448});if(a(o)!==_(o))throw Error("worker_parent_not_canonical")}function h(r,o=d){let e=E(r,c.O_RDONLY|c.O_NOFOLLOW);try{let n=u(e);if(!n.isFile()||n.nlink!==1||!A(n)||n.size>o)throw Error("worker_file_not_private");return S(e,"utf8")}finally{k(e)}}function mo(r,o,e=d){let n=JSON.stringify(o);if(n===void 0)throw Error("worker_file_invalid");let t=n+`
2
+ import{A}from"./vm-hands-entry-lite-tyem93c1.js";import{randomUUID as m}from"crypto";import{closeSync as k,constants as c,fstatSync as u,lstatSync as s,mkdirSync as l,openSync as E,readFileSync as S,realpathSync as a,renameSync as g,unlinkSync as p,writeFileSync as O}from"fs";import{dirname as w,resolve as _}from"path";var d=65536;function f(r){try{return s(r),!0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return!1;throw o}}function v(r,o=!1){if(!f(r)){if(!o)throw Error("worker_state_missing");y(r),l(r,{mode:448})}let e=s(r);if(!e.isDirectory()||e.isSymbolicLink()||!A(e)||a(r)!==_(r))throw Error("worker_state_directory_not_private_or_canonical")}function y(r){let o=w(r);if(!f(o))y(o),l(o,{mode:448});if(a(o)!==_(o))throw Error("worker_parent_not_canonical")}function h(r,o=d){let e=E(r,c.O_RDONLY|c.O_NOFOLLOW);try{let n=u(e);if(!n.isFile()||n.nlink!==1||!A(n)||n.size>o)throw Error("worker_file_not_private");return S(e,"utf8")}finally{k(e)}}function mo(r,o,e=d){let n=JSON.stringify(o);if(n===void 0)throw Error("worker_file_invalid");let t=n+`
3
3
  `;if(Buffer.byteLength(t,"utf8")>e)throw Error("worker_file_too_large");if(v(w(r)),f(r))h(r,e);let i=`${r}.${m()}`;try{O(i,t,{mode:384,flag:"wx"}),g(i,r)}finally{if(f(i))p(i)}}
4
4
  export{f,v,h,mo};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- var Xt=String.raw`(function(loadFfi, existsSync) {
2
+ var Wt=String.raw`(function(loadFfi, existsSync) {
3
3
  const STARTF_USESTDHANDLES = 0x100;
4
4
  const CREATE_SUSPENDED = 0x4;
5
5
  const CREATE_UNICODE_ENVIRONMENT = 0x400;
@@ -242,4 +242,4 @@ var Xt=String.raw`(function(loadFfi, existsSync) {
242
242
  }
243
243
  return { available, unavailableReason, defaultShell, shellArgs, quoteArg, environmentBlock, spawn };
244
244
  })`;
245
- export{Xt};
245
+ export{Wt};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ge,pt}from"./vm-hands-entry-lite-k9vk84wa.js";import{Qe}from"./vm-hands-entry-lite-vn7ag8c7.js";import{$o,le,Kr,gt,Mo}from"./vm-hands-entry-lite-8s4namcq.js";import{E}from"./vm-hands-entry-lite-72nj66ab.js";import{a,nr}from"./vm-hands-entry-lite-8dfw96ym.js";import{spawnSync as H}from"child_process";import{dirname as w}from"path";import{spawn as A}from"child_process";import{accessSync as _,constants as v}from"fs";import{basename as C,join as O}from"path";var l=null;function S(e){if(l===e)l=null;if(e.exitCode===null&&e.signalCode===null)e.kill("SIGTERM")}var Ir=(e,t)=>{if(l)S(l);let s=O(e,$o);try{_(s,v.X_OK)}catch{return()=>{}}let n;try{n=A(s,["--app",e,"--name",C(e,".app"),"--permission",t==="screen"?"screen_recording":"accessibility"],{detached:!0,stdio:"ignore"})}catch{return()=>{}}return n.on("error",()=>{if(l===n)l=null}),n.once("exit",()=>{if(l===n)l=null}),n.unref(),l=n,()=>S(n)};import{chmodSync as ne,existsSync as se,mkdirSync as re,readFileSync as D,realpathSync as ie,renameSync as oe,statSync as j,writeFileSync as ae}from"fs";import{dirname as de,isAbsolute as G,join as N,resolve as T,sep as b}from"path";function F(e=a()){return N(nr(e),"reason","protected-path-grants.json")}var f=null;function L(e){let t=JSON.parse(e);if(!Array.isArray(t?.grants))return[];return t.grants.flatMap((s)=>{let n=s;return n&&typeof n.path==="string"&&G(n.path)&&(n.kind==="file"||n.kind==="folder")&&typeof n.grantedAt==="number"?[{path:n.path,kind:n.kind,grantedAt:n.grantedAt}]:[]})}function y(e=F()){try{let{mtimeMs:t}=j(e);if(f&&f.file===e&&f.mtimeMs===t)return f.grants;let s=L(D(e,"utf8"));return f={file:e,mtimeMs:t,grants:s},s}catch{return[]}}function W(e,t){return e.kind==="file"?t===e.path:t===e.path||t.startsWith(`${e.path}${b}`)}function U(e,t){let s=T(e);return y(t).some((n)=>W(n,s))}function wo(e,t){return E(e)&&!U(e,t)}function bo(e,t,s){let n=t?"file-read* file-write*":"file-read*";return y(s).filter((r)=>r.path===e||r.path.startsWith(`${e}${b}`)).map((r)=>`(allow ${n} (${r.kind==="file"?"literal":"subpath"} ${JSON.stringify(r.path)}))`)}var P="x-apple.systempreferences:com.apple.preference.security",J="curl -fsSL https://reasonmachines.com/install.sh | bash",q=180000,B=2000;var k={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${P}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${P}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${P}?Privacy_AllFiles`}};function R(e){return e.executable}function K(e,t){if(e==="computer_use_identity_missing")return`Reason's background identity is not installed (${e}); reinstall Reason: ${J}`;if(e==="computer_use_identity_outdated")return`Reason's background identity is outdated (${Kr(t)??"unknown"}; this CLI is ${Qe}) (${e}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${e}); run the installed \`reason\``}function ls(e=a()){let t=gt(e);if(t.length>0)return{state:"ready",path:w(w(w(t[0]))),prefix:t};let s=Mo(t,e)??"computer_use_identity_unavailable";return{state:s,path:le(e),detail:K(s,e)}}function V(){return{identity:()=>ls(),grants:(e)=>Ge(e),request:(e,t)=>pt(e,t),worker:async()=>(await import("./status-mtmtkbbp.js")).connectionMacState(),open:(e)=>{H("/usr/bin/open",e,{stdio:"ignore",timeout:1e4})},tile:Ir,restartConnection:async()=>(await import("./connect-cli-xgbm9xfg.js")).restartConnection(),sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now()}}function M(e,t,s){if(e.state!=="ready"||!t)return"unknown";return t[s]?"granted":"missing"}async function us(e){let t=e.identity(),s=t.state==="ready"?await e.grants(t.prefix):null,n=await e.worker(),r=n?R(n):null,i=!r||n?.full_disk_access==="unknown"?"unknown":n?.full_disk_access==="granted"?"granted":"missing",c=(u,d,o)=>{let{label:p,purpose:h,level:m}=k[u];return{id:u,label:p,purpose:h,level:m,state:d,holder:o}};return{identity:{state:t.state,path:t.path,detail:t.state==="ready"?null:t.detail},worker_detail:r?null:"Full Disk Access is read from this computer's running worker; `reason connect` starts it.",permissions:[c("screen",M(t,s,"screen"),t.path),c("accessibility",M(t,s,"accessibility"),t.path),c("disk",i,r)]}}function Ks(e){let t=e.identity.state==="ready"?null:e.identity.state,s=e.permissions.filter((i)=>i.state==="granted").length,n=[...t?[t]:[],...e.permissions.filter((i)=>i.state!=="granted"&&!(t&&i.id!=="disk")).map((i)=>`${i.label} ${i.state}`)],r=!t&&e.permissions.some((i)=>i.state==="missing");return`Permissions: ${s} of ${e.permissions.length}${n.length>0?` (${n.join(", ")})`:""}`+(r?" \u2014 reason permissions allow":n.length>0?" \u2014 reason permissions":"")}async function x(e,t){let s=t.now()+q;for(;;){if(await e())return!0;if(t.now()>=s)return!1;await t.sleep(B)}}async function Js(e,t){let s=t.host??V(),{io:n}=t,r=await us(s),i=r.permissions.filter((o)=>e.includes(o.id)&&o.state!=="granted");if(i.length===0)return n.stdout.write(`Reason permissions: ${e.map((o)=>k[o].label).join(", ")} already allowed.
2
+ import{Ye,ft}from"./vm-hands-entry-lite-2v4zh9ze.js";import{Qe}from"./vm-hands-entry-lite-qdzbd077.js";import{$o,le,Kr,gt,Mo}from"./vm-hands-entry-lite-ggyexab2.js";import{E}from"./vm-hands-entry-lite-46pwqvpf.js";import{a,nr}from"./vm-hands-entry-lite-8dfw96ym.js";import{spawnSync as H}from"child_process";import{dirname as w}from"path";import{spawn as A}from"child_process";import{accessSync as _,constants as v}from"fs";import{basename as C,join as O}from"path";var l=null;function S(e){if(l===e)l=null;if(e.exitCode===null&&e.signalCode===null)e.kill("SIGTERM")}var qr=(e,t)=>{if(l)S(l);let s=O(e,$o);try{_(s,v.X_OK)}catch{return()=>{}}let n;try{n=A(s,["--app",e,"--name",C(e,".app"),"--permission",t==="screen"?"screen_recording":"accessibility"],{detached:!0,stdio:"ignore"})}catch{return()=>{}}return n.on("error",()=>{if(l===n)l=null}),n.once("exit",()=>{if(l===n)l=null}),n.unref(),l=n,()=>S(n)};import{chmodSync as ne,existsSync as se,mkdirSync as re,readFileSync as D,realpathSync as ie,renameSync as oe,statSync as j,writeFileSync as ae}from"fs";import{dirname as de,isAbsolute as G,join as N,resolve as T,sep as b}from"path";function F(e=a()){return N(nr(e),"reason","protected-path-grants.json")}var f=null;function L(e){let t=JSON.parse(e);if(!Array.isArray(t?.grants))return[];return t.grants.flatMap((s)=>{let n=s;return n&&typeof n.path==="string"&&G(n.path)&&(n.kind==="file"||n.kind==="folder")&&typeof n.grantedAt==="number"?[{path:n.path,kind:n.kind,grantedAt:n.grantedAt}]:[]})}function y(e=F()){try{let{mtimeMs:t}=j(e);if(f&&f.file===e&&f.mtimeMs===t)return f.grants;let s=L(D(e,"utf8"));return f={file:e,mtimeMs:t,grants:s},s}catch{return[]}}function W(e,t){return e.kind==="file"?t===e.path:t===e.path||t.startsWith(`${e.path}${b}`)}function U(e,t){let s=T(e);return y(t).some((n)=>W(n,s))}function So(e,t){return E(e)&&!U(e,t)}function Eo(e,t,s){let n=t?"file-read* file-write*":"file-read*";return y(s).filter((r)=>r.path===e||r.path.startsWith(`${e}${b}`)).map((r)=>`(allow ${n} (${r.kind==="file"?"literal":"subpath"} ${JSON.stringify(r.path)}))`)}var P="x-apple.systempreferences:com.apple.preference.security",J="curl -fsSL https://reasonmachines.com/install.sh | bash",q=180000,B=2000;var k={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${P}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${P}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${P}?Privacy_AllFiles`}};function R(e){return e.executable}function K(e,t){if(e==="computer_use_identity_missing")return`Reason's background identity is not installed (${e}); reinstall Reason: ${J}`;if(e==="computer_use_identity_outdated")return`Reason's background identity is outdated (${Kr(t)??"unknown"}; this CLI is ${Qe}) (${e}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${e}); run the installed \`reason\``}function us(e=a()){let t=gt(e);if(t.length>0)return{state:"ready",path:w(w(w(t[0]))),prefix:t};let s=Mo(t,e)??"computer_use_identity_unavailable";return{state:s,path:le(e),detail:K(s,e)}}function V(){return{identity:()=>us(),grants:(e)=>Ye(e),request:(e,t)=>ft(e,t),worker:async()=>(await import("./status-m1crm0qs.js")).connectionMacState(),open:(e)=>{H("/usr/bin/open",e,{stdio:"ignore",timeout:1e4})},tile:qr,restartConnection:async()=>(await import("./connect-cli-jbwaswpq.js")).restartConnection(),sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now()}}function M(e,t,s){if(e.state!=="ready"||!t)return"unknown";return t[s]?"granted":"missing"}async function ds(e){let t=e.identity(),s=t.state==="ready"?await e.grants(t.prefix):null,n=await e.worker(),r=n?R(n):null,i=!r||n?.full_disk_access==="unknown"?"unknown":n?.full_disk_access==="granted"?"granted":"missing",c=(u,d,o)=>{let{label:p,purpose:h,level:m}=k[u];return{id:u,label:p,purpose:h,level:m,state:d,holder:o}};return{identity:{state:t.state,path:t.path,detail:t.state==="ready"?null:t.detail},worker_detail:r?null:"Full Disk Access is read from this computer's running worker; `reason connect` starts it.",permissions:[c("screen",M(t,s,"screen"),t.path),c("accessibility",M(t,s,"accessibility"),t.path),c("disk",i,r)]}}function Ks(e){let t=e.identity.state==="ready"?null:e.identity.state,s=e.permissions.filter((i)=>i.state==="granted").length,n=[...t?[t]:[],...e.permissions.filter((i)=>i.state!=="granted"&&!(t&&i.id!=="disk")).map((i)=>`${i.label} ${i.state}`)],r=!t&&e.permissions.some((i)=>i.state==="missing");return`Permissions: ${s} of ${e.permissions.length}${n.length>0?` (${n.join(", ")})`:""}`+(r?" \u2014 reason permissions allow":n.length>0?" \u2014 reason permissions":"")}async function x(e,t){let s=t.now()+q;for(;;){if(await e())return!0;if(t.now()>=s)return!1;await t.sleep(B)}}async function Js(e,t){let s=t.host??V(),{io:n}=t,r=await ds(s),i=r.permissions.filter((o)=>e.includes(o.id)&&o.state!=="granted");if(i.length===0)return n.stdout.write(`Reason permissions: ${e.map((o)=>k[o].label).join(", ")} already allowed.
3
3
  `),0;let c=!1,u=!1,d=s.identity();for(let o of i){let{label:p,pane:h}=k[o.id];if(o.id!=="disk"){if(d.state!=="ready"){if(!c)n.stderr.write(`Reason permissions: ${d.detail}
4
4
  `);c=!0;continue}let g=o.id;await s.request(d.prefix,g),s.open([h]);let I=s.tile(d.path,g);if(n.stdout.write(`Allow Reason in System Settings > Privacy & Security > ${p}.
5
5
  `),!t.wait)continue;if(n.stdout.write(`Waiting for it (Ctrl-C to stop)\u2026
@@ -11,4 +11,4 @@ import{Ge,pt}from"./vm-hands-entry-lite-k9vk84wa.js";import{Qe}from"./vm-hands-e
11
11
  `),await x(async()=>(await s.worker())?.full_disk_access==="granted",s))n.stdout.write(`Full Disk Access: granted.
12
12
  `);else n.stderr.write("Full Disk Access is not reported yet. If you allowed it, `reason connect` restarts the worker with it.\n"),c=!0}if(u)try{if(await s.restartConnection())n.stdout.write(`This computer's Reason connection restarted to use them.
13
13
  `)}catch(o){n.stderr.write(`This computer's Reason connection uses them after it restarts (\`reason connect\`): ${o instanceof Error?o.message:String(o)}
14
- `)}return c?1:0}export{Ir,wo,bo,ls,us,Ks,Js};
14
+ `)}return c?1:0}export{qr,So,Eo,us,ds,Ks,Js};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{We,go,j,Ve,Ht,Tr,x}from"./vm-hands-entry-lite-ycddfgr4.js";import{K}from"./vm-hands-entry-lite-xrqztkhv.js";import{pt}from"./vm-hands-entry-lite-k9vk84wa.js";import{gt}from"./vm-hands-entry-lite-8s4namcq.js";import{Ir}from"./vm-hands-entry-lite-6pqfr3w2.js";import{Pt,Hi}from"./vm-hands-entry-lite-xe0benev.js";import{G,qe}from"./vm-hands-entry-lite-8hwmhvyx.js";import{xe,Jn}from"./vm-hands-entry-lite-55ja13pk.js";import{St}from"./vm-hands-entry-lite-07apxfh8.js";import{a}from"./vm-hands-entry-lite-8dfw96ym.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-b6gsggvp.js";import{spawn as v,spawnSync as st}from"child_process";import{createHash as it,randomUUID as ge}from"crypto";import{closeSync as at,copyFileSync as ae,existsSync as D,fstatSync as ct,mkdirSync as ce,openSync as lt,readdirSync as L,readFileSync as X,readlinkSync as ut,renameSync as he,rmSync as dt,statSync as mt,writeFileSync as ft}from"fs";import{connect as ht}from"net";import{tmpdir as U,userInfo as _e}from"os";import{basename as le,delimiter as _t,dirname as B,join as f}from"path";var z=`import { spawn, execFileSync } from "node:child_process";
2
+ import{Je,wo,U,Xe,Jt,zr,x}from"./vm-hands-entry-lite-8mttvhef.js";import{K}from"./vm-hands-entry-lite-wghmyfba.js";import{ft}from"./vm-hands-entry-lite-2v4zh9ze.js";import{gt}from"./vm-hands-entry-lite-ggyexab2.js";import{qr}from"./vm-hands-entry-lite-h78c4zxd.js";import{Pt,Hi}from"./vm-hands-entry-lite-qd46yhvz.js";import{G,qe}from"./vm-hands-entry-lite-sqzryt00.js";import{xe,Jn}from"./vm-hands-entry-lite-6qq4f3v5.js";import{St}from"./vm-hands-entry-lite-07apxfh8.js";import{a}from"./vm-hands-entry-lite-8dfw96ym.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-tyem93c1.js";import{spawn as v,spawnSync as st}from"child_process";import{createHash as it,randomUUID as ge}from"crypto";import{closeSync as at,copyFileSync as ae,existsSync as D,fstatSync as ct,mkdirSync as ce,openSync as lt,readdirSync as L,readFileSync as X,readlinkSync as ut,renameSync as he,rmSync as dt,statSync as pt,writeFileSync as mt}from"fs";import{connect as ht}from"net";import{tmpdir as B,userInfo as _e}from"os";import{basename as le,delimiter as _t,dirname as q,join as f}from"path";var z=`import { spawn, execFileSync } from "node:child_process";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { readFileSync, readlinkSync, lstatSync, realpathSync, statSync, mkdtempSync, mkdirSync, chmodSync, writeFileSync, readdirSync, rmSync, openSync, readSync, closeSync, renameSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
@@ -950,7 +950,7 @@ if(process.env.REASON_CLOUD_GATEWAY_EXEC === "1") {
950
950
  process.stdout.write(JSON.stringify(cloudAutomationFailure(error))+"\\n");process.exitCode=1;
951
951
  }
952
952
  }
953
- `;import{spawn as Ce}from"child_process";import{lstatSync as V,readFileSync as Z,rmSync as Ne}from"fs";import{basename as Pe}from"path";var Me="__desktop-call",De="/usr/bin/setpriv",Le=27262976,Ue=8192,$e=2000;function q(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function Be(e){try{return JSON.parse(e)}catch{return null}}function Fe(){return[process.execPath,...Pe(process.execPath).startsWith("bun")&&process.argv[1]?[process.argv[1]]:[],Me]}function He(e){let o=(i)=>{try{return V(i).uid}catch{return null}},t=V("/tmp/.X11-unix",{throwIfNoEntry:!1});if(!t?.isDirectory()||t.uid!==0)return;let n=["/tmp/.X99-lock","/tmp/.X11-unix/X99"].filter((i)=>{let u=o(i);return u!==null&&u!==e.uid});if(!n.length)return;let s="";try{let i=Z("/tmp/.X99-lock","utf8").trim();if(/^\d+$/.test(i))s=Z(`/proc/${i}/comm`,"utf8").trim()}catch{}if(/^X/.test(s))return;for(let i of n)Ne(i,{force:!0})}function Bt(e,o,t,n={}){if(t.throwIfAborted(),(o.op==="display"||o.op==="automation")&&process.platform==="linux"&&process.getuid?.()===0)try{He(e)}catch{}let s=n.command??Fe();return new Promise((i,u)=>{let c=(n.spawnProcess??Ce)(De,[`--reuid=${e.uid}`,`--regid=${e.gid}`,"--clear-groups","--no-new-privs","--",...s],{cwd:e.home,detached:!0,stdio:["pipe","pipe","pipe"],env:{HOME:e.home,USER:e.username,LOGNAME:e.username,PATH:"/usr/local/bin:/usr/bin:/bin"}}),d=[],m=0,l="",p=null,g=!1,_,h=(y)=>{try{process.kill(-c.pid,y)}catch{c.kill(y)}},I=(y)=>{p??=y,h("SIGTERM"),_??=setTimeout(()=>h("SIGKILL"),$e)},S=()=>I(new r("cancelled","Reason cancelled the desktop operation."));t.addEventListener("abort",S,{once:!0});let w=(y)=>{if(g)return;g=!0,clearTimeout(_),t.removeEventListener("abort",S),y()};if(c.stdout.on("data",(y)=>{if(m+=y.byteLength,m>Le)I(new r("desktop_delegate_failed","Reason's desktop reply is too large."));else d.push(y)}),c.stderr.setEncoding("utf8").on("data",(y)=>{l=(l+y).slice(-Ue)}),c.stdin.on("error",()=>{}),c.once("error",()=>w(()=>u(p??new r("desktop_delegate_unavailable","Reason could not start its desktop as the desktop account.")))),c.once("close",(y,Ee)=>w(()=>{if(p)return u(p);let b=Be(Buffer.concat(d).toString("utf8"));if(q(b)&&b.ok===!0&&q(b.result))return i(b.result);let A=q(b)&&b.ok===!1&&typeof b.code==="string"&&typeof b.message==="string"?new r(b.code.slice(0,120),b.message.slice(0,2000)):null,J=`exited ${y??Ee}${A?"":" with no reply"}`,Y=l.trim().split(`
953
+ `;import{spawn as Ce}from"child_process";import{lstatSync as V,readFileSync as Z,rmSync as Ne}from"fs";import{basename as Pe}from"path";var Me="__desktop-call",De="/usr/bin/setpriv",Le=27262976,Ue=8192,$e=2000;function W(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function Be(e){try{return JSON.parse(e)}catch{return null}}function We(){return[process.execPath,...Pe(process.execPath).startsWith("bun")&&process.argv[1]?[process.argv[1]]:[],Me]}function Fe(e){let o=(i)=>{try{return V(i).uid}catch{return null}},t=V("/tmp/.X11-unix",{throwIfNoEntry:!1});if(!t?.isDirectory()||t.uid!==0)return;let n=["/tmp/.X99-lock","/tmp/.X11-unix/X99"].filter((i)=>{let u=o(i);return u!==null&&u!==e.uid});if(!n.length)return;let s="";try{let i=Z("/tmp/.X99-lock","utf8").trim();if(/^\d+$/.test(i))s=Z(`/proc/${i}/comm`,"utf8").trim()}catch{}if(/^X/.test(s))return;for(let i of n)Ne(i,{force:!0})}function Bt(e,o,t,n={}){if(t.throwIfAborted(),(o.op==="display"||o.op==="automation")&&process.platform==="linux"&&process.getuid?.()===0)try{Fe(e)}catch{}let s=n.command??We();return new Promise((i,u)=>{let c=(n.spawnProcess??Ce)(De,[`--reuid=${e.uid}`,`--regid=${e.gid}`,"--clear-groups","--no-new-privs","--",...s],{cwd:e.home,detached:!0,stdio:["pipe","pipe","pipe"],env:{HOME:e.home,USER:e.username,LOGNAME:e.username,PATH:"/usr/local/bin:/usr/bin:/bin"}}),d=[],m=0,l="",p=null,g=!1,_,h=(y)=>{try{process.kill(-c.pid,y)}catch{c.kill(y)}},I=(y)=>{p??=y,h("SIGTERM"),_??=setTimeout(()=>h("SIGKILL"),$e)},S=()=>I(new r("cancelled","Reason cancelled the desktop operation."));t.addEventListener("abort",S,{once:!0});let w=(y)=>{if(g)return;g=!0,clearTimeout(_),t.removeEventListener("abort",S),y()};if(c.stdout.on("data",(y)=>{if(m+=y.byteLength,m>Le)I(new r("desktop_delegate_failed","Reason's desktop reply is too large."));else d.push(y)}),c.stderr.setEncoding("utf8").on("data",(y)=>{l=(l+y).slice(-Ue)}),c.stdin.on("error",()=>{}),c.once("error",()=>w(()=>u(p??new r("desktop_delegate_unavailable","Reason could not start its desktop as the desktop account.")))),c.once("close",(y,Ee)=>w(()=>{if(p)return u(p);let b=Be(Buffer.concat(d).toString("utf8"));if(W(b)&&b.ok===!0&&W(b.result))return i(b.result);let A=W(b)&&b.ok===!1&&typeof b.code==="string"&&typeof b.message==="string"?new r(b.code.slice(0,120),b.message.slice(0,2000)):null,J=`exited ${y??Ee}${A?"":" with no reply"}`,Y=l.trim().split(`
954
954
  `).at(-1)?.slice(-300)??"";if(!A||A.code==="desktop_delegate_failed")process.stderr.write(`Reason worker: desktop call ${J}${l?`: ${l.trim().slice(-500)}`:""}
955
- `);if(A)return u(A);u(new r("desktop_delegate_failed",`Reason's desktop operation failed (${J}${Y?`: ${Y}`:""}).`))})),t.aborted)S();c.stdin.end(JSON.stringify(o))})}async function Q(e,o,t,n={}){let s=await Bt(e,{op:"automation",call:o},t,n);if(!Number.isSafeInteger(s.code)||typeof s.stdout!=="string"||typeof s.stderr!=="string")throw new r("desktop_delegate_failed","Reason's desktop reply is malformed.");return{code:s.code,stdout:Buffer.from(s.stdout,"base64"),stderr:s.stderr}}import{execFile as Ge,spawn as je}from"child_process";import{closeSync as Xe,mkdirSync as Ke,openSync as Je}from"fs";import{dirname as E,join as Ye}from"path";import{promisify as ze}from"util";var Ze=ze(Ge),ee="x-apple.systempreferences:com.apple.preference.security",Qe={accessibility:`${ee}?Privacy_Accessibility`,screen:`${ee}?Privacy_ScreenCapture`},et=64,O=new Map;function T(e,o){let t=O.get(e);if(t?.has(o))return!1;if(!t){if(O.size>=et)O.delete(O.keys().next().value);t=new Set,O.set(e,t)}return t.add(o),!0}function tt(){let e=a(),o=Jn(xe(e),process.env),t=Ye(e,".local","share","reason","desktop-install.log");Ke(E(t),{recursive:!0,mode:448});let n=Je(t,"a",384);try{let s=je(o,["desktop","install"],{detached:!0,stdio:["ignore",n,n],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});s.on("error",()=>{return}),s.unref()}finally{Xe(n)}}var N={open:async(e,o)=>{await Ze("/usr/bin/open",e,{signal:o,timeout:1e4,maxBuffer:8192})},request:(e,o)=>pt(e,o),tile:Ir,installDesktop:tt},te=!1;async function oe(e,o,t){try{await o.open(["-a","Google Chrome",e],t)}catch{t.throwIfAborted(),await o.open([e],t)}}async function ne(e,o,t,n){if(await t.open([Qe[o]],n).catch(()=>{}),e[0]&&!n.aborted)t.tile(E(E(E(e[0]))),o)}async function ot(e,o,t,n,s){for(let i of t){if(!T(e,`grant:${i}`))continue;s.throwIfAborted(),await n.request(o,i).catch(()=>null),await ne(o,i,n,s)}}var rt={name:"open_tab",description:"Open a web page in the user's own Chrome on this Mac. Reason cannot read, screenshot or click in that tab, and no tab_id is returned: browser control needs Reason's Chrome extension. An actual browser call opens its setup page.",inputSchema:{type:"object",properties:{url:{type:"string",description:"An http or https URL."}},required:["url"],additionalProperties:!1}};function re(e){return{code:0,stderr:"",stdout:Buffer.from(JSON.stringify({ok:!0,...e}))}}function nt(e){if(typeof e!=="string")return null;try{let o=new URL(e);return o.protocol==="https:"||o.protocol==="http:"?o.href:null}catch{return null}}async function se(e,o=N){let{call:t,runId:n,signal:s}=e;if(t.kind==="browser"){if(t.operation==="discover")return re({result:{tools:[rt]}});if(t.operation!=="call")throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet. Request a browser operation or connect Chrome from Reason to set it up.")}if(e.desktopMissing&&!te){te=!0;try{o.installDesktop()}catch{}}if(t.kind==="computer"){if(e.identity.length>0&&T(n,"grant:probe")){let c=await o.request(e.identity).catch(()=>null),d=c?[...c.accessibility?[]:["accessibility"],...c.screen?[]:["screen"]]:[];for(let m of d)T(n,`grant:${m}`);for(let m of d)await ne(e.identity,m,o,s)}throw new r("automation_computer_setup_required","Computer use is not set up on this Mac yet; Reason asked macOS for any missing permission.")}if(T(n,"page:chrome-extension"))await oe(go,o,s).catch(()=>{});let i=t.arguments,u=t.operation==="call"&&t.tool==="open_tab"&&i&&typeof i==="object"&&!Array.isArray(i)?nt(i.url):null;if(!u)throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet; Reason opened its Chrome Web Store page. open_tab still opens pages.");return await oe(u,o,s),re({result:{content:[{type:"text",text:JSON.stringify({opened:u,browser:"the user's Chrome",controllable:!1,note:"Opened for the user to see. Reason cannot read or act in this tab until Reason's Chrome extension is added (its Chrome Web Store page is open)."})}]}})}async function ie(e,o=N){if(e.call.kind!=="computer"||e.call.operation!=="permission_status"||e.output.code!==0||e.identity.length===0)return e.output;let t;try{t=JSON.parse(e.output.stdout.toString("utf8"))}catch{return e.output}if(!t||typeof t!=="object"||Array.isArray(t))return e.output;let n=t.permissions;if(!n||typeof n!=="object")return e.output;let s=n,i=[...s.accessibility==="missing"?["accessibility"]:[],...s.screenRecording==="missing"?["screen"]:[]];if(i.length===0)return e.output;return await ot(e.runId,e.identity,i,o,e.signal),{...e.output,stdout:Buffer.from(JSON.stringify({...t,requested:i}))}}var H=172032,wt=18874368,yt=8192,bt=65536,xt=55000,kt=60000,vt=4,It=40000,Rt=/^[0-9a-f-]{36}$/,ue=z,At=ge();function P(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function M(){throw new r("invalid_automation_request","Reason automation request is malformed.")}function we(e){let o=Object.keys(e).sort().join(",");if(o==="call"||o==="browser,call"){let t=e.call,n=o==="browser,call";if(!P(t)||t.version!==1||t.kind!=="computer"&&t.kind!=="browser"||n&&(e.browser!==St||t.kind!=="browser")||JSON.stringify(t).length>bt)M();return{call:t,userChrome:n}}if(o==="offset,output_id"){if(typeof e.output_id!=="string"||!Rt.test(e.output_id)||!Number.isSafeInteger(e.offset)||e.offset<0)M();return{output_id:e.output_id,offset:e.offset}}return M()}function Pn(e=process.platform,o=x){if(e==="darwin")return!0;return(e==="linux"||e==="win32")&&o()?.features.computer===!0}var Ot="__computer-use";function Us(e=x){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function ye(e,o,t,n){return new Promise((s)=>{let i=v(e,o,{env:t,stdio:"ignore",windowsHide:!0}),u=setTimeout(()=>{i.kill("SIGKILL"),s(-1)},n);i.once("error",()=>{clearTimeout(u),s(-1)}),i.once("exit",(c)=>{clearTimeout(u),s(c??-1)})})}function Et(e,o,t,n){return new Promise((s)=>{let i=v(e,o,{env:t,stdio:["ignore","pipe","ignore"],windowsHide:!0}),u="";i.stdout.setEncoding("utf8").on("data",(d)=>{u+=d});let c=setTimeout(()=>{i.kill("SIGKILL"),s(null)},n);i.once("error",()=>{clearTimeout(c),s(null)}),i.once("close",(d)=>{clearTimeout(c),s(d===0?u:null)})})}function Tt(e){return R(e)?f(U(),"open-browser-use"):"/tmp/open-browser-use"}function R(e){return e.platform==="win32-x64"||e.platform==="win32-arm64"}var Ct=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Nt=33554432;function Mt(e,o){let t;try{t=e===null?null:JSON.parse(e)}catch{return null}let n=P(t)&&P(t.result)?t.result.metadata:null;if(!P(n)||n.extensionId!==o)return null;return typeof n.extensionInstanceId==="string"&&Ct.test(n.extensionInstanceId)?n.extensionInstanceId:null}async function be(e,o,t){let n=t.storages.map((c)=>{try{return L(c).filter((d)=>d.endsWith(".log")||d.endsWith(".ldb")).map((d)=>f(c,d))}catch{return[]}}),s;try{s=n.some((c)=>c.length>0)?L(t.socketDir).filter((c)=>c.endsWith(".sock")):[]}catch{return[]}let i=[];for(let c of s){let d=f(t.socketDir,c),m=Mt(await Et(e,["info","--socket",d,"--timeout","2s"],o,5000),t.extensionId);if(m)i.push({instance:m,socket:d})}let u=[];for(let[c,d]of(i.length>0?n:[]).entries())for(let m of d)try{if(mt(m).size>Nt)continue;let l=X(m),p=i.find((g)=>l.includes(g.instance));if(p){u.push({storage:t.storages[c],...p});break}}catch{}return u}async function Dt(e,o,t){return(await be(e,o,t))[0]?.instance??null}function Se(e,o,t){return Dt(e.nativeHost,o,{socketDir:Tt(e),extensionId:j,storages:[f(t,"browser-profile","Default","Local Extension Settings",j)]})}var de=/^(Default|Profile ([0-9]+))$/;async function Lt(e,o,t=a(),n=Ht){let s=f(t,"Library","Application Support","Google","Chrome"),i=[];try{i=L(s)}catch(l){if(l.code==="EPERM")throw new r("browser_use_chrome_access_denied","macOS blocked Reason from reading Chrome's profiles. Allow Full Disk Access for Reason on this Mac and try again.")}let u=(l)=>Number(de.exec(l)?.[2]??-1),c=i.filter((l)=>de.test(l)&&D(f(s,l,"Extensions",We))).sort((l,p)=>u(l)-u(p)),d=(l)=>f(s,l,"Local Extension Settings",We);return(await be(e,o,{socketDir:n,extensionId:We,storages:c.map(d)})).map(({storage:l,instance:p,socket:g})=>({profile:c.find((_)=>d(_)===l),instance:p,socket:g}))}async function Ut(e,o,t=a(),n=Ht){let s=(await Lt(e,o,t,n))[0]?.instance;if(!s)throw new r("automation_user_chrome_not_connected","No Chrome profile on this Mac is connected to Reason. Open Chrome with the Reason extension, then try again.");return s}function pe(e){return new Promise((o)=>{let t=ht({path:e}),n=(s)=>{t.destroy(),o(s)};t.setTimeout(1000,()=>n(!1)),t.once("error",()=>n(!1)),t.once("connect",()=>n(!0))})}async function ke(e,o){let t=Date.now()+o;while(Date.now()<t){if(await e())return!0;await new Promise((n)=>setTimeout(n,200))}return!1}var W=new Map;function F(e,o){let t=W.get(e);if(!t)t=o().finally(()=>W.delete(e)),W.set(e,t);return t}async function $t(e,o){if(await pe(e))return;if(dt(e,{force:!0}),await ye("dbus-daemon",["--session",`--address=unix:path=${e}`,"--fork"],o,1e4)!==0||!await ke(()=>pe(e),5000))throw new r("automation_unavailable","Reason could not start the desktop session bus.")}async function me(e,o,t){let n=e.platform==="darwin-arm64"||R(e)?async()=>await Se(e,o,t)!==null:async()=>await ye(e.nativeHost,["info"],o,5000)===0;if(await n())return;let s=["--profile-directory=Default",`--load-extension=${e.extensionDir}`,"--no-first-run","--no-default-browser-check","--window-size=1280,800","about:blank"],i,u=null,c=0;if(e.platform==="darwin-arm64"){let l=f(t,"browser-profile");G(l);let p=f(l,"NativeMessagingHosts");ce(p,{recursive:!0,mode:448});let g=Tr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let _=e.browser.slice(0,e.browser.indexOf(".app/")+4),h=s.filter((I)=>I!=="about:blank").concat("--no-startup-window","--use-mock-keychain");i=v("/usr/bin/open",["-g","-n","-a",_,"--args",`--user-data-dir=${l}`,...h],{env:o,stdio:"ignore"})}else if(R(e)){let l=f(t,"browser-profile");G(l),st(C("icacls"),[B(e.browser),"/grant","*S-1-15-2-1:(OI)(CI)(RX)","*S-1-15-2-2:(OI)(CI)(RX)"],{stdio:"ignore",windowsHide:!0,timeout:60000});let p=s.filter((g)=>g!=="about:blank").concat("--no-startup-window","--keep-alive-for-test");i=v(e.browser,[`--user-data-dir=${l}`,...p],{detached:!0,stdio:"ignore",env:o})}else{let l=f(o.HOME,".config","google-chrome"),p=f(l,"NativeMessagingHosts");ce(p,{recursive:!0,mode:448});let g=Tr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let _=process.geteuid?.()===0?["--no-sandbox"]:[];u=f(t,"browser.log");let h=lt(u,"a",384);c=ct(h).size,i=v(e.browser,[`--user-data-dir=${l}`,...s,..._,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",h,h],env:{...o,ACCESSIBILITY_ENABLED:"1"}}),at(h)}let d=!1;i.once("error",()=>{d=!0}),i.once("exit",(l)=>{d||=l!==0}),i.unref();let m=!1;if(await ke(async()=>d||(m=await n()),It),!m){if(u&&X(u).subarray(c).toString("utf8").includes("No usable sandbox"))throw new r("automation_browser_sandbox_unavailable","Chromium found no usable sandbox on this machine. Run the worker as a non-root user with unprivileged user namespaces enabled, or in a container with seccomp unconfined.");throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function zs(e){await Re(e,!0)}function qs(e){return ve(e,Ie(e))}function ve(e,o){return e.platform==="darwin-arm64"||R(e)?f(o,"browser-profile"):f(o,"home",".config","google-chrome")}function Ie(e){let o=f(e.root,"automation");if(!D(o)||!qt(e.automation))return e.automation;if(!Wt(ve(e,o)))try{he(o,e.automation)}catch{}return D(o)?o:e.automation}function qt(e){try{return L(e).length===0}catch(o){return o.code==="ENOENT"}}function Wt(e){let o;try{o=ut(f(e,"SingletonLock"))}catch{return!1}let t=Number(o.slice(o.lastIndexOf("-")+1));if(!Number.isSafeInteger(t)||t<=0)return!0;try{return process.kill(t,0),!0}catch(n){return n.code==="EPERM"}}async function Re(e,o){Pt({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=Ie(e);G(t);let n=_e().username,s={USER:n,LOGNAME:n,REASON_AUTOMATION_OCU:e.ocu,REASON_AUTOMATION_OBU:e.nativeHost};if(e.platform==="darwin-arm64"||R(e)){let l=R(e)?{...s,...Ft(),HOME:a()}:{...s,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:Ot};if(!o)return l;await F("browser",()=>me(e,l,t));let p=await Se(e,l,t);if(!p)throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.");return{...l,REASON_AUTOMATION_OBU_INSTANCE:p,REASON_AUTOMATION_BACKGROUND_TABS:"1"}}let i=await qe(),u=f(t,"home"),c=f(t,"runtime");G(u),G(c);let d=f(t,"bus"),m={...s,HOME:u,PATH:`${B(e.node)}:/usr/bin:/bin`,DISPLAY:i.display,XAUTHORITY:i.xauthority,XDG_RUNTIME_DIR:c,DBUS_SESSION_BUS_ADDRESS:`unix:path=${d}`,...i.sound?{PULSE_SERVER:Ve(i.sound)}:{}};if(await F("bus",()=>$t(d,m)),o)await F("browser",()=>me(e,m,t));return m}function Ft(){let e=process.env.SystemRoot??"C:\\Windows",o=Object.fromEntries(["SystemDrive","USERPROFILE","LOCALAPPDATA","APPDATA","ProgramData","ProgramFiles","PATHEXT","ComSpec","USERNAME","USERDOMAIN","COMPUTERNAME","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","PSModuleAnalysisCachePath"].flatMap((n)=>process.env[n]?[[n,process.env[n]]]:[])),t=f(e,"System32");return{...o,SystemRoot:e,windir:e,TEMP:U(),TMP:U(),PATH:[t,f(t,"WindowsPowerShell","v1.0"),e].join(_t)}}async function Gt(e,o,t){let n=_e().username,s={USER:n,LOGNAME:n,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OBU:o,REASON_AUTOMATION_BACKGROUND_TABS:"1"},i=await Ut(o,s);return t.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:i}}function jt(e){if(process.platform!=="win32")return["--input-type=module","--eval",e];let o=f(U(),`reason-automation-${it("sha256").update(e).digest("hex").slice(0,16)}.mjs`);if(!D(o)||X(o,"utf8")!==e){let t=`${o}.${process.pid}.tmp`;ft(t,e,{mode:384}),he(t,o)}return[o]}function Ae(e,o,t,n){if(typeof ue!=="string")return Promise.reject(new r("automation_unavailable","This Reason build has no automation runtime."));let s=ue;return new Promise((i,u)=>{let c=v(e,jt(s),{env:{...o,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),d=[],m=0,l="",p=null,g=!1,_=(w)=>{if(p??=w,process.platform==="win32"&&c.pid){v(f(process.env.SystemRoot??"C:\\Windows","System32","taskkill.exe"),["/pid",String(c.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0}).once("error",()=>c.kill("SIGKILL"));return}try{process.kill(-c.pid,"SIGKILL")}catch{c.kill("SIGKILL")}},h=(w)=>{if(g)return;g=!0,clearTimeout(I),n.removeEventListener("abort",S),w()},I=setTimeout(()=>_(new r("automation_timed_out","Reason automation did not finish in time.")),xt),S=()=>_(new r("cancelled","Reason cancelled the automation call."));if(n.addEventListener("abort",S,{once:!0}),c.stdout.on("data",(w)=>{if(m+=w.byteLength,m>wt)_(new r("automation_output_too_large","Reason automation output is too large."));else d.push(w)}),c.stderr.setEncoding("utf8").on("data",(w)=>{l=(l+w).slice(-yt)}),c.stdin.on("error",()=>{}),c.once("error",()=>h(()=>u(p??new r("automation_unavailable","Reason could not start the automation runtime.")))),c.once("close",(w)=>h(()=>{if(p)u(p);else i({code:w??1,stdout:Buffer.concat(d),stderr:l})})),n.aborted)S();c.stdin.end(t)})}var k=new Map;function Xt(e,o,t){for(let[s,i]of k)if(i.expiresAt<=t)k.delete(s);while(k.size>=vt)k.delete(k.keys().next().value);let n=ge();return k.set(n,{runId:e,bytes:o,expiresAt:t+kt}),n}async function Oe(e,o,t,n={}){let s=await(n.environment??Re)(e,o.kind==="browser");return t.throwIfAborted(),await(n.runtime??Ae)(e.node,s,JSON.stringify(o),t)}async function Ws(e,o){let t=we({call:e});if(!("call"in t))M();let n=x();if(!n?.features.computer||t.call.kind==="browser"&&!n.features.browser)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");return await Oe(n,t.call,o)}function fe(e,o,t){let n=e.stdout.byteLength>H?Xt(o,e.stdout,t):void 0;return{code:e.code,stderr:e.stderr,instance_id:At,output_bytes:e.stdout.byteLength,chunk:e.stdout.subarray(0,H).toString("base64"),...n?{output_id:n}:{}}}async function Rn(e,o={}){let t=we(e.payload),n=(o.now??Date.now)();if("output_id"in t){let h=k.get(t.output_id);if(!h||h.runId!==e.runId||h.expiresAt<=n||t.offset>h.bytes.byteLength)throw new r("automation_output_unavailable","Reason automation output expired.");return{chunk:h.bytes.subarray(t.offset,t.offset+H).toString("base64")}}let s=(o.components??x)(),i=(o.platform??process.platform)==="darwin",u=i?(o.macIdentity??gt)():[],c=o.macSetup??N,d=!s?.features.computer||t.call.kind==="browser"&&!t.userChrome&&!s.features.browser;if(i&&(d||u.length===0||t.call.kind==="browser"&&t.userChrome&&!e.userChrome))return fe(await se({runId:e.runId,call:t.call,identity:u,desktopMissing:d,signal:e.signal},c),e.runId,n);if(!s?.features.computer)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let m=t.userChrome?e.userChrome:void 0;if(t.userChrome&&!m)throw new r("automation_user_chrome_unavailable","Your own Chrome is not enabled on this computer: run `reason desktop install` on this Mac (and `reason connect --user-chrome on` if you turned it off).");if(t.call.kind==="browser"&&!m&&!s.features.browser)throw new r("automation_browser_not_installed",!s.platform.startsWith("linux")?"Browser use is unavailable on this machine: re-run `reason desktop install`.":"Browser use is unavailable on this machine: install a non-snap Chromium at /usr/bin/chromium, then re-run `reason desktop install`.");e.signal.throwIfAborted();let l=t.call.kind==="browser"&&t.call.operation!=="record_start"&&t.call.operation!=="record_stop",p=await Hi(e.runId,e.signal,o.now,l?"call":"run"),g="account"in o?o.account??null:K(),_;try{if(m){let h=await(o.userChromeEnvironment??Gt)(s,m,e.signal);e.signal.throwIfAborted(),_=await(o.runtime??Ae)(s.node,h,JSON.stringify(t.call),e.signal)}else if(g)_=await(o.delegate??Q)(g,t.call,e.signal);else _=await Oe(s,t.call,e.signal,o)}finally{p()}if(i)_=await ie({runId:e.runId,call:t.call,identity:u,output:_,signal:e.signal},c);return fe(_,e.runId,n)}
955
+ `);if(A)return u(A);u(new r("desktop_delegate_failed",`Reason's desktop operation failed (${J}${Y?`: ${Y}`:""}).`))})),t.aborted)S();c.stdin.end(JSON.stringify(o))})}async function Q(e,o,t,n={}){let s=await Bt(e,{op:"automation",call:o},t,n);if(!Number.isSafeInteger(s.code)||typeof s.stdout!=="string"||typeof s.stderr!=="string")throw new r("desktop_delegate_failed","Reason's desktop reply is malformed.");return{code:s.code,stdout:Buffer.from(s.stdout,"base64"),stderr:s.stderr}}import{execFile as He,spawn as Ge}from"child_process";import{closeSync as je,mkdirSync as Ke,openSync as Ye}from"fs";import{dirname as E,join as ze}from"path";import{promisify as Ve}from"util";var Ze=Ve(He),ee="x-apple.systempreferences:com.apple.preference.security",Qe={accessibility:`${ee}?Privacy_Accessibility`,screen:`${ee}?Privacy_ScreenCapture`},et=64,O=new Map;function T(e,o){let t=O.get(e);if(t?.has(o))return!1;if(!t){if(O.size>=et)O.delete(O.keys().next().value);t=new Set,O.set(e,t)}return t.add(o),!0}function tt(){let e=a(),o=Jn(xe(e),process.env),t=ze(e,".local","share","reason","desktop-install.log");Ke(E(t),{recursive:!0,mode:448});let n=Ye(t,"a",384);try{let s=Ge(o,["desktop","install"],{detached:!0,stdio:["ignore",n,n],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});s.on("error",()=>{return}),s.unref()}finally{je(n)}}var N={open:async(e,o)=>{await Ze("/usr/bin/open",e,{signal:o,timeout:1e4,maxBuffer:8192})},request:(e,o)=>ft(e,o),tile:qr,installDesktop:tt},te=!1;async function oe(e,o,t){try{await o.open(["-a","Google Chrome",e],t)}catch{t.throwIfAborted(),await o.open([e],t)}}async function ne(e,o,t,n){if(await t.open([Qe[o]],n).catch(()=>{}),e[0]&&!n.aborted)t.tile(E(E(E(e[0]))),o)}async function ot(e,o,t,n,s){for(let i of t){if(!T(e,`grant:${i}`))continue;s.throwIfAborted(),await n.request(o,i).catch(()=>null),await ne(o,i,n,s)}}var rt={name:"open_tab",description:"Open a web page in the user's own Chrome on this Mac. Reason cannot read, screenshot or click in that tab, and no tab_id is returned: browser control needs Reason's Chrome extension. An actual browser call opens its setup page.",inputSchema:{type:"object",properties:{url:{type:"string",description:"An http or https URL."}},required:["url"],additionalProperties:!1}};function re(e){return{code:0,stderr:"",stdout:Buffer.from(JSON.stringify({ok:!0,...e}))}}function nt(e){if(typeof e!=="string")return null;try{let o=new URL(e);return o.protocol==="https:"||o.protocol==="http:"?o.href:null}catch{return null}}async function se(e,o=N){let{call:t,runId:n,signal:s}=e;if(t.kind==="browser"){if(t.operation==="discover")return re({result:{tools:[rt]}});if(t.operation!=="call")throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet. Request a browser operation or connect Chrome from Reason to set it up.")}if(e.desktopMissing&&!te){te=!0;try{o.installDesktop()}catch{}}if(t.kind==="computer"){if(e.identity.length>0&&T(n,"grant:probe")){let c=await o.request(e.identity).catch(()=>null),d=c?[...c.accessibility?[]:["accessibility"],...c.screen?[]:["screen"]]:[];for(let m of d)T(n,`grant:${m}`);for(let m of d)await ne(e.identity,m,o,s)}throw new r("automation_computer_setup_required","Computer use is not set up on this Mac yet; Reason asked macOS for any missing permission.")}if(T(n,"page:chrome-extension"))await oe(wo,o,s).catch(()=>{});let i=t.arguments,u=t.operation==="call"&&t.tool==="open_tab"&&i&&typeof i==="object"&&!Array.isArray(i)?nt(i.url):null;if(!u)throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet; Reason opened its Chrome Web Store page. open_tab still opens pages.");return await oe(u,o,s),re({result:{content:[{type:"text",text:JSON.stringify({opened:u,browser:"the user's Chrome",controllable:!1,note:"Opened for the user to see. Reason cannot read or act in this tab until Reason's Chrome extension is added (its Chrome Web Store page is open)."})}]}})}async function ie(e,o=N){if(e.call.kind!=="computer"||e.call.operation!=="permission_status"||e.output.code!==0||e.identity.length===0)return e.output;let t;try{t=JSON.parse(e.output.stdout.toString("utf8"))}catch{return e.output}if(!t||typeof t!=="object"||Array.isArray(t))return e.output;let n=t.permissions;if(!n||typeof n!=="object")return e.output;let s=n,i=[...s.accessibility==="missing"?["accessibility"]:[],...s.screenRecording==="missing"?["screen"]:[]];if(i.length===0)return e.output;return await ot(e.runId,e.identity,i,o,e.signal),{...e.output,stdout:Buffer.from(JSON.stringify({...t,requested:i}))}}var j=172032,wt=18874368,yt=8192,bt=65536,xt=55000,kt=60000,vt=4,It=40000,Rt=/^[0-9a-f-]{36}$/,ue=z,At=ge();function P(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function M(){throw new r("invalid_automation_request","Reason automation request is malformed.")}function we(e){let o=Object.keys(e).sort().join(",");if(o==="call"||o==="browser,call"){let t=e.call,n=o==="browser,call";if(!P(t)||t.version!==1||t.kind!=="computer"&&t.kind!=="browser"||n&&(e.browser!==St||t.kind!=="browser")||JSON.stringify(t).length>bt)M();return{call:t,userChrome:n}}if(o==="offset,output_id"){if(typeof e.output_id!=="string"||!Rt.test(e.output_id)||!Number.isSafeInteger(e.offset)||e.offset<0)M();return{output_id:e.output_id,offset:e.offset}}return M()}function Pn(e=process.platform,o=x){if(e==="darwin")return!0;return(e==="linux"||e==="win32")&&o()?.features.computer===!0}var Ot="__computer-use";function Us(e=x){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function ye(e,o,t,n){return new Promise((s)=>{let i=v(e,o,{env:t,stdio:"ignore",windowsHide:!0}),u=setTimeout(()=>{i.kill("SIGKILL"),s(-1)},n);i.once("error",()=>{clearTimeout(u),s(-1)}),i.once("exit",(c)=>{clearTimeout(u),s(c??-1)})})}function Et(e,o,t,n){return new Promise((s)=>{let i=v(e,o,{env:t,stdio:["ignore","pipe","ignore"],windowsHide:!0}),u="";i.stdout.setEncoding("utf8").on("data",(d)=>{u+=d});let c=setTimeout(()=>{i.kill("SIGKILL"),s(null)},n);i.once("error",()=>{clearTimeout(c),s(null)}),i.once("close",(d)=>{clearTimeout(c),s(d===0?u:null)})})}function Tt(e){return R(e)?f(B(),"open-browser-use"):"/tmp/open-browser-use"}function R(e){return e.platform==="win32-x64"||e.platform==="win32-arm64"}var Ct=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Nt=33554432;function Mt(e,o){let t;try{t=e===null?null:JSON.parse(e)}catch{return null}let n=P(t)&&P(t.result)?t.result.metadata:null;if(!P(n)||n.extensionId!==o)return null;return typeof n.extensionInstanceId==="string"&&Ct.test(n.extensionInstanceId)?n.extensionInstanceId:null}async function be(e,o,t){let n=t.storages.map((c)=>{try{return L(c).filter((d)=>d.endsWith(".log")||d.endsWith(".ldb")).map((d)=>f(c,d))}catch{return[]}}),s;try{s=n.some((c)=>c.length>0)?L(t.socketDir).filter((c)=>c.endsWith(".sock")):[]}catch{return[]}let i=[];for(let c of s){let d=f(t.socketDir,c),m=Mt(await Et(e,["info","--socket",d,"--timeout","2s"],o,5000),t.extensionId);if(m)i.push({instance:m,socket:d})}let u=[];for(let[c,d]of(i.length>0?n:[]).entries())for(let m of d)try{if(pt(m).size>Nt)continue;let l=X(m),p=i.find((g)=>l.includes(g.instance));if(p){u.push({storage:t.storages[c],...p});break}}catch{}return u}async function Dt(e,o,t){return(await be(e,o,t))[0]?.instance??null}function Se(e,o,t){return Dt(e.nativeHost,o,{socketDir:Tt(e),extensionId:U,storages:[f(t,"browser-profile","Default","Local Extension Settings",U)]})}var de=/^(Default|Profile ([0-9]+))$/;async function Lt(e,o,t=a(),n=Jt){let s=f(t,"Library","Application Support","Google","Chrome"),i=[];try{i=L(s)}catch(l){if(l.code==="EPERM")throw new r("browser_use_chrome_access_denied","macOS blocked Reason from reading Chrome's profiles. Allow Full Disk Access for Reason on this Mac and try again.")}let u=(l)=>Number(de.exec(l)?.[2]??-1),c=i.filter((l)=>de.test(l)&&D(f(s,l,"Extensions",Je))).sort((l,p)=>u(l)-u(p)),d=(l)=>f(s,l,"Local Extension Settings",Je);return(await be(e,o,{socketDir:n,extensionId:Je,storages:c.map(d)})).map(({storage:l,instance:p,socket:g})=>({profile:c.find((_)=>d(_)===l),instance:p,socket:g}))}async function Ut(e,o,t=a(),n=Jt){let s=(await Lt(e,o,t,n))[0]?.instance;if(!s)throw new r("automation_user_chrome_not_connected","No Chrome profile on this Mac is connected to Reason. Open Chrome with the Reason extension, then try again.");return s}function pe(e){return new Promise((o)=>{let t=ht({path:e}),n=(s)=>{t.destroy(),o(s)};t.setTimeout(1000,()=>n(!1)),t.once("error",()=>n(!1)),t.once("connect",()=>n(!0))})}async function ke(e,o){let t=Date.now()+o;while(Date.now()<t){if(await e())return!0;await new Promise((n)=>setTimeout(n,200))}return!1}var F=new Map;function H(e,o){let t=F.get(e);if(!t)t=o().finally(()=>F.delete(e)),F.set(e,t);return t}async function $t(e,o){if(await pe(e))return;if(dt(e,{force:!0}),await ye("dbus-daemon",["--session",`--address=unix:path=${e}`,"--fork"],o,1e4)!==0||!await ke(()=>pe(e),5000))throw new r("automation_unavailable","Reason could not start the desktop session bus.")}async function me(e,o,t){let n=e.platform==="darwin-arm64"||R(e)?async()=>await Se(e,o,t)!==null:async()=>await ye(e.nativeHost,["info"],o,5000)===0;if(await n())return;let s=["--profile-directory=Default",`--load-extension=${e.extensionDir}`,"--no-first-run","--no-default-browser-check","--window-size=1280,800","about:blank"],i,u=null,c=0;if(e.platform==="darwin-arm64"){let l=f(t,"browser-profile");G(l);let p=f(l,"NativeMessagingHosts");ce(p,{recursive:!0,mode:448});let g=zr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let _=e.browser.slice(0,e.browser.indexOf(".app/")+4),h=s.filter((I)=>I!=="about:blank").concat("--no-startup-window","--use-mock-keychain");i=v("/usr/bin/open",["-g","-n","-a",_,"--args",`--user-data-dir=${l}`,...h],{env:o,stdio:"ignore"})}else if(R(e)){let l=f(t,"browser-profile");G(l),st(C("icacls"),[q(e.browser),"/grant","*S-1-15-2-1:(OI)(CI)(RX)","*S-1-15-2-2:(OI)(CI)(RX)"],{stdio:"ignore",windowsHide:!0,timeout:60000});let p=s.filter((g)=>g!=="about:blank").concat("--no-startup-window","--keep-alive-for-test");i=v(e.browser,[`--user-data-dir=${l}`,...p],{detached:!0,stdio:"ignore",env:o})}else{let l=f(o.HOME,".config","google-chrome"),p=f(l,"NativeMessagingHosts");ce(p,{recursive:!0,mode:448});let g=zr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let _=process.geteuid?.()===0?["--no-sandbox"]:[];u=f(t,"browser.log");let h=lt(u,"a",384);c=ct(h).size,i=v(e.browser,[`--user-data-dir=${l}`,...s,..._,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",h,h],env:{...o,ACCESSIBILITY_ENABLED:"1"}}),at(h)}let d=!1;i.once("error",()=>{d=!0}),i.once("exit",(l)=>{d||=l!==0}),i.unref();let m=!1;if(await ke(async()=>d||(m=await n()),It),!m){if(u&&X(u).subarray(c).toString("utf8").includes("No usable sandbox"))throw new r("automation_browser_sandbox_unavailable","Chromium found no usable sandbox on this machine. Run the worker as a non-root user with unprivileged user namespaces enabled, or in a container with seccomp unconfined.");throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function zs(e){await Re(e,!0)}function qs(e){return ve(e,Ie(e))}function ve(e,o){return e.platform==="darwin-arm64"||R(e)?f(o,"browser-profile"):f(o,"home",".config","google-chrome")}function Ie(e){let o=f(e.root,"automation");if(!D(o)||!qt(e.automation))return e.automation;if(!Wt(ve(e,o)))try{he(o,e.automation)}catch{}return D(o)?o:e.automation}function qt(e){try{return L(e).length===0}catch(o){return o.code==="ENOENT"}}function Wt(e){let o;try{o=ut(f(e,"SingletonLock"))}catch{return!1}let t=Number(o.slice(o.lastIndexOf("-")+1));if(!Number.isSafeInteger(t)||t<=0)return!0;try{return process.kill(t,0),!0}catch(n){return n.code==="EPERM"}}async function Re(e,o){Pt({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=Ie(e);G(t);let n=_e().username,s={USER:n,LOGNAME:n,REASON_AUTOMATION_OCU:e.ocu,REASON_AUTOMATION_OBU:e.nativeHost};if(e.platform==="darwin-arm64"||R(e)){let l=R(e)?{...s,...Ft(),HOME:a()}:{...s,HOME:a(),PATH:`${q(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:Ot};if(!o)return l;await H("browser",()=>me(e,l,t));let p=await Se(e,l,t);if(!p)throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.");return{...l,REASON_AUTOMATION_OBU_INSTANCE:p,REASON_AUTOMATION_BACKGROUND_TABS:"1"}}let i=await qe(),u=f(t,"home"),c=f(t,"runtime");G(u),G(c);let d=f(t,"bus"),m={...s,HOME:u,PATH:`${q(e.node)}:/usr/bin:/bin`,DISPLAY:i.display,XAUTHORITY:i.xauthority,XDG_RUNTIME_DIR:c,DBUS_SESSION_BUS_ADDRESS:`unix:path=${d}`,...i.sound?{PULSE_SERVER:Xe(i.sound)}:{}};if(await H("bus",()=>$t(d,m)),o)await H("browser",()=>me(e,m,t));return m}function Ft(){let e=process.env.SystemRoot??"C:\\Windows",o=Object.fromEntries(["SystemDrive","USERPROFILE","LOCALAPPDATA","APPDATA","ProgramData","ProgramFiles","PATHEXT","ComSpec","USERNAME","USERDOMAIN","COMPUTERNAME","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","PSModuleAnalysisCachePath"].flatMap((n)=>process.env[n]?[[n,process.env[n]]]:[])),t=f(e,"System32");return{...o,SystemRoot:e,windir:e,TEMP:B(),TMP:B(),PATH:[t,f(t,"WindowsPowerShell","v1.0"),e].join(_t)}}async function Ht(e,o,t){let n=_e().username,s={USER:n,LOGNAME:n,HOME:a(),PATH:`${q(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OBU:o,REASON_AUTOMATION_BACKGROUND_TABS:"1"},i=await Ut(o,s);return t.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:i}}function Gt(e){if(process.platform!=="win32")return["--input-type=module","--eval",e];let o=f(B(),`reason-automation-${it("sha256").update(e).digest("hex").slice(0,16)}.mjs`);if(!D(o)||X(o,"utf8")!==e){let t=`${o}.${process.pid}.tmp`;mt(t,e,{mode:384}),he(t,o)}return[o]}function Ae(e,o,t,n){if(typeof ue!=="string")return Promise.reject(new r("automation_unavailable","This Reason build has no automation runtime."));let s=ue;return new Promise((i,u)=>{let c=v(e,Gt(s),{env:{...o,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),d=[],m=0,l="",p=null,g=!1,_=(w)=>{if(p??=w,process.platform==="win32"&&c.pid){v(f(process.env.SystemRoot??"C:\\Windows","System32","taskkill.exe"),["/pid",String(c.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0}).once("error",()=>c.kill("SIGKILL"));return}try{process.kill(-c.pid,"SIGKILL")}catch{c.kill("SIGKILL")}},h=(w)=>{if(g)return;g=!0,clearTimeout(I),n.removeEventListener("abort",S),w()},I=setTimeout(()=>_(new r("automation_timed_out","Reason automation did not finish in time.")),xt),S=()=>_(new r("cancelled","Reason cancelled the automation call."));if(n.addEventListener("abort",S,{once:!0}),c.stdout.on("data",(w)=>{if(m+=w.byteLength,m>wt)_(new r("automation_output_too_large","Reason automation output is too large."));else d.push(w)}),c.stderr.setEncoding("utf8").on("data",(w)=>{l=(l+w).slice(-yt)}),c.stdin.on("error",()=>{}),c.once("error",()=>h(()=>u(p??new r("automation_unavailable","Reason could not start the automation runtime.")))),c.once("close",(w)=>h(()=>{if(p)u(p);else i({code:w??1,stdout:Buffer.concat(d),stderr:l})})),n.aborted)S();c.stdin.end(t)})}var k=new Map;function jt(e,o,t){for(let[s,i]of k)if(i.expiresAt<=t)k.delete(s);while(k.size>=vt)k.delete(k.keys().next().value);let n=ge();return k.set(n,{runId:e,bytes:o,expiresAt:t+kt}),n}async function Oe(e,o,t,n={}){let s=await(n.environment??Re)(e,o.kind==="browser");return t.throwIfAborted(),await(n.runtime??Ae)(e.node,s,JSON.stringify(o),t)}async function Ws(e,o){let t=we({call:e});if(!("call"in t))M();let n=x();if(!n?.features.computer||t.call.kind==="browser"&&!n.features.browser)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");return await Oe(n,t.call,o)}function fe(e,o,t){let n=e.stdout.byteLength>j?jt(o,e.stdout,t):void 0;return{code:e.code,stderr:e.stderr,instance_id:At,output_bytes:e.stdout.byteLength,chunk:e.stdout.subarray(0,j).toString("base64"),...n?{output_id:n}:{}}}async function Rn(e,o={}){let t=we(e.payload),n=(o.now??Date.now)();if("output_id"in t){let h=k.get(t.output_id);if(!h||h.runId!==e.runId||h.expiresAt<=n||t.offset>h.bytes.byteLength)throw new r("automation_output_unavailable","Reason automation output expired.");return{chunk:h.bytes.subarray(t.offset,t.offset+j).toString("base64")}}let s=(o.components??x)(),i=(o.platform??process.platform)==="darwin",u=i?(o.macIdentity??gt)():[],c=o.macSetup??N,d=!s?.features.computer||t.call.kind==="browser"&&!t.userChrome&&!s.features.browser;if(i&&(d||u.length===0||t.call.kind==="browser"&&t.userChrome&&!e.userChrome))return fe(await se({runId:e.runId,call:t.call,identity:u,desktopMissing:d,signal:e.signal},c),e.runId,n);if(!s?.features.computer)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let m=t.userChrome?e.userChrome:void 0;if(t.userChrome&&!m)throw new r("automation_user_chrome_unavailable","Your own Chrome is not enabled on this computer: run `reason desktop install` on this Mac (and `reason connect --user-chrome on` if you turned it off).");if(t.call.kind==="browser"&&!m&&!s.features.browser)throw new r("automation_browser_not_installed",!s.platform.startsWith("linux")?"Browser use is unavailable on this machine: re-run `reason desktop install`.":"Browser use is unavailable on this machine: install a non-snap Chromium at /usr/bin/chromium, then re-run `reason desktop install`.");e.signal.throwIfAborted();let l=t.call.kind==="browser"&&t.call.operation!=="record_start"&&t.call.operation!=="record_stop",p=await Hi(e.runId,e.signal,o.now,l?"call":"run"),g="account"in o?o.account??null:K(),_;try{if(m){let h=await(o.userChromeEnvironment??Ht)(s,m,e.signal);e.signal.throwIfAborted(),_=await(o.runtime??Ae)(s.node,h,JSON.stringify(t.call),e.signal)}else if(g)_=await(o.delegate??Q)(g,t.call,e.signal);else _=await Oe(s,t.call,e.signal,o)}finally{p()}if(i)_=await ie({runId:e.runId,call:t.call,identity:u,output:_,signal:e.signal},c);return fe(_,e.runId,n)}
956
956
  export{Bt,Pn,Us,zs,qs,Ws,Rn};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{N}from"./vm-hands-entry-lite-48rphbjm.js";var Io=32;var Do="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",Oo=262144;var P=2,Br=33554432,Fr=200000,zn=4000000,ft=240000;var qn=2000;var jr=16384,Je=32768,Se=128,Wn=64,Xe=2097152,Yt=1,ne=16384,Ye=32768,Vn=8388608,Ee=1000,Zt=2500,Hr=2000,Qt=Zt+Hr,R=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/,h=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Ur={text_only:4430,invalid_json:4431,invalid_cancel_request:4432,invalid_sdk_response:4433,claim_required:4434,invalid_claim:4435,executor_mismatch:4436,stale_generation:4437,fence_conflict:4438,frame_too_large:4439,result_too_large:4440,progress_too_large:4441,terminal_cleanup_started:4442,job_journal_unavailable:4443},I=new Map(Object.entries(Ur).map(([t,n])=>[n,t]));var y=["cancelled","command_failed","duplicate_request_id","duplicate_result_evicted","invalid_repl_response","invalid_request","process_group_cleanup_unconfirmed","repl_failed","result_too_large","repl_response_too_large","repl_transport_failed","request_ledger_full","request_journal_unavailable","request_outcome_uncertain","maintenance_held","request_not_found","resume_digest_mismatch","spawn_failed","stale_generation","timeout"],k=new Set(y),Gn=16384,w=["maintenance_held","invalid_job_request","jobs_disabled","job_not_found","job_conflict","job_capacity","job_journal_unavailable","job_not_running","job_lease_expired","job_input_sequence","job_input_backpressure","stale_generation","pty_unsupported","job_mode_mismatch"];class r extends Error{code;constructor(t){super(t);this.name="HandsProtocolError",this.code=t}}function m(t){return new TextEncoder().encode(t).byteLength}function a(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function i(t,n){let e=new Set(n);return Object.keys(t).every((s)=>e.has(s))}function ae(t){return typeof t==="string"&&R.test(t)}function U(t){return Number.isSafeInteger(t)&&Number(t)>=1}function L(t){return typeof t==="string"&&h.test(t)}function ce(t){return typeof t==="string"&&t.startsWith("pty-")&&L(t.slice(4))}function p(t){return[t.cols,t.rows].every((n)=>Number.isSafeInteger(n)&&Number(n)>=1&&Number(n)<=Ee)}function _(t){if(typeof t!=="string"||t.length>Math.ceil(ne/3)*4||t.length%4!==0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return-1;let n=t.endsWith("==")?2:t.endsWith("=")?1:0;if(n&&"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(t[t.length-n-1])&(n===2?15:3))return-1;let s=t.length/4*3-n;return s<=ne?s:-1}function l(t){if(m(t)>Br)throw new r("frame_too_large");try{return JSON.parse(t)}catch{throw new r("invalid_json")}}function zr(t){let n=l(t);if(!a(n)||!i(n,["type","version","generation","id","jobId","action","input"])||n.type!=="job"||n.version!==P||!U(n.generation)||!ae(n.id)||!ae(n.jobId)||!a(n.input))throw new r("invalid_job_request");let e=n.input,s=Number.isSafeInteger(e.leaseExpiresAtMs)&&Number(e.leaseExpiresAtMs)>0,d=Number.isSafeInteger(e.sequence)&&Number(e.sequence)>=1;if(!(n.action==="start"?e.mode==="pty"?i(e,["mode","cols","rows","leaseExpiresAtMs"])&&ce(n.jobId)&&p(e)&&s:i(e,["script","leaseExpiresAtMs"])&&typeof e.script==="string"&&e.script.length<=Fr&&s:n.action==="inspect"?i(e,["after"])&&Number.isSafeInteger(e.after)&&Number(e.after)>=0:n.action==="input"?"dataBase64"in e?i(e,["sequence","dataBase64"])&&ce(n.jobId)&&d&&_(e.dataBase64)>0:i(e,["sequence","data","eof"])&&d&&typeof e.data==="string"&&e.data.length<=jr&&typeof e.eof==="boolean":n.action==="resize"?i(e,["sequence","cols","rows"])&&ce(n.jobId)&&d&&p(e):n.action==="renew"?i(e,["leaseExpiresAtMs"])&&s:n.action==="cancel"&&i(e,[])))throw new r("invalid_job_request");return n}function qr(t){let n=l(t);if(!a(n)||!i(n,["type","version","generation","id","ok","job","error"])||n.type!=="job_result"||n.version!==P||!U(n.generation)||!ae(n.id))throw new r("invalid_job_result");if(n.ok===!1&&n.job===void 0&&typeof n.error==="string"&&w.some((o)=>o===n.error))return n;let e=n.job;if(n.ok!==!0||n.error!==void 0||!a(e)||!i(e,["jobId","state","startedAtMs","finishedAtMs","leaseExpiresAtMs","exitCode","inputSequence","output","firstCursor","nextCursor","truncated","process","environmentRevision","environmentSnapshotId","pty"])||!ae(e.jobId)||!["starting","running","exited","cancelled","expired","uncertain"].includes(String(e.state))||!Number.isSafeInteger(e.startedAtMs)||Number(e.startedAtMs)<1||!Number.isSafeInteger(e.leaseExpiresAtMs)||Number(e.leaseExpiresAtMs)<1||e.finishedAtMs!==null&&(!Number.isSafeInteger(e.finishedAtMs)||Number(e.finishedAtMs)<Number(e.startedAtMs))||e.exitCode!==null&&(!Number.isSafeInteger(e.exitCode)||Number(e.exitCode)<0||Number(e.exitCode)>255)||!Number.isSafeInteger(e.inputSequence)||Number(e.inputSequence)<0||!Number.isSafeInteger(e.firstCursor)||Number(e.firstCursor)<1||!Number.isSafeInteger(e.nextCursor)||Number(e.nextCursor)<Number(e.firstCursor)-1||typeof e.truncated!=="boolean"||!Array.isArray(e.output)||e.output.length>Se)throw new r("invalid_job_result");if(e.environmentRevision===void 0!==(e.environmentSnapshotId===void 0)||e.environmentRevision!==void 0&&(!Number.isSafeInteger(e.environmentRevision)||Number(e.environmentRevision)<1||!L(e.environmentSnapshotId)))throw new r("invalid_job_result");let s=Number(e.firstCursor)-1,d=0;for(let o of e.output){if(!a(o)||!i(o,["cursor","stream","text"])||!Number.isSafeInteger(o.cursor)||Number(o.cursor)<=s||Number(o.cursor)>Number(e.nextCursor)||!["stdout","stderr"].includes(String(o.stream))||typeof o.text!=="string")throw new r("invalid_job_result");d+=o.text.length,s=Number(o.cursor)}if(d>Je)throw new r("invalid_job_result");let c=e.state==="starting"||e.state==="running";if(c&&(e.finishedAtMs!==null||e.exitCode!==null)||!c&&e.finishedAtMs===null||e.state==="uncertain"&&e.exitCode!==null||e.state==="exited"&&e.exitCode===null||e.state==="cancelled"&&e.exitCode!==130||e.state==="expired"&&e.exitCode!==124)throw new r("invalid_job_result");if(e.process!==void 0){let o=e.process;if(!a(o)||!i(o,["pid","processGroupId","executorLaunchId"])||!Number.isSafeInteger(o.pid)||Number(o.pid)<1||o.processGroupId!==o.pid||!L(o.executorLaunchId)||!["starting","running"].includes(String(e.state)))throw new r("invalid_job_result")}if(e.pty!==void 0){let o=e.pty;if(!a(o)||!i(o,["version","cols","rows","output","cleanup"])||o.version!==Yt||!ce(e.jobId)||!p(o)||e.output.length!==0||!Array.isArray(o.output)||o.output.length>Se||(c?o.cleanup!=="pending":e.state==="uncertain"?o.cleanup!=="unconfirmed":o.cleanup!=="confirmed")||e.state==="running"&&(e.process===void 0||e.environmentRevision===void 0))throw new r("invalid_job_result");let g=Number(e.firstCursor)-1,b=0;for(let u of o.output){if(!a(u)||!i(u,["cursor","dataBase64"])||!Number.isSafeInteger(u.cursor)||Number(u.cursor)<=g||Number(u.cursor)>Number(e.nextCursor))throw new r("invalid_job_result");let f=_(u.dataBase64);if(f<=0||(b+=f)>Ye)throw new r("invalid_job_result");g=Number(u.cursor)}}return n}function Kn(t){if(m(t)>Xe)throw new r("frame_too_large");let n=l(t);if(!a(n)||!i(n,["version","sessionId","operationId","runId","deviceId","rootId","workspace","binding","targetRevision","rootGrantRevision","generation","fenceId","executorLaunchId","job"])||n.version!==Yt||![n.sessionId,n.operationId,n.runId].every(ae)||![n.deviceId,n.rootId,n.fenceId,n.executorLaunchId].every(L)||!U(n.generation)||!Number.isSafeInteger(n.rootGrantRevision)||Number(n.rootGrantRevision)<1||!["workspace_source","mcp_control"].includes(String(n.binding))||!Number.isSafeInteger(n.targetRevision)||Number(n.targetRevision)<0||n.binding==="workspace_source"&&n.targetRevision!==0||!a(n.workspace))throw new r("invalid_pty_receipt");if(!N(n.workspace))throw new r("invalid_pty_receipt");let e=qr(JSON.stringify({type:"job_result",version:P,generation:n.generation,id:n.operationId,ok:!0,job:n.job}));if(!e.ok||!e.job.pty||e.job.pty.output.length!==0||e.job.process&&e.job.process.executorLaunchId!==n.executorLaunchId)throw new r("invalid_pty_receipt");return n}export{Io,Do,Oo,P,Br,Fr,zn,ft,qn,jr,Je,Se,Wn,Xe,Yt,ne,Ye,Vn,Ee,Zt,Hr,Qt,Ur,Gn,ae,U,L,ce,zr,qr,Kn};
2
+ import{N}from"./vm-hands-entry-lite-48rphbjm.js";var go=32;var _o="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",yo=262144;var P=2,Lr=33554432,$r=200000,Dn=4000000,pt=240000;var On=2000;var Mr=16384,Ve=32768,ve=128,Nn=64,Ge=2097152,Vt=1,ne=16384,Ke=32768,Ln=8388608,Se=1000,Gt=2500,Br=2000,Kt=Gt+Br,R=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/,h=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Fr={text_only:4430,invalid_json:4431,invalid_cancel_request:4432,invalid_sdk_response:4433,claim_required:4434,invalid_claim:4435,executor_mismatch:4436,stale_generation:4437,fence_conflict:4438,frame_too_large:4439,result_too_large:4440,progress_too_large:4441,terminal_cleanup_started:4442,job_journal_unavailable:4443},I=new Map(Object.entries(Fr).map(([t,n])=>[n,t]));var y=["cancelled","command_failed","duplicate_request_id","duplicate_result_evicted","invalid_repl_response","invalid_request","process_group_cleanup_unconfirmed","repl_failed","result_too_large","repl_response_too_large","repl_transport_failed","request_ledger_full","request_journal_unavailable","request_outcome_uncertain","maintenance_held","request_not_found","resume_digest_mismatch","spawn_failed","stale_generation","timeout"],k=new Set(y),$n=16384,w=["maintenance_held","invalid_job_request","jobs_disabled","job_not_found","job_conflict","job_capacity","job_journal_unavailable","job_not_running","job_lease_expired","job_input_sequence","job_input_backpressure","stale_generation","pty_unsupported","job_mode_mismatch"];class r extends Error{code;constructor(t){super(t);this.name="HandsProtocolError",this.code=t}}function m(t){return new TextEncoder().encode(t).byteLength}function a(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function i(t,n){let e=new Set(n);return Object.keys(t).every((s)=>e.has(s))}function ae(t){return typeof t==="string"&&R.test(t)}function H(t){return Number.isSafeInteger(t)&&Number(t)>=1}function L(t){return typeof t==="string"&&h.test(t)}function ce(t){return typeof t==="string"&&t.startsWith("pty-")&&L(t.slice(4))}function p(t){return[t.cols,t.rows].every((n)=>Number.isSafeInteger(n)&&Number(n)>=1&&Number(n)<=Se)}function _(t){if(typeof t!=="string"||t.length>Math.ceil(ne/3)*4||t.length%4!==0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return-1;let n=t.endsWith("==")?2:t.endsWith("=")?1:0;if(n&&"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(t[t.length-n-1])&(n===2?15:3))return-1;let s=t.length/4*3-n;return s<=ne?s:-1}function l(t){if(m(t)>Lr)throw new r("frame_too_large");try{return JSON.parse(t)}catch{throw new r("invalid_json")}}function jr(t){let n=l(t);if(!a(n)||!i(n,["type","version","generation","id","jobId","action","input"])||n.type!=="job"||n.version!==P||!H(n.generation)||!ae(n.id)||!ae(n.jobId)||!a(n.input))throw new r("invalid_job_request");let e=n.input,s=Number.isSafeInteger(e.leaseExpiresAtMs)&&Number(e.leaseExpiresAtMs)>0,d=Number.isSafeInteger(e.sequence)&&Number(e.sequence)>=1;if(!(n.action==="start"?e.mode==="pty"?i(e,["mode","cols","rows","leaseExpiresAtMs"])&&ce(n.jobId)&&p(e)&&s:i(e,["script","leaseExpiresAtMs"])&&typeof e.script==="string"&&e.script.length<=$r&&s:n.action==="inspect"?i(e,["after"])&&Number.isSafeInteger(e.after)&&Number(e.after)>=0:n.action==="input"?"dataBase64"in e?i(e,["sequence","dataBase64"])&&ce(n.jobId)&&d&&_(e.dataBase64)>0:i(e,["sequence","data","eof"])&&d&&typeof e.data==="string"&&e.data.length<=Mr&&typeof e.eof==="boolean":n.action==="resize"?i(e,["sequence","cols","rows"])&&ce(n.jobId)&&d&&p(e):n.action==="renew"?i(e,["leaseExpiresAtMs"])&&s:n.action==="cancel"&&i(e,[])))throw new r("invalid_job_request");return n}function Hr(t){let n=l(t);if(!a(n)||!i(n,["type","version","generation","id","ok","job","error"])||n.type!=="job_result"||n.version!==P||!H(n.generation)||!ae(n.id))throw new r("invalid_job_result");if(n.ok===!1&&n.job===void 0&&typeof n.error==="string"&&w.some((o)=>o===n.error))return n;let e=n.job;if(n.ok!==!0||n.error!==void 0||!a(e)||!i(e,["jobId","state","startedAtMs","finishedAtMs","leaseExpiresAtMs","exitCode","inputSequence","output","firstCursor","nextCursor","truncated","process","environmentRevision","environmentSnapshotId","pty"])||!ae(e.jobId)||!["starting","running","exited","cancelled","expired","uncertain"].includes(String(e.state))||!Number.isSafeInteger(e.startedAtMs)||Number(e.startedAtMs)<1||!Number.isSafeInteger(e.leaseExpiresAtMs)||Number(e.leaseExpiresAtMs)<1||e.finishedAtMs!==null&&(!Number.isSafeInteger(e.finishedAtMs)||Number(e.finishedAtMs)<Number(e.startedAtMs))||e.exitCode!==null&&(!Number.isSafeInteger(e.exitCode)||Number(e.exitCode)<0||Number(e.exitCode)>255)||!Number.isSafeInteger(e.inputSequence)||Number(e.inputSequence)<0||!Number.isSafeInteger(e.firstCursor)||Number(e.firstCursor)<1||!Number.isSafeInteger(e.nextCursor)||Number(e.nextCursor)<Number(e.firstCursor)-1||typeof e.truncated!=="boolean"||!Array.isArray(e.output)||e.output.length>ve)throw new r("invalid_job_result");if(e.environmentRevision===void 0!==(e.environmentSnapshotId===void 0)||e.environmentRevision!==void 0&&(!Number.isSafeInteger(e.environmentRevision)||Number(e.environmentRevision)<1||!L(e.environmentSnapshotId)))throw new r("invalid_job_result");let s=Number(e.firstCursor)-1,d=0;for(let o of e.output){if(!a(o)||!i(o,["cursor","stream","text"])||!Number.isSafeInteger(o.cursor)||Number(o.cursor)<=s||Number(o.cursor)>Number(e.nextCursor)||!["stdout","stderr"].includes(String(o.stream))||typeof o.text!=="string")throw new r("invalid_job_result");d+=o.text.length,s=Number(o.cursor)}if(d>Ve)throw new r("invalid_job_result");let c=e.state==="starting"||e.state==="running";if(c&&(e.finishedAtMs!==null||e.exitCode!==null)||!c&&e.finishedAtMs===null||e.state==="uncertain"&&e.exitCode!==null||e.state==="exited"&&e.exitCode===null||e.state==="cancelled"&&e.exitCode!==130||e.state==="expired"&&e.exitCode!==124)throw new r("invalid_job_result");if(e.process!==void 0){let o=e.process;if(!a(o)||!i(o,["pid","processGroupId","executorLaunchId"])||!Number.isSafeInteger(o.pid)||Number(o.pid)<1||o.processGroupId!==o.pid||!L(o.executorLaunchId)||!["starting","running"].includes(String(e.state)))throw new r("invalid_job_result")}if(e.pty!==void 0){let o=e.pty;if(!a(o)||!i(o,["version","cols","rows","output","cleanup"])||o.version!==Vt||!ce(e.jobId)||!p(o)||e.output.length!==0||!Array.isArray(o.output)||o.output.length>ve||(c?o.cleanup!=="pending":e.state==="uncertain"?o.cleanup!=="unconfirmed":o.cleanup!=="confirmed")||e.state==="running"&&(e.process===void 0||e.environmentRevision===void 0))throw new r("invalid_job_result");let g=Number(e.firstCursor)-1,b=0;for(let u of o.output){if(!a(u)||!i(u,["cursor","dataBase64"])||!Number.isSafeInteger(u.cursor)||Number(u.cursor)<=g||Number(u.cursor)>Number(e.nextCursor))throw new r("invalid_job_result");let f=_(u.dataBase64);if(f<=0||(b+=f)>Ke)throw new r("invalid_job_result");g=Number(u.cursor)}}return n}function Mn(t){if(m(t)>Ge)throw new r("frame_too_large");let n=l(t);if(!a(n)||!i(n,["version","sessionId","operationId","runId","deviceId","rootId","workspace","binding","targetRevision","rootGrantRevision","generation","fenceId","executorLaunchId","job"])||n.version!==Vt||![n.sessionId,n.operationId,n.runId].every(ae)||![n.deviceId,n.rootId,n.fenceId,n.executorLaunchId].every(L)||!H(n.generation)||!Number.isSafeInteger(n.rootGrantRevision)||Number(n.rootGrantRevision)<1||!["workspace_source","mcp_control"].includes(String(n.binding))||!Number.isSafeInteger(n.targetRevision)||Number(n.targetRevision)<0||n.binding==="workspace_source"&&n.targetRevision!==0||!a(n.workspace))throw new r("invalid_pty_receipt");if(!N(n.workspace))throw new r("invalid_pty_receipt");let e=Hr(JSON.stringify({type:"job_result",version:P,generation:n.generation,id:n.operationId,ok:!0,job:n.job}));if(!e.ok||!e.job.pty||e.job.pty.output.length!==0||e.job.process&&e.job.process.executorLaunchId!==n.executorLaunchId)throw new r("invalid_pty_receipt");return n}export{go,_o,yo,P,Lr,$r,Dn,pt,On,Mr,Ve,ve,Nn,Ge,Vt,ne,Ke,Ln,Se,Gt,Br,Kt,Fr,$n,ae,H,L,ce,jr,Hr,Mn};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- var tr={name:"github-native-engineer-device-worker-production",version:"0.2.553",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@agentclientprotocol/sdk":"1.9.0","@anthropic-ai/sandbox-runtime":"^0.0.80","@earendil-works/pi-tui":"1.0.0","@reason/runtime-distribution":"workspace:*",diff:"8.0.4","open-browser-use-sdk":"0.1.42","playwright-core":"1.60.0",toml:"5.0.1",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.4",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^5.0.1",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
2
+ var tr={name:"github-native-engineer-device-worker-production",version:"0.2.554",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@agentclientprotocol/sdk":"1.9.0","@anthropic-ai/sandbox-runtime":"^0.0.80","@earendil-works/pi-tui":"1.0.0","@reason/runtime-distribution":"workspace:*",diff:"8.0.4","open-browser-use-sdk":"0.1.42","playwright-core":"1.60.0",toml:"5.0.1",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.4",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^5.0.1",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
3
3
  export{tr};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{_e,ye,we}from"./vm-hands-entry-lite-2hfrcr50.js";import{Oe,Ne,Le}from"./vm-hands-entry-lite-b6gsggvp.js";import{spawn as A}from"child_process";import{randomUUID as s}from"crypto";import{basename as C}from"path";import{fileURLToPath as E}from"url";function S(){let p=C(process.execPath).startsWith("bun");return{command:process.execPath,args:[...p?["--no-env-file",E(new URL("./worker-candidate-entry.ts",import.meta.url))]:[],"worker","__preview-probe"]}}async function Cs(p,a,m=S()){if(a.aborted||!["darwin","linux","win32"].includes(process.platform)||process.platform==="win32"&&!ye())return!1;let n=new AbortController,o=()=>n.abort();a.addEventListener("abort",o,{once:!0});let y=setTimeout(o,5000),t=A(m.command,m.args,{cwd:p,...Ne(),stdio:["pipe","pipe","ignore"],env:Oe()});Le(t);let l=!1,b=new Promise((e)=>t.once("close",()=>{l=!0,e()}));t.on("error",o);let f,w,k=new Promise((e)=>{f=e}),I=new Promise((e)=>{w=e}),v=new Promise((e)=>n.signal.addEventListener("abort",()=>e(null),{once:!0})),i="",g=0,P=!1;t.stdout.setEncoding("utf8"),t.stdout.on("data",(e)=>{if(g+=Buffer.byteLength(e),i+=e,g>512){o();return}while(i.includes(`
2
+ import{_e,ye,we}from"./vm-hands-entry-lite-bpamn7ny.js";import{Oe,Ne,Le}from"./vm-hands-entry-lite-tyem93c1.js";import{spawn as A}from"child_process";import{randomUUID as s}from"crypto";import{basename as C}from"path";import{fileURLToPath as E}from"url";function S(){let p=C(process.execPath).startsWith("bun");return{command:process.execPath,args:[...p?["--no-env-file",E(new URL("./worker-candidate-entry.ts",import.meta.url))]:[],"worker","__preview-probe"]}}async function Cs(p,a,m=S()){if(a.aborted||!["darwin","linux","win32"].includes(process.platform)||process.platform==="win32"&&!ye())return!1;let n=new AbortController,o=()=>n.abort();a.addEventListener("abort",o,{once:!0});let y=setTimeout(o,5000),t=A(m.command,m.args,{cwd:p,...Ne(),stdio:["pipe","pipe","ignore"],env:Oe()});Le(t);let l=!1,b=new Promise((e)=>t.once("close",()=>{l=!0,e()}));t.on("error",o);let f,w,k=new Promise((e)=>{f=e}),I=new Promise((e)=>{w=e}),v=new Promise((e)=>n.signal.addEventListener("abort",()=>e(null),{once:!0})),i="",g=0,P=!1;t.stdout.setEncoding("utf8"),t.stdout.on("data",(e)=>{if(g+=Buffer.byteLength(e),i+=e,g>512){o();return}while(i.includes(`
3
3
  `)){let c=i.indexOf(`
4
4
  `),d=i.slice(0,c);i=i.slice(c+1);try{if(!P){let r=JSON.parse(d);if(!r||Object.keys(r).length!==2||!Number.isInteger(r.port)||r.port<1024||r.port>65535||typeof r.token!=="string"||!/^[a-zA-Z0-9_-]{43}$/.test(r.token))throw Error("probe_receipt_invalid");P=!0,f({port:r.port,token:r.token})}else if(d==="ready")w(!0);else o()}catch{o()}}}),b.then(o);let h,u=!1;try{let e=await Promise.race([k,v]);if(!e||!t.pid||n.signal.aborted||a.aborted)return!1;let c=Date.now()+4500,d=s(),r={organizationId:s(),userId:s(),runId:s(),deviceId:s(),rootId:s(),attachmentRevision:0,grantRevision:1,jobId:"readiness",generation:1,fenceId:s(),port:e.port,expiresAtMs:c},L={binding:r,executorLaunchId:d,job:{jobId:r.jobId,state:"running",startedAtMs:Date.now(),finishedAtMs:null,leaseExpiresAtMs:c,exitCode:null,inputSequence:0,output:[],firstCursor:1,nextCursor:0,truncated:!1,process:{pid:t.pid,processGroupId:t.pid,executorLaunchId:d}}},x=we({binding:r,deniedPorts:new Set,readCurrentJob:async()=>!l&&!n.signal.aborted?L:null});h=await _e({binding:r,deviceRelayUrl:`ws://127.0.0.1:${e.port}/device/readiness/${e.token}`,port:x,signal:n.signal}),u=await Promise.race([I,v])===!0&&!n.signal.aborted&&!a.aborted}catch{u=!1}finally{if(clearTimeout(y),a.removeEventListener("abort",o),h?.close(),n.abort(),t.stdin.destroy(),!l)t.kill("SIGKILL");await b}return u&&l}
5
5
  export{Cs};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-b6gsggvp.js";import{execFileSync as h}from"child_process";import{mkdirSync as k,readdirSync as D,readFileSync as w,rmSync as g,statSync as x,writeFileSync as L}from"fs";import{join as p,sep as y}from"path";import{setTimeout as _}from"timers/promises";var P=3000,u=null;function S(e){return p(e,"users")}function Pt(e){if(u?.root===e.root)return;let o=S(e.root);k(o,{recursive:!0,mode:448}),L(p(o,String(process.pid)),"",{mode:384}),u=e}function Sa(){if(!u)return;g(p(S(u.root),String(process.pid)),{force:!0}),u=null}function m(e){try{return process.kill(e,0),!0}catch(o){return o instanceof Error&&"code"in o&&o.code==="EPERM"}}function E(){let e=process.getuid?.();if(process.platform==="linux")return D("/proc").flatMap((n)=>{if(!/^\d+$/.test(n))return[];try{if(x(`/proc/${n}`).uid!==e)return[];let s=w(`/proc/${n}/cmdline`).toString("utf8").split("\x00").join(" ").trim();return s?[{pid:Number(n),command:s}]:[]}catch{return[]}});if(process.platform==="win32")return h(C("powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.CommandLine)" }'],{encoding:"utf8",maxBuffer:16777216,windowsHide:!0}).split(/\r?\n/).flatMap((s)=>{let l=/^(\d+) (.+)$/.exec(s.trim());return l?[{pid:Number(l[1]),command:l[2]}]:[]});return h("/bin/ps",["-axww","-o","pid=,uid=,command="],{encoding:"utf8",maxBuffer:16777216}).split(`
2
+ import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-tyem93c1.js";import{execFileSync as h}from"child_process";import{mkdirSync as k,readdirSync as D,readFileSync as w,rmSync as g,statSync as x,writeFileSync as L}from"fs";import{join as p,sep as y}from"path";import{setTimeout as _}from"timers/promises";var P=3000,u=null;function S(e){return p(e,"users")}function Pt(e){if(u?.root===e.root)return;let o=S(e.root);k(o,{recursive:!0,mode:448}),L(p(o,String(process.pid)),"",{mode:384}),u=e}function Sa(){if(!u)return;g(p(S(u.root),String(process.pid)),{force:!0}),u=null}function m(e){try{return process.kill(e,0),!0}catch(o){return o instanceof Error&&"code"in o&&o.code==="EPERM"}}function E(){let e=process.getuid?.();if(process.platform==="linux")return D("/proc").flatMap((n)=>{if(!/^\d+$/.test(n))return[];try{if(x(`/proc/${n}`).uid!==e)return[];let s=w(`/proc/${n}/cmdline`).toString("utf8").split("\x00").join(" ").trim();return s?[{pid:Number(n),command:s}]:[]}catch{return[]}});if(process.platform==="win32")return h(C("powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.CommandLine)" }'],{encoding:"utf8",maxBuffer:16777216,windowsHide:!0}).split(/\r?\n/).flatMap((s)=>{let l=/^(\d+) (.+)$/.exec(s.trim());return l?[{pid:Number(l[1]),command:l[2]}]:[]});return h("/bin/ps",["-axww","-o","pid=,uid=,command="],{encoding:"utf8",maxBuffer:16777216}).split(`
3
3
  `).flatMap((n)=>{let s=/^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(n);return s&&Number(s[2])===e?[{pid:Number(s[1]),command:s[3]}]:[]})}async function Ea(){let e=u;if(!e)return{released:"unused",stopped:0};let o=S(e.root);g(p(o,String(process.pid)),{force:!0}),u=null;let n=!1;for(let t of D(o)){let c=Number(t);if(Number.isSafeInteger(c)&&c>0&&m(c))n=!0;else g(p(o,t),{force:!0})}if(n)return{released:"shared",stopped:0};let s=E().filter((t)=>t.pid!==process.pid&&(t.command.includes(`${e.root}${y}`)||t.command.includes(`${e.automation}${y}`)||t.command.includes(e.extensionDir))),l=(t,c)=>{try{process.kill(t,c)}catch{}};for(let t of s)l(t.pid,"SIGTERM");for(let t=Date.now()+P;Date.now()<t&&s.some((c)=>m(c.pid));)await new Promise((c)=>setTimeout(c,100));for(let t of s)if(m(t.pid))l(t.pid,"SIGKILL");return{released:"stopped",stopped:s.length}}var M=20000,N=30000,O=100,a=new Map,i=null,b=0,f=[];function ji(e){a.set(e,(a.get(e)??0)+1);let o=!1;return()=>{if(o)return;o=!0;let n=(a.get(e)??1)-1;if(n>0){a.set(e,n);return}if(a.delete(e),i?.run===e)i.idleUntil=0}}function T(){return new r("automation_desktop_busy","Another Session, or another agent of this Session, is using this worker's desktop. Retry after it finishes.")}function U(e,o){return i!==null&&i.run!==e&&(i.calls>0||o<i.idleUntil)}async function Hi(e,o,n=Date.now,s="run"){let l=Symbol(e);f.push(l);try{let d=n()+N;for(;;){if(b===0&&!U(e,n())&&(i?.run===e||f[0]===l))break;if(n()>=d)throw T();await _(O,void 0,{signal:o}).catch(()=>o.throwIfAborted())}}finally{f.splice(f.indexOf(l),1)}if(s==="call"&&!(i?.run===e&&(i.calls>0||n()<i.idleUntil))){b+=1;let d=!1;return()=>{if(d)return;d=!0,b-=1}}if(i?.run!==e)i={run:e,calls:0,idleUntil:0};let t=i;t.calls+=1;let c=!1;return()=>{if(c)return;c=!0,t.calls-=1,t.idleUntil=n()+M}}
4
4
  export{Pt,Sa,Ea,ji,Hi};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{tr}from"./vm-hands-entry-lite-pg2czhxb.js";var Qe=tr.version,Qn=`reason-cli/${Qe}`;export{Qe,Qn};