@reason-machines/cli-linux-arm64 0.2.349 → 0.2.352

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 (81) hide show
  1. package/bin/ara +1 -1
  2. package/bin/vm-hands/api-0wscteg6.js +2 -0
  3. package/bin/vm-hands/api-credentials-6qs21t88.js +2 -0
  4. package/bin/vm-hands/{ask-relay-qr4gmz44.js → ask-relay-0j7e2qfb.js} +2 -2
  5. package/bin/vm-hands/connect-cli-vqcvzj5n.js +2 -0
  6. package/bin/vm-hands/{custom-endpoint-device-syw4d5k4.js → custom-endpoint-device-j3e3zjd5.js} +1 -1
  7. package/bin/vm-hands/desktop-account-gcysz0m3.js +2 -0
  8. package/bin/vm-hands/{device-workspace-s49yhsk7.js → device-workspace-7yg5x68n.js} +1 -1
  9. package/bin/vm-hands/hands-worker-source-hbp5n31r.js +2 -0
  10. package/bin/vm-hands/{index-t1h1wd8g.js → index-swa20ch8.js} +1 -1
  11. package/bin/vm-hands/local-automation-snr7w7rm.js +2 -0
  12. package/bin/vm-hands/local-capabilities-ggbsk169.js +2 -0
  13. package/bin/vm-hands/local-desktop-users-pccz3sz9.js +2 -0
  14. package/bin/vm-hands/local-display-mac-gj72gkfb.js +2 -0
  15. package/bin/vm-hands/local-display-session-fcptmmhc.js +2 -0
  16. package/bin/vm-hands/local-pty-session-zen80k1k.js +2 -0
  17. package/bin/vm-hands/{network-contract-8d4bpy3e.js → network-contract-rm9x646s.js} +1 -1
  18. package/bin/vm-hands/package-1e3w44ve.js +2 -0
  19. package/bin/vm-hands/permissions-fwvgtbvr.js +2 -0
  20. package/bin/vm-hands/{reason-hands-protocol-k12eme4q.js → reason-hands-protocol-3z7bas06.js} +1 -1
  21. package/bin/vm-hands/{status-xs5bh7hf.js → status-a1xhjh72.js} +2 -2
  22. package/bin/vm-hands/version-3k9sc1xe.js +2 -0
  23. package/bin/vm-hands/vm-hands-entry-lite-0d93secz.js +540 -0
  24. package/bin/vm-hands/vm-hands-entry-lite-1ey4kprv.js +5 -0
  25. package/bin/vm-hands/{vm-hands-entry-lite-svs618mf.js → vm-hands-entry-lite-22q8r2qr.js} +2 -2
  26. package/bin/vm-hands/{vm-hands-entry-lite-kt418g2w.js → vm-hands-entry-lite-33ttamma.js} +2 -2
  27. package/bin/vm-hands/{vm-hands-entry-lite-9dx3at21.js → vm-hands-entry-lite-5b29hq7h.js} +2 -2
  28. package/bin/vm-hands/{vm-hands-entry-lite-0jar357h.js → vm-hands-entry-lite-6f5eypjm.js} +2 -2
  29. package/bin/vm-hands/{vm-hands-entry-lite-1xjtcxpn.js → vm-hands-entry-lite-6qfax5p2.js} +1 -1
  30. package/bin/vm-hands/{vm-hands-entry-lite-289bc9v7.js → vm-hands-entry-lite-84d59wrf.js} +1 -1
  31. package/bin/vm-hands/{vm-hands-entry-lite-z0wwfy97.js → vm-hands-entry-lite-8hez8yg7.js} +2 -2
  32. package/bin/vm-hands/{vm-hands-entry-lite-7qg63rj8.js → vm-hands-entry-lite-9khka7wc.js} +2 -2
  33. package/bin/vm-hands/{vm-hands-entry-lite-0wyjnvjz.js → vm-hands-entry-lite-beannz0s.js} +2 -2
  34. package/bin/vm-hands/{vm-hands-entry-lite-yeahy7rk.js → vm-hands-entry-lite-c9wp99nr.js} +2 -2
  35. package/bin/vm-hands/{vm-hands-entry-lite-1jhry648.js → vm-hands-entry-lite-dys7am1h.js} +1 -1
  36. package/bin/vm-hands/{vm-hands-entry-lite-7ba3nhgv.js → vm-hands-entry-lite-dyy62gt3.js} +2 -2
  37. package/bin/vm-hands/{vm-hands-entry-lite-tfpebnar.js → vm-hands-entry-lite-fs3ahdgg.js} +1 -1
  38. package/bin/vm-hands/{vm-hands-entry-lite-8ynztq9j.js → vm-hands-entry-lite-gcn3rmz6.js} +1 -1
  39. package/bin/vm-hands/{vm-hands-entry-lite-449p9dx7.js → vm-hands-entry-lite-gkd1gkfc.js} +3 -3
  40. package/bin/vm-hands/{vm-hands-entry-lite-m16qf0yy.js → vm-hands-entry-lite-hwjtyptw.js} +1 -1
  41. package/bin/vm-hands/{vm-hands-entry-lite-f66d7y5a.js → vm-hands-entry-lite-hz0ywb12.js} +3 -3
  42. package/bin/vm-hands/{vm-hands-entry-lite-x6jqyxkx.js → vm-hands-entry-lite-jfwz0br7.js} +2 -2
  43. package/bin/vm-hands/{vm-hands-entry-lite-2xh7sjs0.js → vm-hands-entry-lite-k17ntg9v.js} +2 -2
  44. package/bin/vm-hands/{vm-hands-entry-lite-knfh7w3j.js → vm-hands-entry-lite-mybm2kyz.js} +2 -2
  45. package/bin/vm-hands/{vm-hands-entry-lite-k2cvr710.js → vm-hands-entry-lite-nbtpm59m.js} +71 -168
  46. package/bin/vm-hands/{vm-hands-entry-lite-mhsv58hw.js → vm-hands-entry-lite-nd1k2jz9.js} +1 -1
  47. package/bin/vm-hands/{vm-hands-entry-lite-k469tezz.js → vm-hands-entry-lite-nvhzj5b0.js} +1 -1
  48. package/bin/vm-hands/{vm-hands-entry-lite-wgjqxtxj.js → vm-hands-entry-lite-pztap0be.js} +2 -2
  49. package/bin/vm-hands/{vm-hands-entry-lite-h1642n10.js → vm-hands-entry-lite-q2z2f9n4.js} +2 -2
  50. package/bin/vm-hands/{vm-hands-entry-lite-q756n4nh.js → vm-hands-entry-lite-qbg33vxp.js} +1 -1
  51. package/bin/vm-hands/{vm-hands-entry-lite-36xzwsxn.js → vm-hands-entry-lite-qf01e5f1.js} +2 -2
  52. package/bin/vm-hands/{vm-hands-entry-lite-k2e3q5qj.js → vm-hands-entry-lite-tdgbgcer.js} +1 -1
  53. package/bin/vm-hands/{vm-hands-entry-lite-gt5pkv4h.js → vm-hands-entry-lite-tj1y61bg.js} +1 -1
  54. package/bin/vm-hands/{vm-hands-entry-lite-wmxksawm.js → vm-hands-entry-lite-wpx6sg6d.js} +2 -2
  55. package/bin/vm-hands/{vm-hands-entry-lite-pa111vpq.js → vm-hands-entry-lite-xhjbc3e4.js} +2 -2
  56. package/bin/vm-hands/vm-hands-entry-lite-zrvaqawr.js +5 -0
  57. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  58. package/bin/vm-hands/{vm-hands-executor-6q1n7hpe.js → vm-hands-executor-8m5p7snz.js} +1 -1
  59. package/bin/vm-hands/vm-hands-op-runner-48q5h3dw.js +2 -0
  60. package/bin/vm-hands/{vm-hands-runtime-k21dbztp.js → vm-hands-runtime-ncemfwsx.js} +3 -3
  61. package/bin/vm-hands/worker-sandbox-yw24sxyp.js +2 -0
  62. package/package.json +1 -1
  63. package/bin/vm-hands/api-credentials-d34gw13p.js +0 -2
  64. package/bin/vm-hands/api-t5zxz49k.js +0 -2
  65. package/bin/vm-hands/connect-cli-rknch17k.js +0 -2
  66. package/bin/vm-hands/desktop-account-pm3zxjjt.js +0 -2
  67. package/bin/vm-hands/hands-worker-source-0ca76sbd.js +0 -2
  68. package/bin/vm-hands/local-automation-3nabm5h3.js +0 -2
  69. package/bin/vm-hands/local-capabilities-mnz5et6y.js +0 -2
  70. package/bin/vm-hands/local-desktop-users-zxw8xxw9.js +0 -2
  71. package/bin/vm-hands/local-display-mac-jdgx19jw.js +0 -2
  72. package/bin/vm-hands/local-display-session-k2ewepn4.js +0 -2
  73. package/bin/vm-hands/local-pty-session-frp7k8fz.js +0 -2
  74. package/bin/vm-hands/package-vj1s3sye.js +0 -2
  75. package/bin/vm-hands/permissions-74dw20hk.js +0 -2
  76. package/bin/vm-hands/version-mhc6y1v9.js +0 -2
  77. package/bin/vm-hands/vm-hands-entry-lite-1wy28sjt.js +0 -5
  78. package/bin/vm-hands/vm-hands-entry-lite-pnkfgnqz.js +0 -5
  79. package/bin/vm-hands/vm-hands-entry-lite-qwb91tgj.js +0 -529
  80. package/bin/vm-hands/vm-hands-op-runner-01szqn0m.js +0 -2
  81. package/bin/vm-hands/worker-sandbox-1kpm6af4.js +0 -2
@@ -0,0 +1,5 @@
1
+ // @bun
2
+ import{M as f}from"./vm-hands-entry-lite-fs3ahdgg.js";import{Fh as T,sh as v,vh as K,yh as U,zh as y}from"./vm-hands-entry-lite-6qfax5p2.js";import{ii as $}from"./vm-hands-entry-lite-k17ntg9v.js";var u=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function _(x){let w=typeof x==="string"?u.exec(x):null;return w?{major:Number(w[1]),minor:Number(w[2])}:null}import{createHash as n,randomBytes as j}from"crypto";import{createInterface as o}from"readline";import{randomBytes as d}from"crypto";import{chmodSync as q,existsSync as C,lstatSync as l,mkdirSync as a,readFileSync as b,renameSync as p,unlinkSync as O,writeFileSync as L}from"fs";import{homedir as t}from"os";import{dirname as i,join as F}from"path";function B(x=process.env,w=t()){let H=x.XDG_CONFIG_HOME?.trim()||F(w,".config"),J=K({env:x})==="staging"?["staging"]:[];return F(T(H,...J),"credentials.json")}function A(x,w=B()){return a(i(w),{recursive:!0,mode:448}),L(w,`${JSON.stringify(x,null,2)}
3
+ `,{mode:384}),q(w,384),w}function M(x=B()){if(!C(x))return null;try{let w=b(x,"utf8"),H=JSON.parse(w);if(typeof H.apiOrigin!=="string"||typeof H.clientId!=="string"||typeof H.accessToken!=="string"||typeof H.refreshToken!=="string"||typeof H.expiresAt!=="string"||typeof H.orgId!=="string"||!Array.isArray(H.scopes))return null;let G=new URL(H.apiOrigin).origin,J=U(G);if(J!==G)s(x,w,J);return{apiOrigin:J,clientId:H.clientId,accessToken:H.accessToken,refreshToken:H.refreshToken,expiresAt:H.expiresAt,scopes:H.scopes.filter((Q)=>typeof Q==="string"),orgId:H.orgId}}catch{return null}}function s(x,w,H){let G=`${x}.${process.pid}.${d(6).toString("hex")}.tmp`;try{let J=l(x);if(!J.isFile()||J.uid!==process.geteuid?.())return;let Q=JSON.parse(w);if(L(G,`${JSON.stringify({...Q,apiOrigin:H},null,2)}
4
+ `,{mode:384,flag:"wx"}),q(G,384),b(x,"utf8")!==w)throw Error("credentials_changed");p(G,x)}catch{try{O(G)}catch{}}}function R(x=B()){if(!C(x))return!1;return O(x),!0}var S=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var s0=S.filter((x)=>x!=="network:read"&&x!=="network:write");class D extends Error{oauthCode;constructor(x,w=null){super(x);this.oauthCode=w;this.name="LoginError"}}function n0(){let x=j(48).toString("base64url"),w=n("sha256").update(x).digest("base64url");return{verifier:x,challenge:w,state:j(32).toString("base64url")}}function r(x,w){let H=typeof x.error==="string"?x.error:null,G=typeof x.error_description==="string"?x.error_description:H?H:w;return new D(G,H)}async function e(x,w,H,G){let J=await H(`${x}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:w,signal:G}),Q=await J.json().catch(()=>({}));if(!J.ok)throw r(Q,`OAuth token request failed (${J.status})`);return Q}var x0=1e4;async function w0(x,w={}){let H=w.fetchImpl??fetch,G=await e(x.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:x.clientId,refresh_token:x.refreshToken}),H,AbortSignal.timeout(x0)).catch((Q)=>{if(Q instanceof Error&&Q.name==="TimeoutError")throw new D("Reason did not answer the login refresh in time. Check the network and retry.");throw Q});if(typeof G.access_token!=="string"||typeof G.refresh_token!=="string"||typeof G.expires_in!=="number")throw new D("Reason returned an incomplete refreshed login.");let J={...x,accessToken:G.access_token,refreshToken:G.refresh_token,expiresAt:new Date(Date.now()+G.expires_in*1000).toISOString(),scopes:typeof G.scope==="string"?G.scope.split(/\s+/).filter(Boolean):x.scopes};return A(J,w.path??B()),J}var z=new Map;function k(x,w){if(!w)return x;if(w.aborted)return Promise.reject(w.reason);return new Promise((H,G)=>{let J=()=>G(w.reason);w.addEventListener("abort",J,{once:!0}),x.then(H,G).finally(()=>w.removeEventListener("abort",J))})}async function P(x={}){let w=x.path??B(),H=M(w);if(!H)return null;let G=x.apiOrigin??v(process.env,"REASON_API_URL")?.trim();if(G&&!y(H.apiOrigin,new URL(G).origin))return null;let J=Date.parse(H.expiresAt)<=Date.now()+60000;if(!x.forceRefresh&&!J)return H;let Q=[w,H.apiOrigin,H.clientId,H.refreshToken].join("\x00"),V=z.get(Q);if(V)return k(V,x.signal);let Z;return Z=w0(H,{fetchImpl:x.fetchImpl,path:w}).catch(async(Y)=>{if(!(Y instanceof D)||Y.oauthCode!=="invalid_grant"&&Y.oauthCode!=="invalid_client")throw Y;let N=M(w),c=Y.oauthCode==="invalid_client"?N?.clientId!==H.clientId:N?.refreshToken!==H.refreshToken;if(N&&c)return P({fetchImpl:x.fetchImpl,path:w});return R(w),null}).finally(()=>{if(z.get(Q)===Z)z.delete(Q)}),z.set(Q,Z),k(Z,x.signal)}function o0(x,w){return new Promise((H)=>{let G=o({input:x}),J=!1,Q=(Z)=>{if(J)return;J=!0,w.removeEventListener("abort",V),G.close(),x.pause(),H(Z)},V=()=>Q(null);w.addEventListener("abort",V,{once:!0}),G.once("line",(Z)=>Q(Z)),G.once("close",()=>Q(null))})}var $0=$.object({label:$.string(),used_percent:$.number().min(0).max(100).nullable(),resets_at:$.string().nullable(),exhausted:$.boolean().nullable()}),H0=$.object({groups:$.array($.object({selectable:$.boolean().optional(),accounts:$.array($.object({source_id:$.string().min(1),model_ids:$.array($.string().min(1)).optional()}))}))});function G0(x){let w=H0.safeParse(x);if(!w.success)return;return w.data.groups.some((H)=>H.selectable!==!1&&H.accounts.some((G)=>G.model_ids===void 0||G.model_ids.length>0))}class X extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor(x,w,H,G,J,Q){super(H);this.status=x;this.code=w;this.suggestedModel=G;this.retryAfterMs=J;this.resolutionReason=Q;this.name="ApiError"}static rateLimitDelayMs(x,w){if(!(x instanceof X)||x.status!==429)return null;return Math.min(60000,Math.max(w,x.retryAfterMs??0))}}var J0=["minimal","low","medium","high","xhigh","max"],Q0=$.object({id:$.string().min(1),kind:$.string(),name:$.string(),custom_name:$.string().nullish(),status:$.string(),online:$.boolean(),compatible:$.boolean().optional(),compatibility_reason:$.string().nullish(),folder_lane_of:$.string().nullish(),roots:$.array($.object({id:$.string().min(1),label:$.string()}))}),W0=$.object({devices:$.array(Q0),end_cursor:$.string().nullish(),has_next_page:$.boolean().optional()}),Z0=$.object({id:$.string().min(1),name:$.string()}),V0=$.object({items:$.array(Z0)}),X0=$.object({id:$.string().min(1),name:$.string(),main:$.boolean(),mine:$.boolean(),session_id:$.string().nullish(),appearance:$.object({color:$.string().nullish()}).nullish().catch(null)}),Y0=$.object({items:$.array(X0)}),B0=$.object({skill_id:$.string().min(1),name:$.string(),description:$.string().nullish(),activation_keywords:$.array($.string()).default([]),is_enabled:$.boolean().default(!0)}),D0=$.object({items:$.array(B0).default([])}),z0=$.object({id:$.string().min(1),kind:$.string(),enabled:$.boolean(),schedule:$.object({expression:$.string().nullish(),every_seconds:$.number().nullish(),next_run_at:$.string().nullish()}).nullish(),github:$.object({event:$.string().nullish(),action:$.string().nullish(),repo:$.string().nullish()}).nullish(),last_fired_at:$.string().nullish()}),h=$.object({id:$.string().min(1),name:$.string().nullish(),instructions:$.string().nullish(),enabled:$.boolean(),triggers:$.array(z0).default([])}),N0=$.object({items:$.array(h).default([]),end_cursor:$.string().nullish(),has_next_page:$.boolean().optional()}),K0=$.object({id:$.string().min(1),slug:$.string().nullish(),name:$.string(),description:$.string().nullish(),transport:$.string().nullish(),url:$.string().nullish(),enabled:$.boolean()}),M0=$.object({items:$.array(K0).default([])}),P0=$.object({status:$.string(),summary:$.string().nullish(),category:$.string().nullish(),outcome:$.string().nullish(),message_count:$.number().nullish(),pr_url:$.string().nullish(),cost_usd:$.number().nullish(),generated_at:$.string().nullish()}),E=$.object({tags:$.array($.string()).default([])}),_0=$.enum(["linux","macos"]),m=$.object({id:$.string().min(1),name:$.string().min(1),platform:_0.nullable(),workers:$.object({total:$.number().int(),online:$.number().int(),busy:$.number().int(),idle:$.number().int()}),sessions:$.object({queued:$.number().int(),running:$.number().int()})}),F0=$.object({machines:$.array(m)}),U0=$.object({machine:m}),T0=$.object({deleted:$.literal(!0),revoked_workers:$.number().int(),revoked_tokens:$.number().int()}),q0=$.object({token:$.object({id:$.string().min(1),machine_id:$.string().min(1),token_prefix:$.string()}),secret:$.string().startsWith("rmt_")}),I=$.looseObject({machine_id:$.string().min(1),machine_name:$.string().min(1)}),C0=I.extend({organization_id:$.string().min(1)}),b0=$.object({id:$.string().min(1),name:$.string().min(1),state:$.enum(["waiting","placed"]),queue_position:$.number().int().nullable()});function H1(x){let w=b0.safeParse(x.machine);return w.success?w.data:null}var O0=$.union([$.object({kind:$.literal("cloud")}),$.object({kind:$.enum(["mac","headless"]),device_id:$.string().min(1),root_id:$.string().min(1)})]);function G1(x){let w=O0.safeParse(x.runs_on);return w.success?w.data:null}function W(x,w,H){let G=x.safeParse(w);if(!G.success)throw new X(502,H,"Reason returned an unexpected response.");return G.data}var L0=$.object({error:$.object({type:$.string(),message:$.string()})});function g(x,w,H){let G=L0.safeParse(w),J=typeof w.error==="string"?w.error:G.success?G.data.error.type:`http_${x}`,Q=typeof w.detail==="string"?w.detail:typeof w.message==="string"?w.message:G.success?G.data.error.message:`Reason request failed (${x}${typeof w.error==="string"?` ${w.error}`:""})`,V=J==="github_connection_required"&&typeof w.connect_url==="string"&&/^https?:\/\//.test(w.connect_url)?` Connect it at ${w.connect_url}`:"",Z=H===null||H.trim()===""?NaN:Number(H);return new X(x,J,`${Q}${V}`,typeof w.suggested_model==="string"?w.suggested_model:void 0,Number.isFinite(Z)&&Z>=0?Z*1000:void 0,typeof w.resolution_reason==="string"?w.resolution_reason:void 0)}async function J1(x){let w=await(x.fetchImpl??fetch)(`${x.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${x.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(x.body),signal:AbortSignal.timeout(30000),redirect:"error"}),H=await w.json().catch(()=>({}));if(!w.ok)throw g(w.status,H,w.headers.get("retry-after"));return W(C0,H,"invalid_machine_ticket")}class A0{options;credentials;constructor(x,w={}){this.options=w;this.credentials=x}trackEvent(x,w={}){}async request(x,w={},H=!1){let G=this.options.fetchImpl??fetch,J=await G(`${this.credentials.apiOrigin}/v3${x}`,{method:w.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":"reason-cli","x-reason-agent":"Reason CLI",...w.raw?{"content-type":w.raw.contentType}:w.body===void 0?{}:{"content-type":"application/json"},...w.headers},body:w.raw?w.raw.bytes:w.body===void 0?void 0:JSON.stringify(w.body),signal:w.signal,redirect:"error"}),Q=await J.json().catch(()=>({}));if(J.status===401&&!H&&w.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let V=await P({fetchImpl:G,path:this.options.credentialsPath,forceRefresh:!0,signal:w.signal});if(V)return this.credentials=V,this.request(x,w,!0)}if(!J.ok)throw g(J.status,Q,J.headers.get("retry-after"));return Q}createHeadlessDeviceEnrollmentTicket(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:x,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(x){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:x,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(w){if(w instanceof X&&(w.status===404||w.status===405||w.status===403&&w.code==="endpoint_not_available"))return null;throw w}}addDeviceRoot(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(x)}/roots`,{method:"POST",body:w,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(x)}/roots/${encodeURIComponent(w)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(x,w=""){let H=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return x===void 0?H:`${H}/${encodeURIComponent(x)}${w}`}async listMachines(){return W(F0,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(x){let w=await this.request(this.machinePath(),{method:"POST",body:{name:x.name,...x.platform?{platform:x.platform}:{}}});return W(U0,w,"invalid_machine").machine}async deleteMachine(x){let w=await this.request(this.machinePath(x),{method:"DELETE"});return W(T0,w,"invalid_machine_deletion")}async createMachineToken(x){let w=await this.request(this.machinePath(x,"/tokens"),{method:"POST",body:{}});return W(q0,w,"invalid_machine_token")}async createMachineEnrollmentTicket(x,w){let H=await this.request(this.machinePath(x,"/enrollment-tickets"),{method:"POST",body:w,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return W(I,H,"invalid_machine_ticket")}self(x){return this.request("/self",{signal:x})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:x,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:x,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(x,w){let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:x,signal:w});return W(f,H,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(x)}`,{method:"POST",body:w,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(x){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:{messages:x},signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((w)=>typeof w.email==="string"?[{email:w.email,role:typeof w.role==="string"?w.role:"member"}]:[])}claimExistingCliPairing(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:x}})}async claudeCodeSignIn(){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(x,w,H={}){let G=x.kind==="setup_token"?{setup_token:x.token}:{access_token:x.credential.access,refresh_token:x.credential.refresh,expires_at:new Date(x.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:H.retryUnauthorized,signal:H.signal,body:{...G,...w?{account_key:w}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((w)=>{let H=typeof w.full_name==="string"?w.full_name:typeof w.repo_full_name==="string"?w.repo_full_name:null;if(!H)return[];return[{repo_id:typeof w.repo_id==="string"?w.repo_id:void 0,full_name:H,provider:w.provider==="gitlab"?"gitlab":"github",default_branch:typeof w.default_branch==="string"?w.default_branch:null,private:typeof w.private==="boolean"?w.private:void 0}]})}async listProjects(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),w=V0.safeParse(x);if(!w.success)throw new X(502,"invalid_project_list","Reason returned an unexpected project list.");return w.data.items}async listReasons(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return W(Y0,x,"invalid_reason_list").items}async openReasonConversation(x){let w=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(x)}/conversation`,{method:"POST"});return W($.object({session_id:$.string().min(1)}),w,"invalid_reason_conversation").session_id}async listSkills(){try{let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return W(D0,x,"invalid_skill_list").items}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return[];throw x}}async listDevices(){let x=[],w=null;for(let H=0;H<50;H+=1){let G=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${w?`?after=${encodeURIComponent(w)}`:""}`),J=W0.safeParse(G);if(!J.success)throw new X(502,"invalid_device_list","Reason returned an unexpected machine list.");if(x.push(...J.data.devices),w=J.data.has_next_page?J.data.end_cursor??null:null,!w)break}return x}async listModels(){try{let w=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((J)=>J.hidden!==!0),H=w.filter((J)=>J.available!==!1).map(({reasoning_efforts:J,hidden:Q,available:V,...Z})=>({...Z,...Array.isArray(J)?{reasoning_efforts:J0.filter((Y)=>J.includes(Y))}:{}})),G=new Set(H.map((J)=>J.detail));return{models:H.length>1&&G.size===1?H.map(({detail:J,...Q})=>Q):H,runnable:H.length>0||w.length===0}}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return{models:[],runnable:!0};throw x}}async getAgentVersion(x){try{let w=await this.request("/deployment",{signal:x,retryUnauthorized:!1});return _(w.reason_version)?w.reason_version:null}catch{return null}}async getUsageQuota(){try{let x=$0.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!x.success)return null;let w;try{w=G0(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...x.data,own_inference:w}}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return null;throw x}}async listSessions(x=50,w,H={}){let G=new URLSearchParams({first:String(Math.min(Math.max(x,1),200)),status:H.status??"active"});if(w)G.set("project_id",w);if(H.origin)G.set("origin",H.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${G.toString()}`)).items??[]}getSession(x,w){let H=w?.fields.length?`?fields=${encodeURIComponent(w.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}${H}`)}async prestartSession(x){let w=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:x}});return w?.status==="starting"||w?.status==="ready"}async createSession(x){let w=x.mode==="ephemeral"||x.workspaceOwnership==="externally-managed";if(x.attachments?.length)await this.requireSessionAttachments();if(w||x.runtimeProfile){let J=await this.request("/deployment");if(w&&(!Array.isArray(J.session_modes)||!J.session_modes.includes(x.mode??"standard")||!Array.isArray(J.workspace_ownerships)||!J.workspace_ownerships.includes(x.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(x.runtimeProfile&&(!Array.isArray(J.experimental_runtime_profiles)||!J.experimental_runtime_profiles.includes(x.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:x.prompt,...x.attachments?.length?{attachments:x.attachments}:{},...x.mode?{mode:x.mode}:{},...x.workspaceOwnership?{workspace_ownership:x.workspaceOwnership}:{},...x.target?{target:x.target}:{},...x.repo?{repo:x.repo}:{},...x.provider?{provider:x.provider}:{},...x.model?{model:x.model}:{},...x.reasoningEffort?{reasoning_effort:x.reasoningEffort}:{},...x.runtimeProfile?{experimental_runtime_profile:x.runtimeProfile}:{},...x.ref?{ref:x.ref}:{},...x.branch?{branch:x.branch}:{},...x.completionMode?{completion_mode:x.completionMode}:{},...x.env&&Object.keys(x.env).length>0?{env:x.env}:{},...x.clientSessionId?{client_session_id:x.clientSessionId}:{},...x.longRunning?{long_running:{enabled:!0}}:{},...x.spendLimitRcu?{spend_limit_rcu:x.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),G=await this.getSession(H.session_id);if(w){let J=G.session_policy,Q=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!J||J.version!==1||J.mode!==(x.mode??"standard")||J.workspaceOwnership!==(x.workspaceOwnership??"managed")||!J.components||Q.some((V)=>J.components[V]!==!0))throw await this.cancelSession(H.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(x.runtimeProfile&&G.experimental_runtime_profile!==x.runtimeProfile)throw await this.cancelSession(H.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return G}async getEvents(x,w=-1,H={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/events?after_seq=${w}&limit=500${H.waitMs?`&wait_ms=${H.waitMs}`:""}`,H.signal?{signal:H.signal}:{})}catch(G){if(!(G instanceof X)||G.status!==403&&G.status!==404)throw G;return{session:await this.getSession(x),items:[],next_seq:w}}}async getMessages(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages?first=500${w===void 0?"":`&after_seq=${w}`}`)}async getAttachments(x,w){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/attachments${w?`?view=${w}`:""}`)).items??[]}catch(H){if(H instanceof X&&(H.status===403||H.status===404))return[];throw H}}async requireSessionAttachments(){let x=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(x.session_attachments!==!0){let w=typeof x.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(x.reason_version)?`Agent ${x.reason_version}`:null,H=typeof x.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(x.commit_sha)?`server ${x.commit_sha.slice(0,12)}`:null,G=[w,H].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${G?` (${G})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(x,w,H={}){if(H.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages`,{method:"POST",body:{message:w,...H.attachments?.length?{attachments:H.attachments}:{},...H.model?{model:H.model}:{},...H.reasoningEffort?{reasoning_effort:H.reasoningEffort}:{},...H.target?{target:H.target}:{},...H.delivery?{delivery:H.delivery}:{}}})}async steerQueuedMessage(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages/${encodeURIComponent(w)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages/${encodeURIComponent(w)}/queued`,{method:"DELETE"})}async getConversation(x){let w=[],H=null;for(let G=0;G<50;G+=1){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/conversation${H?`?after=${encodeURIComponent(H)}`:""}`);if(w.push(...J.items??[]),!J.has_next_page||!J.end_cursor)break;H=J.end_cursor}return w}createSharedLink(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/shared-links`,{method:"POST",body:{url:w.url,...w.label?{label:w.label}:{},...w.expiresInSeconds!==void 0?{expires_in_seconds:w.expiresInSeconds}:{}}})}sessionAction(x,w,H={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/${w}`,{method:"POST",body:H})}renameSession(x,w){return this.sessionAction(x,"rename",{title:w||null})}moveSessionToProject(x,w){return this.sessionAction(x,"project",{project_id:w})}compactSession(x){return this.sessionAction(x,"compact")}retrySession(x){return this.sessionAction(x,"retry")}rewindSession(x,w){return this.sessionAction(x,"rewind",{message_id:w.messageId,content:w.content,request_id:w.requestId})}forkSession(x,w){return this.sessionAction(x,"fork",{...w.message?{message:w.message}:{},client_session_id:w.clientSessionId})}cancelSession(x,w={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/cancel`,{method:"POST",body:w.mode==="hard"?{mode:"hard"}:{}})}sessionPath(x,w=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}${w}`}async archiveSession(x){await this.request(this.sessionPath(x,"/archive"),{method:"POST",body:{}})}async unarchiveSession(x){await this.request(this.sessionPath(x,"/unarchive"),{method:"POST",body:{}})}async deleteSession(x){await this.request(this.sessionPath(x),{method:"DELETE"})}async listSessionTags(x){return W(E,await this.request(this.sessionPath(x,"/tags")),"invalid_session_tags").tags}async appendSessionTags(x,w){let H=await this.request(this.sessionPath(x,"/tags"),{method:"POST",body:{tags:w}});return W(E,H,"invalid_session_tags").tags}async sessionInsight(x,w=!1){let H=await this.request(this.sessionPath(x,w?"/insights/generate":"/insights"),w?{method:"POST",body:{}}:{});return W(P0,H,"invalid_session_insight")}async listAutomations(){let x=[],w=null;for(let H=0;H<20;H+=1){let G=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${w?`&after=${encodeURIComponent(w)}`:""}`),J=W(N0,G,"invalid_automation_list");if(x.push(...J.items),w=J.has_next_page?J.end_cursor??null:null,!w)break}return x}async createScheduledAutomation(x,w){let H=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,G=W(h,await this.request(H,{method:"POST",body:{name:x.name,instructions:x.instructions,...x.repo?{repo:x.repo.full_name,provider:x.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${H}/${encodeURIComponent(G.id)}/triggers`,{method:"POST",body:w})}catch(J){throw await this.deleteAutomation(G.id).catch(()=>{return}),J}return G}async setAutomationEnabled(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(x)}`,{method:"PATCH",body:{enabled:w}})}async deleteAutomation(x){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(x)}`,{method:"DELETE"})}async transcribe(x,w){let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:x,contentType:w}});return W($.object({transcript:$.string()}),H,"invalid_transcript").transcript}async listMcpServers(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return W(M0,x,"invalid_mcp_server_list").items}async setSkillEnabled(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(x)}`,{method:"PUT",body:{is_enabled:w}})}}
5
+ export{B as A,M as B,n0 as C,P as D,o0 as E,X as F,J0 as G,H1 as H,G1 as I,J1 as J,A0 as K};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{u as g0}from"./vm-hands-entry-lite-k2e3q5qj.js";import{v as Q2,x as N7,y as Y4}from"./vm-hands-entry-lite-m16qf0yy.js";import{A as q2,B as V7,C as M4,D as T4,E as u6,F as v0,J as d6,K as I$}from"./vm-hands-entry-lite-pnkfgnqz.js";import{$ as h1,R as jJ,S as WJ,T as y8,U as f8,V as J6,W as Z6,X as b9,Y as A5,Z as v8,_ as _0,aa as m1,ba as P0,ca as n1,da as R5,ea as p5,fa as t3,ga as b5,ka as w5,ta as Y6,ua as G6,va as K6,wa as B6,xa as k9}from"./vm-hands-entry-lite-qwb91tgj.js";import{$a as i8,Ab as m2,Ca as o8,Cb as z5,Da as e8,Db as B9,Fb as H5,Ga as a8,Ia as G5,Jb as $6,Kb as X9,La as K5,Qa as N5,Ra as q5,Sa as h8,Ta as m8,Ua as nJ,Va as rJ,Xa as u,Ya as e,Za as s,_a as c,ab as oJ,bb as _1,eb as G3,fb as K3,gb as G7,hb as K7,ib as B7,jb as b0,kb as J0,lb as g,mb as w9,nb as R1,ob as Z2,pb as N0,qb as eJ,vb as d5,xb as H8,za as I6}from"./vm-hands-entry-lite-f66d7y5a.js";import{Pb as g8}from"./vm-hands-entry-lite-7ba3nhgv.js";import{Wb as O5}from"./vm-hands-entry-lite-wmxksawm.js";import{cc as B5,dc as U5,kc as V5}from"./vm-hands-entry-lite-k2cvr710.js";import{qc as H$}from"./vm-hands-entry-lite-8ynztq9j.js";import{Fc as k8}from"./vm-hands-entry-lite-0wyjnvjz.js";import{Lc as c$,Mc as X$,Nc as C$,Oc as F1,Pc as l6,Qc as q7,Rc as H7,Sc as L1,Tc as M7,Uc as s9,Vc as T7,Wc as Z3,Xc as T$,Yc as G8,Zc as Q3,bd as C5,ed as Q6,hd as DJ,id as OJ}from"./vm-hands-entry-lite-z0wwfy97.js";import{ae as w8,ie as f6,je as t$,te as V2,ud as C2,yd as aJ,zd as iJ}from"./vm-hands-entry-lite-36xzwsxn.js";import{Ge as U7,He as n2,Ke as X6,Ne as l1,Pe as w7,Qe as k7,Ve as S5}from"./vm-hands-entry-lite-wgjqxtxj.js";import{$e as r1,af as D5}from"./vm-hands-entry-lite-pa111vpq.js";import{df as o6,gf as I5,hf as x9,jf as u8}from"./vm-hands-entry-lite-449p9dx7.js";import{wf as t}from"./vm-hands-entry-lite-7qg63rj8.js";import{dg as w1,eg as G0,fg as B2,gg as N6,hg as q6,ig as r$,jg as W3,kg as k2,lg as z4,ng as y2,og as k$,pg as f0,qg as o$,rg as f2,ug as y$}from"./vm-hands-entry-lite-kt418g2w.js";import{yg as Y5}from"./vm-hands-entry-lite-knfh7w3j.js";import{Ch as z$,Dh as C0,Eh as B4,Fh as Q7,Gh as X7,Ih as A2,Jh as Y7,Kh as E9,Lh as X8,Mh as Y8,Nh as Q1,wh as O$,xh as E1,zh as Q$}from"./vm-hands-entry-lite-1xjtcxpn.js";import{Oh as U0,Qh as vJ}from"./vm-hands-entry-lite-9dx3at21.js";import{mi as U}from"./vm-hands-entry-lite-2xh7sjs0.js";import{pi as tJ}from"./vm-hands-entry-lite-0jar357h.js";import{ui as h0}from"./vm-hands-entry-lite-gt5pkv4h.js";import{Ai as JB}from"./vm-hands-entry-lite-mhsv58hw.js";import{spawn as _7,spawnSync as ZB}from"child_process";import{closeSync as F7,mkdirSync as QB,openSync as L7,readdirSync as XB,realpathSync as Y$,rmSync as W1}from"fs";import{hostname as YB}from"os";import{dirname as a9,join as F0,resolve as GB}from"path";import{createHash as f7}from"crypto";import{unlinkSync as h7}from"fs";import{platform as m7}from"os";import{join as v7}from"path";var G4=U.discriminatedUnion("store",[U.strictObject({version:U.literal(1),store:U.literal("keychain")}),U.strictObject({version:U.literal(1),store:U.literal("file"),api_key:U.string().min(1).max(4096)})]),w$=($)=>v7($,"api-key.json");function L$($){let J=f7("sha256").update(`reason-connect-api-key
2
+ import{u as g0}from"./vm-hands-entry-lite-tdgbgcer.js";import{v as Q2,x as N7,y as Y4}from"./vm-hands-entry-lite-hwjtyptw.js";import{A as q2,B as V7,C as M4,D as T4,E as u6,F as v0,J as d6,K as I$}from"./vm-hands-entry-lite-1ey4kprv.js";import{$ as h1,R as jJ,S as WJ,T as y8,U as f8,V as J6,W as Z6,X as b9,Y as A5,Z as v8,_ as _0,aa as m1,ba as P0,ca as n1,da as R5,ea as p5,fa as t3,ga as b5,ka as w5,sa as Y6,ta as G6,ua as K6,va as B6,wa as k9}from"./vm-hands-entry-lite-0d93secz.js";import{$a as oJ,Ba as o8,Bb as z5,Ca as e8,Cb as B9,Eb as H5,Fa as a8,Ha as G5,Ib as $6,Jb as X9,Ka as K5,Pa as N5,Qa as q5,Ra as h8,Sa as m8,Ta as nJ,Ua as rJ,Wa as u,Xa as e,Ya as s,Za as c,_a as i8,ab as _1,db as G3,eb as K3,fb as G7,gb as K7,hb as B7,ib as b0,jb as J0,kb as g,lb as w9,mb as R1,nb as Z2,ob as N0,pb as eJ,ub as d5,wb as H8,ya as I6,zb as m2}from"./vm-hands-entry-lite-hz0ywb12.js";import{Ob as g8}from"./vm-hands-entry-lite-dyy62gt3.js";import{Vb as O5}from"./vm-hands-entry-lite-wpx6sg6d.js";import{$b as U5,_b as B5,gc as V5}from"./vm-hands-entry-lite-nbtpm59m.js";import{mc as H$}from"./vm-hands-entry-lite-gcn3rmz6.js";import{Bc as k8}from"./vm-hands-entry-lite-beannz0s.js";import{Hc as c$,Ic as X$,Jc as C$,Kc as F1,Lc as l6,Mc as q7,Nc as H7,Oc as L1,Pc as M7,Qc as s9,Rc as T7,Sc as Z3,Tc as T$,Uc as G8,Vc as Q3,Zc as C5,ad as Q6,dd as DJ,ed as OJ}from"./vm-hands-entry-lite-8hez8yg7.js";import{Yd as w8,ee as f6,fe as t$,pe as V2,qd as C2,ud as aJ,vd as iJ}from"./vm-hands-entry-lite-qf01e5f1.js";import{Ce as U7,De as n2,Ge as X6,Je as l1,Le as w7,Me as k7,Re as S5}from"./vm-hands-entry-lite-pztap0be.js";import{Xe as r1,Ye as D5}from"./vm-hands-entry-lite-xhjbc3e4.js";import{$e as o6,cf as I5,df as x9,ff as u8}from"./vm-hands-entry-lite-gkd1gkfc.js";import{sf as t}from"./vm-hands-entry-lite-9khka7wc.js";import{$f as w1,ag as G0,bg as B2,cg as N6,dg as q6,eg as r$,fg as W3,gg as k2,hg as z4,jg as y2,kg as k$,lg as f0,mg as o$,ng as f2,qg as y$}from"./vm-hands-entry-lite-33ttamma.js";import{ug as Y5}from"./vm-hands-entry-lite-mybm2kyz.js";import{Ah as B4,Bh as Q7,Ch as X7,Eh as A2,Fh as Y7,Gh as E9,Hh as X8,Ih as Y8,Jh as Q1,sh as O$,th as E1,vh as Q$,yh as z$,zh as C0}from"./vm-hands-entry-lite-6qfax5p2.js";import{Kh as U0,Mh as vJ}from"./vm-hands-entry-lite-5b29hq7h.js";import{ii as U}from"./vm-hands-entry-lite-k17ntg9v.js";import{li as tJ}from"./vm-hands-entry-lite-6f5eypjm.js";import{qi as h0}from"./vm-hands-entry-lite-tj1y61bg.js";import{wi as JB}from"./vm-hands-entry-lite-nd1k2jz9.js";import{spawn as _7,spawnSync as ZB}from"child_process";import{closeSync as F7,mkdirSync as QB,openSync as L7,readdirSync as XB,realpathSync as Y$,rmSync as W1}from"fs";import{hostname as YB}from"os";import{dirname as a9,join as F0,resolve as GB}from"path";import{createHash as f7}from"crypto";import{unlinkSync as h7}from"fs";import{platform as m7}from"os";import{join as v7}from"path";var G4=U.discriminatedUnion("store",[U.strictObject({version:U.literal(1),store:U.literal("keychain")}),U.strictObject({version:U.literal(1),store:U.literal("file"),api_key:U.string().min(1).max(4096)})]),w$=($)=>v7($,"api-key.json");function L$($){let J=f7("sha256").update(`reason-connect-api-key
3
3
  ${$}`).digest("hex");return new r$(B2(),m7(),J)}function L3($,J,Z=L$($)){try{Z.deleteBinding(),Z.createBinding(new TextEncoder().encode(J)),c(w$($),{version:1,store:"keychain"});return}catch(Q){if(!(Q instanceof G0))throw Q}c(w$($),{version:1,store:"file",api_key:J})}function l0($,J=L$($)){if(!u(w$($)))return null;let Z=G4.parse(JSON.parse(s(w$($))));if(Z.store==="file")return Z.api_key;try{let Q=J.loadBinding();return Q?new TextDecoder().decode(Q):null}catch(Q){if(!(Q instanceof G0))throw Q;throw Error("worker_api_key_unreadable")}}function K4($,J=L$($)){if(!u(w$($)))return;if(G4.parse(JSON.parse(s(w$($)))).store==="keychain")try{J.deleteBinding()}catch(Z){if(!(Z instanceof G0))throw Z}h7(w$($))}async function j3($,J){let Z;try{Z=await Y4({env:{REASON_API_KEY:J,REASON_API_URL:$.apiOrigin},fetchImpl:b0($.proxy)})}catch(Q){if(Q instanceof v0&&(Q.status===401||Q.status===403))throw Error("worker_api_key_rejected");throw Q}if(!Z)throw Error("worker_api_key_rejected");if(!Z.scopes.includes("devices:write"))throw Error("worker_api_key_devices_write_required");return Z}import{readdirSync as XZ,renameSync as YZ,rmSync as f$}from"fs";import{join as H0}from"path";import{createHash as g7}from"crypto";import{realpathSync as u7,statSync as d7,unlinkSync as U2}from"fs";import{platform as l7}from"os";import{join as w0}from"path";function d($){return{state:w0(g($),"device.json"),control:w0(g($),"control.json"),lock:w0(g($),"lifecycle.lock"),socket:w0(g($),"control.sock"),daemon:w0(g($),"daemon.json"),releaseCheck:w0(g($),"release-check.json"),updateDeferral:w0(g($),"update-deferral.json"),firstHeartbeat:w0(g($),"first-heartbeat.json")}}var p7=U.object({version:U.literal(1),device_id:U.string().min(1).max(160),offer:U.unknown().optional(),enrollment_ms:U.number().int().nonnegative().max(t$).optional()});function U4($,J,Z){e(g($),!0),c(d($).firstHeartbeat,{version:1,device_id:J,...Z.offer?{offer:Z.offer}:{},...Z.enrollmentMs!==void 0?{enrollment_ms:Z.enrollmentMs}:{}})}function D3($,J){let Z=d($).firstHeartbeat;try{if(!u(Z))return null;let Q=p7.safeParse(JSON.parse(s(Z)));if(U2(Z),!Q.success||Q.data.device_id!==J)return null;let X=V2(Q.data.offer);return{...X?{offer:X}:{},...Q.data.enrollment_ms!==void 0?{enrollmentMs:Q.data.enrollment_ms}:{}}}catch{return null}}function T0($,J=!1){e(g($),J);let Z=["local-device.key","local-device.binding","device.json"].filter((Q)=>{let X=w0(g($),Q);if(!u(X))return!1;return s(X),!0});return $.lifetime==="persistent"&&Z.join()==="device.json"?O3($):new W3(g($))}function N2($,J){T0($,!0),a7($);let Z=J??O3($),Q=new W3(g($));try{Z.deleteBinding(),Z.deleteKey(),Z.createFreshPublicKey()}catch(X){if(X instanceof G0)return Q;throw X}return Q.deleteBinding(),Q.deleteKey(),Z}function O3($){return new r$(B2(),l7(),c7($))}function c7($){let J=z3($);return g7("sha256").update(`reason-worker
4
4
  ${J?.directory??g($)}`).digest("hex")}function I1($,J){c(w0(g($),C1),{version:1,directory:z3($)?.directory??g($),devicePublicKey:J})}var C1="keychain-scope.json";function V4($){return u(w0(g($),C1))}var s7=U.strictObject({version:U.literal(1),directory:U.string().min(1),devicePublicKey:U.string().min(1)});function z3($){let J=w0(g($),C1);if(!u(J))return null;let Z=s7.safeParse(JSON.parse(s(J))),Q=d($).state;if(!Z.success||!u(Q))return null;return JSON.parse(s(Q))?.devicePublicKey===Z.data.devicePublicKey?Z.data:null}function a7($){let J=w0(g($),C1);if(!u(J))return;if(z3($))try{let Z=O3($);Z.deleteBinding(),Z.deleteKey()}catch(Z){if(!(Z instanceof G0))throw Z}U2(J)}function V$($){let J=u7($.workspaceRoot);if(J!==$.workspaceRoot||!d7(J).isDirectory()||!R1(J,$.stateDirectory))throw Error("worker_workspace_not_canonical_or_overlaps_state")}function o($){if(!u(g($)))return null;let J=k$(d($).state,{proofStore:T0($),repair:!1}),Z=J!==null&&B4($.apiOrigin,J.apiOrigin),Q=Z?[N0($),N0({...$,apiOrigin:J.apiOrigin})]:[N0($)];if(J&&(!Q.includes(J.worker?.configDigest??"")||J.worker.lifetime!==$.lifetime||J.apiOrigin!==$.apiOrigin&&!Z||J.roots.length>32||J.roots[0]?.path!==$.workspaceRoot||J.handsSlots!==$.slots))throw Error("worker_config_binding_mismatch");return J}var N4=U.strictObject({version:U.literal(1),drained:U.boolean(),revoked:U.boolean()});function $0($){let J=d($).control;return u(J)?N4.parse(JSON.parse(s(J))):{version:1,drained:!1,revoked:!1}}function I0($,J){c(d($).control,N4.parse(J))}function k0($){let J=T0($);J.deleteBinding(),J.deleteKey();let Z=w0(g($),C1);if(u(Z))U2(Z);let Q=d($).state;if(u(Q))U2(Q)}var i7=U.strictObject({read:U.boolean(),write:U.boolean(),execute:U.boolean(),discover_environment:U.boolean(),expose_mcp:U.literal(!1)}),A3=U.strictObject({version:U.literal(1),organization_id:U.string().min(1).max(160),enrollment_ticket:U.string().min(1).max(4096),code_verifier:U.string().regex(/^[A-Za-z0-9._~-]{43,128}$/),root_fingerprint_key:U.string().regex(/^[a-f0-9]{64}$/),root:U.strictObject({path_fingerprint:U.string().regex(/^[a-f0-9]{64}$/),permissions:i7,execution_mode:U.enum(["confined","host"]).default("confined")}),folders:U.array(U.strictObject({path_fingerprint:U.string().regex(/^[a-f0-9]{64}$/)})).min(1).max(31).optional()}),n7=U.object({device_id:U.string().min(1).max(160),organization_id:U.string().min(1).max(160),auth_scheme:U.literal("p256"),protocol_version:U.literal(2),roots:U.array(U.object({id:U.string().min(1),label:U.string(),path_fingerprint:U.string()})).min(1).max(32),headless:U.object({lifecycle:U.enum(["persistent","ephemeral"]),expires_at:U.iso.datetime({offset:!0})}),first_heartbeat:U.unknown().optional()}),R3=30000;class o0 extends Error{deviceRemoved;constructor($){super("worker_enrollment_rejected");this.deviceRemoved=$}}async function r7($,J,Z=fetch){let Q=await Z(`${$}/app/local-runtime/enroll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J),redirect:"error",signal:AbortSignal.timeout(R3)});if(!Q.ok){let X=Q.status===409?await Q.json().catch(()=>null):null;throw new o0(X?.error==="device_revoked")}return Q.json()}async function I3($,J,Z,Q){g0();let X=A3.parse(JSON.parse(s(J)));return e0($,X,Z,Q)}async function e0($,J,Z,Q=(Y,G)=>r7(Y,G,b0($.proxy)),X=performance.now()){let Y=H4($,J,Z),G=await Q($.apiOrigin,{...Y.request,enrollment_ticket:J.enrollment_ticket,code_verifier:J.code_verifier});return Y.receipt(G,X)}async function q4($,J,Z,Q,X=performance.now()){let Y=H4($,J,Z),G=await Q(Y.request,J.code_verifier);return G===null?null:Y.receipt(G,X)}function H4($,J,Z){if(g0(),J.root.execution_mode!==$.executionMode)throw Error("worker_enrollment_mode_mismatch");let Q=y$([$.workspaceRoot],J.root.permissions,Buffer.from(J.root_fingerprint_key,"hex"))[0];if(Q.path!==$.workspaceRoot||Q.pathFingerprint!==J.root.path_fingerprint)throw Error("worker_enrollment_root_mismatch");let X=($.folders??[]).map((K,N)=>{let H=y$([K],J.root.permissions,Buffer.from(J.root_fingerprint_key,"hex"))[0];if(H.path!==K||H.pathFingerprint!==J.folders?.[N]?.path_fingerprint)throw Error("worker_enrollment_root_mismatch");return H});if((J.folders?.length??0)!==X.length)throw Error("worker_enrollment_root_mismatch");let Y=[{...Q,label:"workspace"},...X],G;try{G=Z.loadPublicKey()}catch{G=Z.createFreshPublicKey()}return{request:{device_public_key:G,name:$.name,os:process.platform,architecture:process.arch,reason_runtime_version:t,bridge_version:t,protocol_version:2,capabilities:{supported_operations:[]},roots:Y.map((K)=>({label:K.label,path_fingerprint:K.pathFingerprint,permissions:J.root.permissions}))},receipt(K,N){let H=n7.parse(K);if(H.organization_id!==J.organization_id||H.roots.length!==Y.length||H.roots.some((q,M)=>q.path_fingerprint!==Y[M].pathFingerprint)||H.headless.lifecycle!==$.lifetime||Date.parse(H.headless.expires_at)<=Date.now())throw Error("worker_enrollment_receipt_mismatch");let B=V2(H.first_heartbeat);try{U4($,H.device_id,{...B?{offer:B}:{},enrollmentMs:Math.min(t$,Math.max(0,Math.round(performance.now()-N)))})}catch{}return{version:4,apiOrigin:$.apiOrigin,orgId:H.organization_id,deviceId:H.device_id,devicePublicKey:G,displayName:$.name,registeredAt:new Date().toISOString(),handsSlots:$.slots,worker:{configDigest:N0($),lifetime:$.lifetime,expiresAt:H.headless.expires_at},roots:H.roots.map((q,M)=>({id:q.id,label:q.label,path:Y[M].path,pathFingerprint:q.path_fingerprint,permissions:J.root.permissions}))}}}}import{randomBytes as t7,randomUUID as o7}from"crypto";import{unlinkSync as e7}from"fs";import{join as $Z}from"path";var _4=U.strictObject({version:U.literal(1),install_id:U.uuid(),fingerprint_key:U.string().regex(/^[a-f0-9]{64}$/)}),JZ=U.object({enrollment_ticket:U.string().min(1).max(4096),expires_at:U.iso.datetime({offset:!0}),device_kind:U.literal("headless"),lifecycle:U.enum(["persistent","ephemeral"]),device_expires_at:U.iso.datetime({offset:!0})});function C3($){return JZ.parse($)}var ZZ=U.object({credentialKind:U.enum(["oauth","api_key"]).optional(),apiOrigin:U.url(),clientId:U.string(),accessToken:U.string().min(1).max(32768),refreshToken:U.string().max(32768),expiresAt:U.iso.datetime({offset:!0}),scopes:U.array(U.string().max(128)).max(128),orgId:U.string().min(1).max(160)});function j$($){return q2(E1("REASON_CLI_CHANNEL",$.channel),U0())}async function W$($,J=j$($)){if(!u(J))return null;let Z=ZZ.parse(JSON.parse(s(J)));if(!C0(Z.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(Z.credentialKind==="api_key")return Date.parse(Z.expiresAt)>Date.now()?Z:null;let Q=b0($.proxy),X=Object.assign((G,V)=>Q(G,{...V,redirect:"error",signal:AbortSignal.timeout(30000)}),{preconnect:fetch.preconnect}),Y=await T4({path:J,fetchImpl:X});if(Y&&!C0(Y.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");return Y}async function F4($,J,Z){if(!C0(J.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(!J.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let Q=D$($);return Q.complete(J.orgId,await Z.createHeadlessDeviceEnrollmentTicket(Q.request))}async function L4($,J,Z,Q,X){let Y=performance.now();if(!C0(J.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(!J.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let G=D$($),V=X?void 0:Z.enrollHeadlessDevice?.bind(Z);if(V){let K=await q4($,G.direct(J.orgId),Q,(N,H)=>V({approval:G.request,code_verifier:H,registration:N}).catch((B)=>{throw QZ(B)}),Y);if(K)return K}return e0($,G.complete(J.orgId,await Z.createHeadlessDeviceEnrollmentTicket(G.request)),Q,X,Y)}function QZ($){if(!($ instanceof v0))return $;if($.status===409)return new o0($.code==="device_revoked");if($.status===410||$.status===401&&$.code==="invalid_enrollment_ticket"||$.status===403&&$.code==="grant_exceeded"||$.status===400&&$.code==="invalid_device_enrollment")return new o0(!1);return $}var P1=($)=>$Z(g($),"enrollment-install.json");function j4($){if(u(P1($)))e7(P1($))}function D$($,{stored:J=!0}={}){g0();let Z=P1($),Q=J&&u(Z)?_4.parse(JSON.parse(s(Z))):{version:1,install_id:o7(),fingerprint_key:t7(32).toString("hex")};if(J&&!u(Z))c(Z,Q);let X={read:!0,write:!0,execute:!0,discover_environment:!0,expose_mcp:!1},Y=Buffer.from(Q.fingerprint_key,"hex"),G=y$([$.workspaceRoot],X,Y)[0];if(G.path!==$.workspaceRoot)throw Error("worker_workspace_not_canonical_or_overlaps_state");let V=($.folders??[]).map((B)=>{let q=y$([B],X,Y)[0];if(q.path!==B)throw Error("worker_workspace_not_canonical_or_overlaps_state");return{path_fingerprint:q.pathFingerprint}}),K=M4(),N={install_id:Q.install_id,code_challenge:K.challenge,lifecycle:$.lifetime,roots:[G.pathFingerprint,...V.map((B)=>B.path_fingerprint)].map((B)=>({path_fingerprint:B,permissions:X,execution_mode:$.executionMode}))},H=(B)=>({version:1,organization_id:B,code_verifier:K.verifier,root_fingerprint_key:Q.fingerprint_key,root:{path_fingerprint:G.pathFingerprint,permissions:X,execution_mode:$.executionMode},...V.length?{folders:V}:{}});return{request:N,saveInstall(B){e(g(B),!0),c(P1(B),Q)},complete(B,q){let M=C3(q);if(M.lifecycle!==$.lifetime||Date.parse(M.expires_at)<=Date.now()||Date.parse(M.device_expires_at)<=Date.now())throw Error("worker_ticket_receipt_mismatch");return{...H(B),enrollment_ticket:M.enrollment_ticket}},direct:H}}function W4($,J,Z){let Q=P1($);if(!u(Q))throw Error("worker_folders_unavailable");let X=_4.parse(JSON.parse(s(Q)));return y$([J],Z,Buffer.from(X.fingerprint_key,"hex"))[0]}var H2=8,A4=600000,R4=15000,D4=new Set(["device_revoked","invalid_device_credential"]),M2=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,N$=($)=>H0(g($),"workspaces"),I4="account.json",P3=($)=>u(H0($,I4));function y0($){let J;try{J=XZ(N$($))}catch{return[]}return J.filter((Z)=>M2.test(Z)).sort().map((Z)=>{let Q=H0(N$($),Z),X=H0(Q,"worker.json"),Y=null;try{let G=J0.safeParse(JSON.parse(s(X)));if(G.success&&G.data.stateDirectory===Q)Y=G.data}catch{}return{organizationId:Z,directory:Q,configPath:X,config:Y,account:P3(Q)}})}function T2($,J){let Z=J.toLowerCase();if(!M2.test(Z))throw Error("worker_workspace_id_invalid");let Q=J0.parse({...$,stateDirectory:H0(N$($),Z)});return e(Q.stateDirectory,!0),c(H0(Q.stateDirectory,I4),{version:1}),{config:Q,configPath:H0(Q.stateDirectory,"worker.json")}}function _2($,J){try{let{config:Z,configPath:Q}=T2($,J);e(g(Z),!0),I0(Z,{version:1,drained:!0,revoked:!0}),c(Q,Z)}catch{}}function x1($,J){let Z=J.toLowerCase(),Q=null;try{Q=o($)?.orgId.toLowerCase()??null}catch{}return Q===Z||y0($).some((X)=>!X.account&&X.config!==null&&X.organizationId===Z)}var E3=["device.json","local-device.key","local-device.binding","keychain-scope.json","control.json","enrollment-install.json","first-heartbeat.json"];function O4($,J){let Z=o($);if(!Z?.worker)throw Error("worker_identity_missing");I1($,Z.devicePublicKey),e(g(J),!0);for(let Y of E3)f$(H0(g(J),Y),{force:!0});for(let Y of E3){let G=H0(g($),Y);if(u(G))YZ(G,H0(g(J),Y))}let Q=T0(J),X=k$(d(J).state,{proofStore:Q,repair:!1});if(!X?.worker)throw Error("worker_identity_missing");f0({...X,worker:{...X.worker,configDigest:N0(J)}},d(J).state,{proofStore:Q})}function x3($){for(let J of y0($)){if(J.account)continue;try{if(J.config&&u(d(J.config).state))k0(J.config)}catch{}f$(J.directory,{recursive:!0,force:!0})}f$(b3($),{force:!0})}function F2($,{prefer:J,keep:Z,live:Q=!1}){let X=Date.now(),Y=(B)=>Number(Date.parse(B.worker?.expiresAt??"")>X+60000),V=y0($).flatMap((B)=>{if(!B.account||!B.config)return[];try{if($0(B.config).revoked)return[];let q=o(B.config);return q&&q.orgId.toLowerCase()===B.organizationId&&(!Q||Y(q))?[{...B,config:B.config,state:q}]:[]}catch{return[]}}).sort((B,q)=>Number(q.organizationId===J)-Number(B.organizationId===J)||Y(q.state)-Y(B.state))[0];if(!V)return null;let K=null;try{K=$0($).revoked?null:o($)}catch{}let N=K?.orgId.toLowerCase()??"";if(Z&&K&&M2.test(N)&&N!==V.organizationId){let B=T2($,N);O4($,B.config),c(B.configPath,B.config)}else if(u(g($))){try{if(u(d($).state))k0($)}catch{}for(let B of E3)f$(H0(g($),B),{force:!0})}x3($);let H=J0.parse({...V.config,stateDirectory:$.stateDirectory});return O4(V.config,H),c(H0($.stateDirectory,"worker.json"),H),f$(V.directory,{recursive:!0,force:!0}),H}var S3={before($){for(let{config:J}of y0($))try{let Z=J?o(J):null;if(J&&Z)I1(J,Z.devicePublicKey)}catch{}},after($,J){for(let{organizationId:Z,directory:Q,configPath:X,config:Y}of y0(J)){if(Y)continue;try{let G=J0.parse(JSON.parse(s(X)));if(G.stateDirectory!==H0(N$($),Z))continue;let V=J0.parse({...G,stateDirectory:Q}),K=T0(V),N=k$(d(V).state,{proofStore:K,repair:!1});if(N?.worker?.configDigest===N0(G))f0({...N,worker:{...N.worker,configDigest:N0(V)}},d(V).state,{proofStore:K});c(X,V)}catch{}}}},b3=($)=>H0(N$($),"listed.json");function C4($){try{let J=JSON.parse(s(b3($))),Z=J.names&&typeof J.names==="object"&&!Array.isArray(J.names)?Object.fromEntries(Object.entries(J.names).filter((Q)=>typeof Q[1]==="string")):{};return{listed:J.listed===!0,reason:J.reason==="sign_in"?"sign_in":null,blocked:Array.isArray(J.blocked)?J.blocked.filter((Q)=>typeof Q==="string"):[],names:Z}}catch{return null}}function P4($,J){let Z=y0($),Q=Z.filter((K)=>K.account),X=Z.filter((K)=>!K.account),Y=C4($),G=Y&&!Y.listed?Y.reason:null,V=G||X.length===0&&Y&&!Y.listed?[]:X;if(Q.length===0&&V.length===0&&(G||Y&&!Y.listed))return{workspaces:null,off:G};return{off:G,workspaces:[...Q,...V].map(({organizationId:K,config:N,account:H})=>{let B=!1,q=null,M=!1,T=null;try{B=N?$0(N).revoked:!1,q=N&&!B?o(N):null;let _=N?o$(d(N).daemon):null;M=J&&!!q&&_?.state==="connected",T=M?z4(_,q):null}catch{}return{...T?{permission_recovery:T}:{},organization_id:K,device_id:q?.deviceId??null,name:Y?.names?.[K]??null,root:q?.roots[0]?{id:q.roots[0].id,permissions:q.roots[0].permissions}:null,state:B?"removed":M?"connected":"not_running",blocked:!H&&!B&&!M&&(Y?.blocked.includes(K)??!1),...H?{account:!0}:{}}})}}function E4($){let{config:J,state:Z,client:Q,signal:X}=$,Y=$.log??(()=>{return}),G=new Map,V=null,K=!1,N=C4(J)??{listed:!1,reason:null,blocked:[]},H=(L)=>{let{folders:W,...R}=J,E=Z.roots.slice(1).map((I)=>I.path);return J0.parse({...R,...E.length?{folders:E}:{},stateDirectory:H0(N$(J),L)})},B=async(L)=>{let W=G.get(L);if(!W)return;W.controller.abort(),await W.done},q=(L,W=!1)=>{let R=new AbortController,E=()=>R.abort();if(X.addEventListener("abort",E,{once:!0}),X.aborted)R.abort();let I={...L,controller:R,claims:0,done:Promise.resolve(),account:W};I.done=$.serve(L,R.signal,(C)=>{I.claims=C}).then(()=>{return},(C)=>{if(W&&C instanceof _0&&C.status===401&&D4.has(C.code)){try{I0(L.config,{version:1,drained:!0,revoked:!0})}catch{}Y(`Reason worker: workspace ${L.organizationId} (another account's) no longer accepts this computer (${C.code}); run \`reason connect\` signed in as that account to connect it again
5
5
  `)}else if(C instanceof _0&&C.status===401&&D4.has(C.code)){try{k0(L.config)}catch{}Y(`Reason worker: workspace ${L.organizationId} no longer accepts this computer
@@ -312,7 +312,7 @@ Usage:
312
312
  `),host:Z.host}),V=$8({...G,log:(M)=>Q.stderr.write(`${M}
313
313
  `)}),{configPath:K}=V,N=V.saved;if(!N)return Q.stderr.write("Reason: this computer has no saved connection. Run `reason connect`.\n"),0;let H=(M,T)=>{let _=q3(Z.home,Z.channel),j;try{let O=null;try{O=T.keep?null:o(N)?.orgId.toLowerCase()??null}catch{}if(j=F2(N,{prefer:X2(Z.home,Z.channel,N),...T}),j&&O)_2(j,O)}finally{_()}if(!j)return!1;N=j;let D="";try{D=` (workspace ${o(j)?.orgId??"unknown"})`}catch{}return Q.stderr.write(`Reason: ${M}; this computer goes on running Sessions for its other Reason account${D}.
314
314
  `),!0};if($0(N).revoked&&!H("this computer's connection was removed from Reason",{keep:!1}))return Q.stderr.write("Reason: this computer was removed from Reason. Run `reason connect` to connect it again.\n"),0;if(N.executionMode==="confined"||!j1(N)){let M=l0(N.stateDirectory)??void 0,T=M?null:X2(Z.home,Z.channel,N);if(!M&&!(T&&x1(N,T)))H("this computer's connection expired and its account is not signed in here",{keep:!0,live:!0})}let B=N.executionMode==="confined";if(B||!j1(N)){let M=l0(N.stateDirectory)??void 0;if(Q.stderr.write(B?O7:`Reason: this computer's connection expired; renewing it with ${M?"its API key":"your login"}\u2026
315
- `),await i9(J0.parse({...N,executionMode:"host"}),K,Q,X,M)!==0)return Q.stderr.write(M?"Reason: could not renew this computer's connection. Run `reason connect --api-key KEY` with a valid key.\n":"Reason: could not renew this computer's connection. Run `reason login`, then `reason connect`.\n"),0}let q=new AbortController;if(!X.runWorker)import("./ask-relay-qr4gmz44.js").then(({runBackgroundAskRelay:M})=>M(q.signal,(T)=>Q.stderr.write(`${T}
315
+ `),await i9(J0.parse({...N,executionMode:"host"}),K,Q,X,M)!==0)return Q.stderr.write(M?"Reason: could not renew this computer's connection. Run `reason connect --api-key KEY` with a valid key.\n":"Reason: could not renew this computer's connection. Run `reason login`, then `reason connect`.\n"),0}let q=new AbortController;if(!X.runWorker)import("./ask-relay-0j7e2qfb.js").then(({runBackgroundAskRelay:M})=>M(q.signal,(T)=>Q.stderr.write(`${T}
316
316
  `))).catch(()=>{});try{for(;;){let M=l0(N.stateDirectory)===null?{ownerWorkspaces:X.worker?.ownerWorkspaces??{}}:{},T=X.runWorker?null:$3({stateDirectory:N.stateDirectory}),_=!1,j;try{j=await(X.runWorker??M$)(["start","--config",K],{deferOptionalLanes:!0,...X.worker,...M,ownComputer:!0,io:{stdout:Q.stdout,stderr:Q.stderr},onDeviceRevoked:()=>{_=!0}})}finally{T?.stop()}if(!_)return j;if(!H("this computer's connection was removed from Reason",{keep:!1}))break}return U3(Z.home,Z.channel,!0),Q.stderr.write("Reason: this computer was removed from Reason. Run `reason connect` to connect it again.\n"),0}finally{q.abort()}}async function MB($,J,Z){let{io:Q,options:X,home:Y,channel:G,environment:V}=Z;if(J&&await(X.controlWorker??V0)(J,"status").catch(()=>null))throw new p("This computer is already connected in the background (see `reason status`). Run `reason disconnect` first to connect it only while a command runs.");let K=u0(Y,G,!0),N=A7({parsed:$,saved:J,stateDirectory:K,lifetime:"ephemeral",home:Y,channel:G,options:X,environment:V}),H=R7(N,Z.apiKey??(J?l0(J.stateDirectory)??void 0:void 0)),B=F0(K,"worker.json");return e(K,!0),c(B,H),Q.stdout.write(p9(`Reason: connecting "${H.name}" while this command runs`,H,Z.host.platform,["Connecting\u2026"])),(X.runWorker??M$)(["start","--config",B],{...n9(X.worker,Z.apiKey),ownComputer:!0,io:{stdout:Q.stdout,stderr:Y3(Q.stderr)},onStartup:(q)=>{if(q==="ready")Q.stdout.write(`Connected. Start Sessions on "${H.name}" from Reason. Press Ctrl-C to stop.
317
317
  `);X.worker?.onStartup?.(q)}})}function TB($,J,Z,Q){if(Z.platform!=="darwin")throw new p("--keep-awake is for macOS.");if(!J)throw new p("This computer is not connected to Reason. Run reason connect first.");e(g(J),!0),q8(d(J).daemon,$);let X=R2(d(J).daemon)==="battery_and_ac";return Q.stdout.write(`Keep awake: ${X?"on (this Mac stays awake while it runs Sessions)":"off"}
318
318
  `),0}var _B=U.object({root:U.object({id:U.string().min(1).max(160),label:U.string().max(160),path_fingerprint:U.string()})});async function I7($,J,Z,Q){let X=await(n9(Q.worker,Z).enrollmentCredentials??W$)($,j$($));if(!X)throw Error("worker_session_login_required");if(!X.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let Y=Q.folderApi?.(X)??new I$(X,{credentialsPath:j$($),fetchImpl:b0($.proxy)}),G=(V)=>V instanceof v0&&V.status===404&&!["device_not_found","root_not_found"].includes(V.code);return{add:async(V)=>{let K=W4($,V,{...J.roots[0].permissions,expose_mcp:!1}),N=await Y.addDeviceRoot(J.deviceId,{path_fingerprint:K.pathFingerprint,label:K.label,permissions:{...K.permissions,expose_mcp:!1}}).catch((B)=>{if(G(B))throw Error("worker_folders_unavailable");if(B instanceof v0&&B.code==="root_limit_reached")throw new p("This computer already has the most folders Reason allows (32).");throw B}),H=_B.parse(N).root;if(H.path_fingerprint!==K.pathFingerprint)throw Error("worker_enrollment_receipt_mismatch");return{...K,id:H.id,label:H.label}},remove:async(V)=>{await Y.removeDeviceRoot(J.deviceId,V).catch((K)=>{if(G(K))throw Error("worker_folders_unavailable");if(!(K instanceof v0&&K.code==="root_not_found"))throw K})}}}function C7($,J,Z){f0({...J,roots:Z,handsSlots:$.slots,worker:{...J.worker,configDigest:N0($)}},d($).state,{proofStore:T0($)})}async function P7($,J,Z,Q){let{io:X,options:Y,host:G}=Q,V=J&&!Q.apiKey&&l0(J.stateDirectory)===null?X2(Q.home,Q.channel,J):null,K=J&&V&&P$(J)&&!x1(J,V)?y0(J).find((I)=>I.account&&I.organizationId===V)??null:void 0;if(K===null)throw new p("This computer is not connected for your account. Run reason connect first.");let N=K?K.config:J,H=K?K.configPath:Z,B=N&&P$(N)&&!$0(N).revoked?o(N):null;if(!J||!N||!B||N.lifetime!=="persistent")throw new p("This computer is not connected to Reason. Run reason connect first.");let q=$.addFolder!==void 0,M=q?$.addFolder:$.removeFolder,T=Y.cwd??process.cwd(),_;try{_=X3(T,M)}catch(I){if(q)throw new p(I instanceof Error?I.message:String(I));_=GB(T,M)}if(_===N.workspaceRoot)throw new p(`${_} is this computer's main folder. To use another one, run reason connect --folder PATH.`);let j=N.folders??[],D=B.roots.slice(1).find((I)=>I.path===_);if(!q&&!D&&!j.includes(_))throw new p(`${_} is not one of this computer's folders.`);if(q&&!R1(_,N.stateDirectory))throw new p(`${_} holds Reason's own settings.`);if(q&&!D&&j.length>=31)throw new p("This computer already has the most folders Reason allows (32).");let O=Q.apiKey??l0(N.stateDirectory)??void 0,F=await I7(N,B,O,Y),z=B.roots.filter((I)=>I.path!==_);if(q)z=[...z,await F.add(_)];else if(D)await F.remove(D.id);C7(N,B,z);let L=q?[...j.filter((I)=>I!==_),_]:j.filter((I)=>I!==_),{folders:W,...R}=N;if(c(H,J0.parse({...R,...L.length?{folders:L}:{}})),!await(Y.controlWorker??V0)(J,"reload_roots").then(()=>!0,()=>!1))T$(J,G,"connect");return X.stdout.write(q?`Added ${_}. Sessions on "${N.name}" may run in it.
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Eh as e,Hh as p,Ih as c,Jh as QQ,zh as a}from"./vm-hands-entry-lite-1xjtcxpn.js";import{Oh as O}from"./vm-hands-entry-lite-9dx3at21.js";import{mi as Y}from"./vm-hands-entry-lite-2xh7sjs0.js";import{createHmac as EQ,createPublicKey as hQ,randomBytes as yQ,randomUUID as ZQ,verify as vQ}from"crypto";import{chmodSync as _,existsSync as $Q,mkdirSync as pQ,readFileSync as cQ,realpathSync as uQ,renameSync as dQ,statSync as lQ,unlinkSync as iQ,writeFileSync as sQ}from"fs";import{basename as nQ,dirname as R,isAbsolute as WQ,join as N,resolve as oQ}from"path";var GZ=[Object.freeze({family:"ara",channel:"stable",applicationId:"so.ara.desktop"}),Object.freeze({family:"ara",channel:"staging",applicationId:"so.ara.desktop.staging"}),Object.freeze({family:"reason",channel:"stable",applicationId:"com.reasonmachines.desktop"}),Object.freeze({family:"reason",channel:"staging",applicationId:"com.reasonmachines.desktop.staging"})];var wQ="REASON_DESKTOP_RUNTIME",xQ="REASON_DESKTOP_RUNTIME_CHANNEL",VQ="REASON_DESKTOP_RUNTIME_INSTANCE_ID",MQ="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",VZ={[wQ]:"ARA_DESKTOP_RUNTIME",[xQ]:"ARA_DESKTOP_RUNTIME_CHANNEL",[VQ]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[MQ]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function C(Q){if(Q===void 0)return;if(!/^[a-f0-9]{64}$/.test(Q))throw Error("Invalid desktop workspace scope.");return Q}import{chmodSync as f,existsSync as U,mkdirSync as B,readFileSync as E,realpathSync as KQ,renameSync as fQ,unlinkSync as k,writeFileSync as A}from"fs";import{createPrivateKey as BQ,createPublicKey as kQ,generateKeyPairSync as AQ,randomUUID as FQ,sign as TQ}from"crypto";import{createRequire as _Q}from"module";import{homedir as PQ,platform as u}from"os";import{dirname as RQ,join as H}from"path";import{existsSync as NQ}from"fs";import{join as m}from"path";var K="libara_device_keychain.dylib",I="libreason_device_keychain.dylib";class OQ extends Error{code;constructor(Q,Z){super(Z);this.code=Q;this.name="ManagedRuntimeError"}}function g(Q){let Z=m(Q,I);return NQ(Z)?Z:m(Q,K)}var h=1,DQ=16384,w=65536,bQ=128,SQ=128,d=65536;class X extends Error{code;nativeStatus;constructor(Q,Z){super(`Reason Device proof boundary failed (${Q}).${Z===void 0?"":` Native status: ${Z}.`}`);this.code=Q;this.nativeStatus=Z;this.name="LocalCredentialBoundaryError"}}function l(Q){if(Q.code==="proof_key_read_failed"&&Q.nativeStatus===-25300)return"proof_key_missing";switch(Q.nativeStatus){case-25308:return"keychain_interaction_required";case-25293:return"keychain_access_denied";case-25291:return"keychain_unavailable";default:return Q.code}}var F=null;function i(){if(!F)try{F=_Q(import.meta.url)("bun:ffi")}catch{throw new X("native_boundary_unavailable")}return F}function LQ(Q){if(typeof Q!=="string")return null;try{let Z=new URL(Q);if(Z.protocol!=="https:"&&Z.hostname!=="127.0.0.1"&&Z.hostname!=="localhost"&&Z.hostname!=="[::1]"&&Z.hostname!=="::1")return null;return Z.origin}catch{return null}}function CQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))throw new X("invalid_credential_record");let Z=Q,$=LQ(Z.apiOrigin);if(Z.version!==h||!$||typeof Z.orgId!=="string"||Z.orgId.length<1||Z.orgId.length>160||typeof Z.deviceId!=="string"||Z.deviceId.length<1||Z.deviceId.length>160||typeof Z.credential!=="string"||!/^(?:reason|ara)_dev_/.test(Z.credential)||Z.credential.length>4096)throw new X("invalid_credential_record");return{version:h,apiOrigin:$,orgId:Z.orgId,deviceId:Z.deviceId,credential:Z.credential}}function IQ(Q=process.execPath){let Z=Q;try{Z=KQ(Q)}catch{}return g(RQ(Z))}function z(Q){return i().ptr(Q)}function mQ(Q){if(!U(Q))throw new X("native_boundary_unavailable");let{dlopen:Z,FFIType:$}=i();try{return Z(Q,{ara_device_configure_scope:{args:[$.ptr,$.u64],returns:$.i32},ara_device_key_load_public:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_create_fresh_public:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_sign:{args:[$.ptr,$.u64,$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_is_non_extractable:{args:[$.ptr],returns:$.i32},ara_device_key_delete:{args:[$.ptr],returns:$.i32},ara_device_binding_read:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_binding_create:{args:[$.ptr,$.u64],returns:$.i32},ara_device_binding_update:{args:[$.ptr,$.u64],returns:$.i32},ara_device_binding_delete:{args:[$.ptr],returns:$.i32},ara_device_keychain_read:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_keychain_delete:{args:[$.ptr],returns:$.i32}})}catch(W){if(W instanceof X)throw W;throw new X("native_boundary_unavailable")}}function y(Q){return Buffer.from(Q).toString("base64url")}function x(Q){if(typeof Q!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(Q))return!1;try{let Z=Buffer.from(Q,"base64url");return Z.byteLength===65&&Z[0]===4}catch{return!1}}function s(Q){if(Q.byteLength<8||Q.byteLength>72||Q[0]!==48)return!1;let Z=Q[1];return Z!==void 0&&Z<128&&Z+2===Q.byteLength}class n{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(Q=IQ(),Z=u(),$){this.libraryPath=Q;this.runtimePlatform=Z;this.workspaceScope=$;C($)}symbols(){if(this.runtimePlatform!=="darwin")throw new X("unsupported_platform");this.library??=mQ(this.libraryPath);let Q=new TextEncoder().encode(this.workspaceScope??""),Z=this.library.symbols.ara_device_configure_scope(z(Q.length?Q:new Uint8Array(1)),BigInt(Q.length));if(Z!==0)throw new X("native_boundary_unavailable",Z);return this.library.symbols}publicKey(Q){let Z=new Uint8Array(bQ),$=new BigUint64Array(1),W=Q==="load"?this.symbols().ara_device_key_load_public(z(Z),BigInt(Z.byteLength),z($)):this.symbols().ara_device_key_create_fresh_public(z(Z),BigInt(Z.byteLength),z($));if(W!==0)throw new X(Q==="load"?"proof_key_read_failed":"proof_key_generation_failed",W);let j=Number($[0]);if(!Number.isSafeInteger(j)||j!==65)throw new X("invalid_public_key");let q=y(Z.subarray(0,j));if(!x(q))throw new X("invalid_public_key");return q}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(Q){if(Q.byteLength<1||Q.byteLength>d)throw new X("proof_sign_failed");let Z=new Uint8Array(SQ),$=new BigUint64Array(1),W=this.symbols().ara_device_key_sign(z(Q),BigInt(Q.byteLength),z(Z),BigInt(Z.byteLength),z($));if(W!==0)throw new X("proof_sign_failed",W);let j=Number($[0]);if(!Number.isSafeInteger(j)||j<1||j>Z.byteLength)throw new X("invalid_signature");let q=Z.subarray(0,j);if(!s(q))throw new X("invalid_signature");return y(q)}privateKeyIsNonExtractable(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_is_non_extractable(z(Q));if(Z!==0||Q[0]!==1)throw new X("proof_key_read_failed",Z);return!0}deleteKey(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_delete(z(Q));if(Z!==0)throw new X("proof_key_delete_failed",Z);return Q[0]===1}loadBinding(){let Q=new Uint8Array(w),Z=new BigUint64Array(1),$=this.symbols().ara_device_binding_read(z(Q),BigInt(Q.byteLength),z(Z));if($===1)return null;if($!==0)throw new X("binding_read_failed",$);let W=Number(Z[0]);if(!Number.isSafeInteger(W)||W<1||W>Q.byteLength)throw new X("invalid_binding");return Q.slice(0,W)}createBinding(Q){if(Q.byteLength<1||Q.byteLength>w)throw new X("invalid_binding");let Z=this.symbols().ara_device_binding_create(z(Q),BigInt(Q.byteLength));if(Z!==0)throw new X("binding_create_failed",Z)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>w)throw new X("invalid_binding");let Z=this.symbols().ara_device_binding_update(z(Q),BigInt(Q.byteLength));if(Z!==0)throw new X("binding_update_failed",Z)}deleteBinding(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_binding_delete(z(Q));if(Z!==0)throw new X("binding_delete_failed",Z);return Q[0]===1}loadLegacyCredential(){let Q=new Uint8Array(DQ),Z=new BigUint64Array(1),$=this.symbols().ara_device_keychain_read(z(Q),BigInt(Q.byteLength),z(Z));if($===1)return null;if($!==0)throw new X("legacy_credential_read_failed",$);let W=Number(Z[0]);if(!Number.isSafeInteger(W)||W<1||W>Q.byteLength)throw new X("invalid_credential_record");try{let j=new TextDecoder("utf-8",{fatal:!0}).decode(Q.subarray(0,W));return CQ(JSON.parse(j))}catch(j){if(j instanceof X)throw j;throw new X("invalid_credential_record")}}deleteLegacyCredential(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_keychain_delete(z(Q));if(Z!==0)throw new X("legacy_credential_delete_failed",Z);return Q[0]===1}}function v(Q){let Z=Q.export({format:"jwk"});if(Z.crv!=="P-256"||typeof Z.x!=="string"||typeof Z.y!=="string")throw new X("invalid_public_key");let $=Buffer.from(Z.x,"base64url"),W=Buffer.from(Z.y,"base64url");if($.byteLength!==32||W.byteLength!==32)throw new X("invalid_public_key");let j=Buffer.concat([Buffer.of(4),$,W]).toString("base64url");if(!x(j))throw new X("invalid_public_key");return j}function gQ(){let Q=process.env.XDG_CONFIG_HOME?.trim()||H(PQ(),".config");c(Q);let Z=H(Q,"ara");return p(Z)?Z:H(Q,"reason")}class o{directory;constructor(Q=gQ()){this.directory=Q}keyPath(){return H(this.directory,"local-device.key")}bindingPath(){return H(this.directory,"local-device.binding")}loadPrivateKeyObject(){let Q=this.keyPath();if(!U(Q))throw new X("proof_key_read_failed");try{let Z=E(Q,"utf8");return BQ({key:Z,format:"pem"})}catch{throw new X("proof_key_read_failed")}}loadPublicKey(){let Q=this.loadPrivateKeyObject(),Z=kQ(Q);return v(Z)}createFreshPublicKey(){B(this.directory,{recursive:!0,mode:448});let{privateKey:Q,publicKey:Z}=AQ("ec",{namedCurve:"P-256"}),$=Q.export({type:"pkcs8",format:"pem"}),W=this.keyPath();return A(W,$,{mode:384}),f(W,384),v(Z)}sign(Q){if(Q.byteLength<1||Q.byteLength>d)throw new X("proof_sign_failed");let Z=this.loadPrivateKeyObject(),$;try{$=TQ("sha256",Q,Z)}catch{throw new X("proof_sign_failed")}if(!s($))throw new X("invalid_signature");return $.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let Q=this.keyPath();if(!U(Q))return!1;return k(Q),!0}loadBinding(){let Q=this.bindingPath();if(!U(Q))return null;try{return new Uint8Array(E(Q))}catch{return null}}createBinding(Q){if(Q.byteLength<1||Q.byteLength>w)throw new X("invalid_binding");B(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(U(Z))throw new X("binding_create_failed");A(Z,Q,{mode:384}),f(Z,384)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>w)throw new X("invalid_binding");B(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(!U(Z))throw new X("binding_update_failed");let $=`${Z}.${FQ()}`;try{A($,Q,{mode:384,flag:"wx"}),f($,384),fQ($,Z)}finally{if(U($))k($)}}deleteBinding(){let Q=this.bindingPath();if(!U(Q))return!1;return k(Q),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function T(){return u()==="darwin"?new n:new o}var V=Y.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),r=Y.object({id:V,kind:Y.literal("permission_denied"),operation:Y.enum(["bash","read","write","edit"]),provenance:Y.enum(["sandbox_policy","os_permission_unknown"]),occurredAt:Y.string().datetime(),expiresAt:Y.string().datetime(),sessionId:V,deviceId:V,organizationId:V}).strict();var D=4;var M="macos-keychain-p256-v1",XQ=1,rQ=`ARA-DEVICE-BINDING-V1
2
+ import{Ah as e,Dh as p,Eh as c,Fh as QQ,vh as a}from"./vm-hands-entry-lite-6qfax5p2.js";import{Kh as O}from"./vm-hands-entry-lite-5b29hq7h.js";import{ii as Y}from"./vm-hands-entry-lite-k17ntg9v.js";import{createHmac as EQ,createPublicKey as hQ,randomBytes as yQ,randomUUID as ZQ,verify as vQ}from"crypto";import{chmodSync as _,existsSync as $Q,mkdirSync as pQ,readFileSync as cQ,realpathSync as uQ,renameSync as dQ,statSync as lQ,unlinkSync as iQ,writeFileSync as sQ}from"fs";import{basename as nQ,dirname as R,isAbsolute as WQ,join as N,resolve as oQ}from"path";var GZ=[Object.freeze({family:"ara",channel:"stable",applicationId:"so.ara.desktop"}),Object.freeze({family:"ara",channel:"staging",applicationId:"so.ara.desktop.staging"}),Object.freeze({family:"reason",channel:"stable",applicationId:"com.reasonmachines.desktop"}),Object.freeze({family:"reason",channel:"staging",applicationId:"com.reasonmachines.desktop.staging"})];var wQ="REASON_DESKTOP_RUNTIME",xQ="REASON_DESKTOP_RUNTIME_CHANNEL",VQ="REASON_DESKTOP_RUNTIME_INSTANCE_ID",MQ="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",VZ={[wQ]:"ARA_DESKTOP_RUNTIME",[xQ]:"ARA_DESKTOP_RUNTIME_CHANNEL",[VQ]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[MQ]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function C(Q){if(Q===void 0)return;if(!/^[a-f0-9]{64}$/.test(Q))throw Error("Invalid desktop workspace scope.");return Q}import{chmodSync as f,existsSync as U,mkdirSync as B,readFileSync as E,realpathSync as KQ,renameSync as fQ,unlinkSync as k,writeFileSync as A}from"fs";import{createPrivateKey as BQ,createPublicKey as kQ,generateKeyPairSync as AQ,randomUUID as FQ,sign as TQ}from"crypto";import{createRequire as _Q}from"module";import{homedir as PQ,platform as u}from"os";import{dirname as RQ,join as H}from"path";import{existsSync as NQ}from"fs";import{join as m}from"path";var K="libara_device_keychain.dylib",I="libreason_device_keychain.dylib";class OQ extends Error{code;constructor(Q,Z){super(Z);this.code=Q;this.name="ManagedRuntimeError"}}function g(Q){let Z=m(Q,I);return NQ(Z)?Z:m(Q,K)}var h=1,DQ=16384,w=65536,bQ=128,SQ=128,d=65536;class X extends Error{code;nativeStatus;constructor(Q,Z){super(`Reason Device proof boundary failed (${Q}).${Z===void 0?"":` Native status: ${Z}.`}`);this.code=Q;this.nativeStatus=Z;this.name="LocalCredentialBoundaryError"}}function l(Q){if(Q.code==="proof_key_read_failed"&&Q.nativeStatus===-25300)return"proof_key_missing";switch(Q.nativeStatus){case-25308:return"keychain_interaction_required";case-25293:return"keychain_access_denied";case-25291:return"keychain_unavailable";default:return Q.code}}var F=null;function i(){if(!F)try{F=_Q(import.meta.url)("bun:ffi")}catch{throw new X("native_boundary_unavailable")}return F}function LQ(Q){if(typeof Q!=="string")return null;try{let Z=new URL(Q);if(Z.protocol!=="https:"&&Z.hostname!=="127.0.0.1"&&Z.hostname!=="localhost"&&Z.hostname!=="[::1]"&&Z.hostname!=="::1")return null;return Z.origin}catch{return null}}function CQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))throw new X("invalid_credential_record");let Z=Q,$=LQ(Z.apiOrigin);if(Z.version!==h||!$||typeof Z.orgId!=="string"||Z.orgId.length<1||Z.orgId.length>160||typeof Z.deviceId!=="string"||Z.deviceId.length<1||Z.deviceId.length>160||typeof Z.credential!=="string"||!/^(?:reason|ara)_dev_/.test(Z.credential)||Z.credential.length>4096)throw new X("invalid_credential_record");return{version:h,apiOrigin:$,orgId:Z.orgId,deviceId:Z.deviceId,credential:Z.credential}}function IQ(Q=process.execPath){let Z=Q;try{Z=KQ(Q)}catch{}return g(RQ(Z))}function z(Q){return i().ptr(Q)}function mQ(Q){if(!U(Q))throw new X("native_boundary_unavailable");let{dlopen:Z,FFIType:$}=i();try{return Z(Q,{ara_device_configure_scope:{args:[$.ptr,$.u64],returns:$.i32},ara_device_key_load_public:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_create_fresh_public:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_sign:{args:[$.ptr,$.u64,$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_is_non_extractable:{args:[$.ptr],returns:$.i32},ara_device_key_delete:{args:[$.ptr],returns:$.i32},ara_device_binding_read:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_binding_create:{args:[$.ptr,$.u64],returns:$.i32},ara_device_binding_update:{args:[$.ptr,$.u64],returns:$.i32},ara_device_binding_delete:{args:[$.ptr],returns:$.i32},ara_device_keychain_read:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_keychain_delete:{args:[$.ptr],returns:$.i32}})}catch(W){if(W instanceof X)throw W;throw new X("native_boundary_unavailable")}}function y(Q){return Buffer.from(Q).toString("base64url")}function x(Q){if(typeof Q!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(Q))return!1;try{let Z=Buffer.from(Q,"base64url");return Z.byteLength===65&&Z[0]===4}catch{return!1}}function s(Q){if(Q.byteLength<8||Q.byteLength>72||Q[0]!==48)return!1;let Z=Q[1];return Z!==void 0&&Z<128&&Z+2===Q.byteLength}class n{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(Q=IQ(),Z=u(),$){this.libraryPath=Q;this.runtimePlatform=Z;this.workspaceScope=$;C($)}symbols(){if(this.runtimePlatform!=="darwin")throw new X("unsupported_platform");this.library??=mQ(this.libraryPath);let Q=new TextEncoder().encode(this.workspaceScope??""),Z=this.library.symbols.ara_device_configure_scope(z(Q.length?Q:new Uint8Array(1)),BigInt(Q.length));if(Z!==0)throw new X("native_boundary_unavailable",Z);return this.library.symbols}publicKey(Q){let Z=new Uint8Array(bQ),$=new BigUint64Array(1),W=Q==="load"?this.symbols().ara_device_key_load_public(z(Z),BigInt(Z.byteLength),z($)):this.symbols().ara_device_key_create_fresh_public(z(Z),BigInt(Z.byteLength),z($));if(W!==0)throw new X(Q==="load"?"proof_key_read_failed":"proof_key_generation_failed",W);let j=Number($[0]);if(!Number.isSafeInteger(j)||j!==65)throw new X("invalid_public_key");let q=y(Z.subarray(0,j));if(!x(q))throw new X("invalid_public_key");return q}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(Q){if(Q.byteLength<1||Q.byteLength>d)throw new X("proof_sign_failed");let Z=new Uint8Array(SQ),$=new BigUint64Array(1),W=this.symbols().ara_device_key_sign(z(Q),BigInt(Q.byteLength),z(Z),BigInt(Z.byteLength),z($));if(W!==0)throw new X("proof_sign_failed",W);let j=Number($[0]);if(!Number.isSafeInteger(j)||j<1||j>Z.byteLength)throw new X("invalid_signature");let q=Z.subarray(0,j);if(!s(q))throw new X("invalid_signature");return y(q)}privateKeyIsNonExtractable(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_is_non_extractable(z(Q));if(Z!==0||Q[0]!==1)throw new X("proof_key_read_failed",Z);return!0}deleteKey(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_delete(z(Q));if(Z!==0)throw new X("proof_key_delete_failed",Z);return Q[0]===1}loadBinding(){let Q=new Uint8Array(w),Z=new BigUint64Array(1),$=this.symbols().ara_device_binding_read(z(Q),BigInt(Q.byteLength),z(Z));if($===1)return null;if($!==0)throw new X("binding_read_failed",$);let W=Number(Z[0]);if(!Number.isSafeInteger(W)||W<1||W>Q.byteLength)throw new X("invalid_binding");return Q.slice(0,W)}createBinding(Q){if(Q.byteLength<1||Q.byteLength>w)throw new X("invalid_binding");let Z=this.symbols().ara_device_binding_create(z(Q),BigInt(Q.byteLength));if(Z!==0)throw new X("binding_create_failed",Z)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>w)throw new X("invalid_binding");let Z=this.symbols().ara_device_binding_update(z(Q),BigInt(Q.byteLength));if(Z!==0)throw new X("binding_update_failed",Z)}deleteBinding(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_binding_delete(z(Q));if(Z!==0)throw new X("binding_delete_failed",Z);return Q[0]===1}loadLegacyCredential(){let Q=new Uint8Array(DQ),Z=new BigUint64Array(1),$=this.symbols().ara_device_keychain_read(z(Q),BigInt(Q.byteLength),z(Z));if($===1)return null;if($!==0)throw new X("legacy_credential_read_failed",$);let W=Number(Z[0]);if(!Number.isSafeInteger(W)||W<1||W>Q.byteLength)throw new X("invalid_credential_record");try{let j=new TextDecoder("utf-8",{fatal:!0}).decode(Q.subarray(0,W));return CQ(JSON.parse(j))}catch(j){if(j instanceof X)throw j;throw new X("invalid_credential_record")}}deleteLegacyCredential(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_keychain_delete(z(Q));if(Z!==0)throw new X("legacy_credential_delete_failed",Z);return Q[0]===1}}function v(Q){let Z=Q.export({format:"jwk"});if(Z.crv!=="P-256"||typeof Z.x!=="string"||typeof Z.y!=="string")throw new X("invalid_public_key");let $=Buffer.from(Z.x,"base64url"),W=Buffer.from(Z.y,"base64url");if($.byteLength!==32||W.byteLength!==32)throw new X("invalid_public_key");let j=Buffer.concat([Buffer.of(4),$,W]).toString("base64url");if(!x(j))throw new X("invalid_public_key");return j}function gQ(){let Q=process.env.XDG_CONFIG_HOME?.trim()||H(PQ(),".config");c(Q);let Z=H(Q,"ara");return p(Z)?Z:H(Q,"reason")}class o{directory;constructor(Q=gQ()){this.directory=Q}keyPath(){return H(this.directory,"local-device.key")}bindingPath(){return H(this.directory,"local-device.binding")}loadPrivateKeyObject(){let Q=this.keyPath();if(!U(Q))throw new X("proof_key_read_failed");try{let Z=E(Q,"utf8");return BQ({key:Z,format:"pem"})}catch{throw new X("proof_key_read_failed")}}loadPublicKey(){let Q=this.loadPrivateKeyObject(),Z=kQ(Q);return v(Z)}createFreshPublicKey(){B(this.directory,{recursive:!0,mode:448});let{privateKey:Q,publicKey:Z}=AQ("ec",{namedCurve:"P-256"}),$=Q.export({type:"pkcs8",format:"pem"}),W=this.keyPath();return A(W,$,{mode:384}),f(W,384),v(Z)}sign(Q){if(Q.byteLength<1||Q.byteLength>d)throw new X("proof_sign_failed");let Z=this.loadPrivateKeyObject(),$;try{$=TQ("sha256",Q,Z)}catch{throw new X("proof_sign_failed")}if(!s($))throw new X("invalid_signature");return $.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let Q=this.keyPath();if(!U(Q))return!1;return k(Q),!0}loadBinding(){let Q=this.bindingPath();if(!U(Q))return null;try{return new Uint8Array(E(Q))}catch{return null}}createBinding(Q){if(Q.byteLength<1||Q.byteLength>w)throw new X("invalid_binding");B(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(U(Z))throw new X("binding_create_failed");A(Z,Q,{mode:384}),f(Z,384)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>w)throw new X("invalid_binding");B(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(!U(Z))throw new X("binding_update_failed");let $=`${Z}.${FQ()}`;try{A($,Q,{mode:384,flag:"wx"}),f($,384),fQ($,Z)}finally{if(U($))k($)}}deleteBinding(){let Q=this.bindingPath();if(!U(Q))return!1;return k(Q),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function T(){return u()==="darwin"?new n:new o}var V=Y.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),r=Y.object({id:V,kind:Y.literal("permission_denied"),operation:Y.enum(["bash","read","write","edit"]),provenance:Y.enum(["sandbox_policy","os_permission_unknown"]),occurredAt:Y.string().datetime(),expiresAt:Y.string().datetime(),sessionId:V,deviceId:V,organizationId:V}).strict();var D=4;var M="macos-keychain-p256-v1",XQ=1,rQ=`ARA-DEVICE-BINDING-V1
3
3
  `;function tQ(Q){return Q===void 0||typeof Q==="number"&&Number.isInteger(Q)&&Q>=1&&Q<=4}function jQ(Q,Z=Date.now()){let $=r.safeParse(Q);if(!$.success)return!1;let W=$.data,j=typeof W.occurredAt==="string"?Date.parse(W.occurredAt):NaN,q=typeof W.expiresAt==="string"?Date.parse(W.expiresAt):NaN;return W.kind==="permission_denied"&&["bash","read","write","edit"].includes(W.operation)&&["sandbox_policy","os_permission_unknown"].includes(W.provenance)&&Number.isFinite(j)&&j<=Z&&q>Z&&q>j&&q-j<=600000}function uZ(Q,Z,$=Date.now()){if(!Q||!Z||Q.state!=="connected"||Q.deviceId!==Z.deviceId)return null;let W=Date.parse(Q.lastHeartbeatAt??""),j=Q.permissionRecovery;if(!($-W>=0&&$-W<30000)||!jQ(j,$)||j.deviceId!==Z.deviceId||j.organizationId!==Z.orgId)return null;try{process.kill(Q.pid,0)}catch{return null}return j}function qQ(Q={},Z=O()){let $=a({env:{...process.env,...Q}}),W=Q.XDG_CONFIG_HOME?.trim()||N(Z,".config");return QQ(W,...$==="staging"?["staging"]:[])}function b(Q={},Z=O()){return N(qQ(Q,Z),"local-device.json")}function zQ(Q={},Z=O()){return N(qQ(Q,Z),"local-daemon.json")}function S(Q,Z){pQ(R(Q),{recursive:!0,mode:448}),_(R(Q),448);let $=`${Q}.${process.pid}.${ZQ()}.tmp`;try{sQ($,`${JSON.stringify(Z,null,2)}
4
4
  `,{mode:384,flag:"wx"}),_($,384),dQ($,Q),_(Q,384)}finally{if($Q($))iQ($)}return Q}function L(Q){if(!$Q(Q))return null;try{return JSON.parse(cQ(Q,"utf8"))}catch{return null}}function P(Q,Z,$){try{Q.onCredentialLifecycle?.({event:Z,...$?{reasonCode:$}:{}})}catch{}}function aQ(Q){if(!Array.isArray(Q))return null;let Z=[];for(let $ of Q){if(!$||typeof $!=="object")return null;let W=$;if(typeof W.id!=="string"||typeof W.label!=="string"||typeof W.path!=="string"||typeof W.pathFingerprint!=="string"||!W.permissions||typeof W.permissions.read!=="boolean"||typeof W.permissions.write!=="boolean"||typeof W.permissions.execute!=="boolean"||typeof W.permissions.discover_environment!=="boolean"||typeof W.permissions.expose_mcp!=="boolean")return null;Z.push({id:W.id,label:W.label,path:W.path,pathFingerprint:W.pathFingerprint,permissions:W.permissions})}return Z}function GQ(Q,Z,$=[]){let W=Object.keys(Q);return Z.every((j)=>Object.hasOwn(Q,j))&&W.every((j)=>Z.includes(j)||$.includes(j))}function eQ(Q){if(typeof Q!=="string")return null;try{let Z=new URL(Q);if(Z.protocol!=="https:"&&Z.hostname!=="127.0.0.1"&&Z.hostname!=="localhost")return null;return Z.origin}catch{return null}}function JQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let Z=Q,$=aQ(Z.roots),W=eQ(Z.apiOrigin);if(!W||typeof Z.orgId!=="string"||typeof Z.deviceId!=="string"||typeof Z.displayName!=="string"||typeof Z.registeredAt!=="string"||!tQ(Z.handsSlots)||Z.worker!==void 0&&(!Z.worker||!/^[a-f0-9]{64}$/.test(Z.worker.configDigest)||!["persistent","ephemeral"].includes(Z.worker.lifetime)||!Number.isFinite(Date.parse(Z.worker.expiresAt)))||!$)return null;return{apiOrigin:W,orgId:Z.orgId,deviceId:Z.deviceId,displayName:Z.displayName,registeredAt:Z.registeredAt,...Z.handsSlots!==void 0?{handsSlots:Z.handsSlots}:{},...Z.worker!==void 0?{worker:Z.worker}:{},roots:$}}function QZ(Q){return{...Q,credentialStorage:M}}function ZZ(Q){return{version:D,apiOrigin:Q.apiOrigin,orgId:Q.orgId,deviceId:Q.deviceId,devicePublicKey:Q.devicePublicKey,displayName:Q.displayName,registeredAt:Q.registeredAt,...Q.handsSlots!==void 0?{handsSlots:Q.handsSlots}:{},...Q.worker!==void 0?{worker:Q.worker}:{},roots:Q.roots.map((Z)=>({id:Z.id,label:Z.label,path:Z.path,pathFingerprint:Z.pathFingerprint,permissions:{read:Z.permissions.read,write:Z.permissions.write,execute:Z.permissions.execute,discover_environment:Z.permissions.discover_environment,expose_mcp:Z.permissions.expose_mcp}})),credentialStorage:M}}function UQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let Z=Q;if(!GQ(Z,["version","apiOrigin","orgId","deviceId","devicePublicKey","displayName","registeredAt","roots","credentialStorage"],["handsSlots","worker"]))return null;let $=JQ(Z);if(!$||Z.version!==D||Z.credentialStorage!==M||!x(Z.devicePublicKey))return null;return{version:D,...$,devicePublicKey:Z.devicePublicKey,credentialStorage:M}}function YQ(Q){return new TextEncoder().encode(`${rQ}${JSON.stringify(ZZ(Q))}`)}function $Z(Q){let Z=Buffer.from(Q,"base64url");return hQ({format:"jwk",key:{kty:"EC",crv:"P-256",x:Z.subarray(1,33).toString("base64url"),y:Z.subarray(33,65).toString("base64url")}})}function WZ(Q,Z){let $={version:XQ,state:Q,signature:Z.sign(YQ(Q))};return new TextEncoder().encode(JSON.stringify($))}function HQ(Q){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Q))}catch{throw new X("invalid_binding")}if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new X("invalid_binding");let $=Z;if(!GQ($,["version","state","signature"])||$.version!==XQ||typeof $.signature!=="string"||!/^[A-Za-z0-9_-]{10,128}$/.test($.signature))throw new X("invalid_binding");let W=UQ($.state);if(!W)throw new X("invalid_binding");let j=!1;try{j=vQ("sha256",YQ(W),$Z(W.devicePublicKey),Buffer.from($.signature,"base64url"))}catch{j=!1}if(!j)throw new X("invalid_binding");return W}function XZ(Q){let{credentialStorage:Z,...$}=Q;return $}function jZ(Q){return Q instanceof X?l(Q):"credential_boundary_failed"}function dZ(Q=b(),Z={}){let $=L(Q),W=Z.proofStore??Z.credentialStore??T(),j=W.loadBinding();if(!j){if($&&typeof $==="object"&&!Array.isArray($)&&qZ($))return null;if($!==null)throw new X("invalid_binding");return null}let q=HQ(j),G=W.loadPublicKey();if(W.privateKeyIsNonExtractable(),G!==q.devicePublicKey)throw new X("invalid_public_key");let J=UQ($);if(Z.repair!==!1&&(!J||JSON.stringify(J)!==JSON.stringify(q)))S(Q,q);return XZ(q)}function qZ(Q){let Z=Q,$=JQ(Q);if(!$)return null;if(Z.version===2){if(typeof Z.deviceCredential!=="string"||!/^(?:reason|ara)_dev_/.test(Z.deviceCredential)||Z.deviceCredential.length>4096)return null;return{state:$,credentialSource:"plaintext-v2"}}if(Z.version!==3||Z.credentialStorage!=="macos-keychain-v1"||"deviceCredential"in Z)return null;return{state:$,credentialSource:"keychain-v3"}}function lZ(Q,Z=b(),$={}){let W=$.proofStore??$.credentialStore??T();P($,"credential.store_started");try{if(!x(Q.devicePublicKey)||W.loadPublicKey()!==Q.devicePublicKey)throw new X("invalid_public_key");W.privateKeyIsNonExtractable();let j=QZ(Q),q=W.loadBinding();if(q){let J=HQ(q);if(J.devicePublicKey!==Q.devicePublicKey||J.orgId!==Q.orgId||J.deviceId!==Q.deviceId||J.apiOrigin!==Q.apiOrigin&&!e(J.apiOrigin,Q.apiOrigin))throw new X("invalid_binding")}let G=WZ(j,W);if(q)W.updateBinding(G);else W.createBinding(G);return S(Z,j),P($,"credential.store_completed"),Z}catch(j){throw P($,"credential.store_failed",jZ(j)),j}}function iZ(Q=zQ()){let Z=L(Q);if(!Z||typeof Z!=="object")return null;let $=Z;if($.version!==1||typeof $.pid!=="number"||!Number.isInteger($.pid)||!["starting","connected","stopped","error"].includes($.state??"")||typeof $.startedAt!=="string"||$.lastHeartbeatAt!==void 0&&typeof $.lastHeartbeatAt!=="string"||$.lastUsedAt!==void 0&&typeof $.lastUsedAt!=="string"||$.organizationId!==void 0&&typeof $.organizationId!=="string"||$.organizationName!==void 0&&typeof $.organizationName!=="string"||$.organizationSlug!==void 0&&typeof $.organizationSlug!=="string"||$.error!==void 0&&typeof $.error!=="string"||$.reconnectingSince!==void 0&&typeof $.reconnectingSince!=="string"||$.workspace!==void 0&&typeof $.workspace!=="string")return null;if($.permissionRecovery!==void 0&&!jQ($.permissionRecovery))delete $.permissionRecovery;return $}function sZ(Q,Z=zQ()){return S(Z,Q)}var t=1;function zZ(Q=b()){return N(R(Q),"local-device.proxy.json")}function nZ(Q=zZ()){let Z=L(Q);if(!Z||typeof Z!=="object"||Array.isArray(Z))return null;let $=Z;if($.version!==t||typeof $.url!=="string"||$.url.length===0||$.caFile!==void 0&&(typeof $.caFile!=="string"||!WQ($.caFile)))return null;return{version:t,url:$.url,...$.caFile?{caFile:$.caFile}:{}}}function oZ(Q,Z={read:!0,write:!1,execute:!1,discover_environment:!1,expose_mcp:!1},$=yQ(32)){let W=new Set,j=[];for(let q of Q){let G=uQ(WQ(q)?q:oQ(q));if(!lQ(G).isDirectory())throw Error(`Local execution root is not a directory: ${q}`);if(W.has(G))continue;W.add(G),j.push({id:ZQ(),label:nQ(G)||G,path:G,pathFingerprint:EQ("sha256",$).update(G).digest("hex"),permissions:{...Z}})}if(j.length===0)throw Error("At least one explicit local execution root is required.");return j}
5
- export{OQ as dg,X as eg,IQ as fg,x as gg,s as hg,n as ig,o as jg,jQ as kg,uZ as lg,b as mg,zQ as ng,dZ as og,lZ as pg,iZ as qg,sZ as rg,t as sg,nZ as tg,oZ as ug};
5
+ export{OQ as $f,X as ag,IQ as bg,x as cg,s as dg,n as eg,o as fg,jQ as gg,uZ as hg,b as ig,zQ as jg,dZ as kg,lZ as lg,iZ as mg,sZ as ng,t as og,nZ as pg,oZ as qg};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{$h as Z,Xh as X,Zh as Y}from"./vm-hands-entry-lite-289bc9v7.js";import{execFileSync as z}from"child_process";import{existsSync as V,realpathSync as M}from"fs";import{userInfo as D}from"os";import{isAbsolute as $,join as C,normalize as F,parse as K}from"path";function Q(){let q=F(D().homedir);if(!$(q)||q===K(q).root)throw Error("Could not resolve the canonical macOS user home.");return q}function O(q,B,J=Q()){let L=Z(B);if(B.kind==="managed"&&B.base){let G=M(J);return{anchor:G,boundary:C(G,B.base),path:C(G,L)}}if(B.kind==="root"&&Y(B.path)){let G=M(J);return{anchor:G,boundary:C(G,X),path:C(G,L)}}return{anchor:q,boundary:q,path:C(q,L)}}function _(q=Q()){return C(q,".config")}function b(){if(process.platform!=="darwin")return null;try{let q=z("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return $(q)?M(q):null}catch{return null}}function g(q=Q()){let B=C(q,"Library","Application Support","Ara"),J=C(q,"Library","Application Support","Reason");return V(B)&&!V(J)?B:J}
3
- export{Q as Oh,O as Ph,_ as Qh,b as Rh,g as Sh};
2
+ import{Th as X,Vh as Y,Xh as Z}from"./vm-hands-entry-lite-84d59wrf.js";import{execFileSync as z}from"child_process";import{existsSync as V,realpathSync as M}from"fs";import{userInfo as D}from"os";import{isAbsolute as $,join as C,normalize as F,parse as K}from"path";function Q(){let q=F(D().homedir);if(!$(q)||q===K(q).root)throw Error("Could not resolve the canonical macOS user home.");return q}function O(q,B,J=Q()){let L=Z(B);if(B.kind==="managed"&&B.base){let G=M(J);return{anchor:G,boundary:C(G,B.base),path:C(G,L)}}if(B.kind==="root"&&Y(B.path)){let G=M(J);return{anchor:G,boundary:C(G,X),path:C(G,L)}}return{anchor:q,boundary:q,path:C(q,L)}}function _(q=Q()){return C(q,".config")}function b(){if(process.platform!=="darwin")return null;try{let q=z("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return $(q)?M(q):null}catch{return null}}function g(q=Q()){let B=C(q,"Library","Application Support","Ara"),J=C(q,"Library","Application Support","Reason");return V(B)&&!V(J)?B:J}
3
+ export{Q as Kh,O as Lh,_ as Mh,b as Nh,g as Oh};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{ui as C}from"./vm-hands-entry-lite-gt5pkv4h.js";import{execFileSync as W}from"child_process";import{mkdirSync as b,readdirSync as R,readFileSync as F,rmSync as B,statSync as K,writeFileSync as f}from"fs";import{join as $}from"path";import{setTimeout as k}from"timers/promises";var A=3000,X=null;function G(z){return $(z,"users")}function m(z){if(X?.root===z.root)return;let H=G(z.root);b(H,{recursive:!0,mode:448}),f($(H,String(process.pid)),"",{mode:384}),X=z}function S(){if(!X)return;B($(G(X.root),String(process.pid)),{force:!0}),X=null}function x(z){try{return process.kill(z,0),!0}catch(H){return H instanceof Error&&"code"in H&&H.code==="EPERM"}}function L(){let z=process.getuid?.();if(process.platform==="linux")return R("/proc").flatMap((N)=>{if(!/^\d+$/.test(N))return[];try{if(K(`/proc/${N}`).uid!==z)return[];let Q=F(`/proc/${N}/cmdline`).toString("utf8").split("\x00").join(" ").trim();return Q?[{pid:Number(N),command:Q}]:[]}catch{return[]}});return W("/bin/ps",["-axww","-o","pid=,uid=,command="],{encoding:"utf8",maxBuffer:16777216}).split(`
2
+ import{qi as C}from"./vm-hands-entry-lite-tj1y61bg.js";import{execFileSync as W}from"child_process";import{mkdirSync as b,readdirSync as R,readFileSync as F,rmSync as B,statSync as K,writeFileSync as f}from"fs";import{join as $}from"path";import{setTimeout as k}from"timers/promises";var A=3000,X=null;function G(z){return $(z,"users")}function m(z){if(X?.root===z.root)return;let H=G(z.root);b(H,{recursive:!0,mode:448}),f($(H,String(process.pid)),"",{mode:384}),X=z}function S(){if(!X)return;B($(G(X.root),String(process.pid)),{force:!0}),X=null}function x(z){try{return process.kill(z,0),!0}catch(H){return H instanceof Error&&"code"in H&&H.code==="EPERM"}}function L(){let z=process.getuid?.();if(process.platform==="linux")return R("/proc").flatMap((N)=>{if(!/^\d+$/.test(N))return[];try{if(K(`/proc/${N}`).uid!==z)return[];let Q=F(`/proc/${N}/cmdline`).toString("utf8").split("\x00").join(" ").trim();return Q?[{pid:Number(N),command:Q}]:[]}catch{return[]}});return W("/bin/ps",["-axww","-o","pid=,uid=,command="],{encoding:"utf8",maxBuffer:16777216}).split(`
3
3
  `).flatMap((N)=>{let Q=/^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(N);return Q&&Number(Q[2])===z?[{pid:Number(Q[1]),command:Q[3]}]:[]})}async function p(){let z=X;if(!z)return{released:"unused",stopped:0};let H=G(z.root);B($(H,String(process.pid)),{force:!0}),X=null;let N=!1;for(let J of R(H)){let U=Number(J);if(Number.isSafeInteger(U)&&U>0&&x(U))N=!0;else B($(H,J),{force:!0})}if(N)return{released:"shared",stopped:0};let Q=L().filter((J)=>J.pid!==process.pid&&(J.command.includes(`${z.root}/`)||J.command.includes(`${z.automation}/`)||J.command.includes(z.extensionDir))),Y=(J,U)=>{try{process.kill(J,U)}catch{}};for(let J of Q)Y(J.pid,"SIGTERM");for(let J=Date.now()+A;Date.now()<J&&Q.some((U)=>x(U.pid));)await new Promise((U)=>setTimeout(U,100));for(let J of Q)if(x(J.pid))Y(J.pid,"SIGKILL");return{released:"stopped",stopped:Q.length}}var O=20000,j=30000,v=100,Z=new Map,V=null,q=[];function h(z){Z.set(z,(Z.get(z)??0)+1);let H=!1;return()=>{if(H)return;H=!0;let N=(Z.get(z)??1)-1;if(N>0){Z.set(z,N);return}if(Z.delete(z),V?.run===z)V.idleUntil=0}}function M(){return new C("automation_desktop_busy","Another Session, or another agent of this Session, is using this worker's desktop. Retry after it finishes.")}function P(z,H){return V!==null&&V.run!==z&&(V.calls>0||H<V.idleUntil)}async function I(z,H,N=Date.now){let Q=Symbol(z);q.push(Q);try{let U=N()+j;for(;;){if(!P(z,N())&&(V?.run===z||q[0]===Q))break;if(N()>=U)throw M();await k(v,void 0,{signal:H}).catch(()=>H.throwIfAborted())}}finally{q.splice(q.indexOf(Q),1)}if(V?.run!==z)V={run:z,calls:0,idleUntil:0};let Y=V;Y.calls+=1;let J=!1;return()=>{if(J)return;J=!0,Y.calls-=1,Y.idleUntil=N()+O}}
4
- export{m as ni,S as oi,p as pi,O as qi,j as ri,h as si,I as ti};
4
+ export{m as ji,S as ki,p as li,O as mi,j as ni,h as oi,I as pi};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var j={REASON_API_KEY:"ARA_API_KEY",REASON_API_URL:"ARA_API_URL",REASON_CLI_CHANNEL:"ARA_CLI_CHANNEL",REASON_CLI_LAUNCHER_PATH:"ARA_CLI_LAUNCHER_PATH",REASON_MANAGED_RUNTIME_ROOT:"ARA_MANAGED_RUNTIME_ROOT",REASON_INSTALL_ALIAS_PATH:"ARA_INSTALL_ALIAS_PATH",REASON_INSTALL_DIR:"ARA_INSTALL_DIR",REASON_INSTALL_METHOD:"ARA_INSTALL_METHOD",REASON_INSTALL_PINNED_VERSION:"ARA_INSTALL_PINNED_VERSION",REASON_INSTALL_UPGRADE:"ARA_INSTALL_UPGRADE"},mJ=Object.values(j),UJ=new Set;function m(J,Q){let V=J[Q];if(V?.trim())return V;let Z=J[j[Q]];if(Z?.trim())UJ.add(j[Q]);return Z}function DJ(J,Q){return{[J]:Q,[j[J]]:Q}}import{basename as PJ}from"path";var x=["production","staging"],GJ="https://api.reasonmachines.com",HJ="https://staging-api.reasonmachines.com";var f={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},RJ=new Set(["ara-staging","reason-staging"]);function lJ(J={}){let Q=m(J.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(Q){if(x.includes(Q))return Q;throw Error(`Unknown Reason CLI channel: ${Q}`)}let V=PJ(J.executablePath??process.execPath).toLowerCase();return RJ.has(V)?"staging":"production"}function I(J){return J==="staging"?HJ:GJ}function iJ(J){return`${I(J)}/mcp/ara`}var s={production:["https://api.ara.so",f.production.api],staging:["https://api-staging.ara.so",f.staging.api]};function y(J){let Q;try{Q=new URL(J).origin}catch{return J}let V=x.find((Z)=>s[Z].includes(Q));return V?I(V):Q}function rJ(J,Q){return J===Q||y(J)===y(Q)}function oJ(J,Q){return x.some((V)=>s[V].includes(J)&&Q===I(V))}function aJ(J,Q){try{let V=new URL(Q);return!V.username&&!V.password&&(V.origin===I(J)||V.origin===f[J].api)}catch{return!1}}function tJ(J){try{let Q=new URL(J).hostname.replace(/^\[|\]$/g,"").toLowerCase();return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}import{randomBytes as VJ}from"crypto";import{chmodSync as ZJ,closeSync as a,constants as FJ,linkSync as $J,lstatSync as A,mkdirSync as XJ,openSync as CJ,readdirSync as H,readFileSync as t,readlinkSync as E,renameSync as _,rmdirSync as KJ,symlinkSync as k,unlinkSync as U}from"fs";import{createRequire as OJ}from"module";import{constants as bJ}from"os";import{basename as O,join as K,sep as jJ}from"path";import{existsSync as N,lstatSync as l,readdirSync as EJ,readFileSync as TJ,readlinkSync as kJ,realpathSync as _J}from"fs";import{join as L,sep as AJ}from"path";function i(J,...Q){let V=L(J,"ara"),Z=L(J,"reason");if(!r(V))return L(Z,...Q);if(!N(Z))return L(V,...Q);return N(L(V,...Q))&&!N(L(Z,...Q))?L(V,...Q):L(Z,...Q)}function r(J){try{let Q=l(J);if(!Q.isSymbolicLink())return Q.isDirectory();return kJ(J)!=="reason"&&N(J)}catch{return!1}}function o(J,Q=[]){if(!r(J))return!1;let V;try{V=[J,...EJ(J,{withFileTypes:!0}).filter((Z)=>Z.isDirectory()).map((Z)=>L(J,Z.name))]}catch{return!1}return V.some((Z)=>["connect","connect-once"].filter(($)=>!Q.includes(L(Z,$))).some(($)=>{let z=L(Z,$,"worker.json");try{l(z)}catch{return!1}try{let q=JSON.parse(TJ(z,"utf8"))?.stateDirectory;if(typeof q!=="string")return!0;let M=(X,B)=>X===B||X.startsWith(B+AJ);return M(q,J)||M(c(q),c(J))}catch{return!0}}))}function c(J){try{return _J(J)}catch{return J}}var v=new Set(["credentials.json","local-device.json","local-device.revoked.json","local-device.auth-migration.json","local-device.json.registration-pending.json","local-daemon.json","local-daemon.json.workspaces.json","local-root-fingerprint-key.json","instances","workspaces"]),g=new Set(["local-device.proxy.json"]),IJ=new Set(["local-device.key","local-device.binding"]),n=new Map;function NJ(J,Q,V){let Z=K(J,"ara");if(/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(J))return{state:W(Z)?.isDirectory()?"kept":"absent"};return qJ(Z,K(J,"reason"),{linkAlways:!0,kept:($)=>o($,V??[]),native:Q===void 0?LJ:()=>Q},V!==void 0)}function YQ(J,...Q){return NJ(J),i(J,...Q)}function wQ(J,Q=process.platform){let V=K(J,"Library","Logs");if(Q==="darwin")for(let Z of[""," Staging"," Development"])qJ(K(V,`Ara${Z}`),K(V,`Reason${Z}`),{linkAlways:!1,kept:()=>!1,native:LJ});return K(V,"Reason")}var zJ="config_rename_unavailable:busy";function qJ(J,Q,V,Z=!1){let $=Z?void 0:n.get(J);if($)return $;let z;try{z=SJ(J,Q,V)}catch(q){let M=`config_rename_unavailable:${G(q)??"failed"}`;try{return{state:W(J)?.isDirectory()?"kept":"absent",problem:M}}catch{return{state:"kept",problem:M}}}if(!(z.state==="absent"&&V.linkAlways)&&z.problem!==zJ&&!(z.state==="kept"&&!z.problem))n.set(J,z);return z}function SJ(J,Q,V){vJ(Q,V.native);let Z=!1;for(let $=0;$<8;$+=1){let z=W(J);if(z?.isSymbolicLink())return E(J)===O(Q)?{state:Z?"renamed":"linked"}:{state:"kept"};if(!z){if(u(Q))Y(()=>U(Q),"ENOENT");if(!(Z||V.linkAlways)||!T(Q))return{state:"absent"};let X=C(Q,"link");k(O(Q),X);try{Y(()=>_(X,J),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{Y(()=>U(X),"ENOENT")}continue}if(!z.isDirectory())return{state:"absent"};if(V.kept(J))return e(Q),{state:"kept"};let q=V.native();if(!q)return e(Q),{state:"kept",problem:"config_rename_unavailable:no_native"};let M=fJ(q,J);if(!M)return{state:"kept",problem:zJ};try{if(A(J).isSymbolicLink())continue;let X=uJ(q,J,Q);if(X)return{state:"kept",problem:X};Z=!0}finally{M()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function uJ(J,Q,V){let Z=W(V);if(!Z||u(V)){if(!Z)k(O(V),V);try{J.exchange(Q,V)}catch(X){if(u(V))Y(()=>U(V),"ENOENT");return`config_rename_unavailable:${G(X)??"exchange_failed"}`}return null}if(!Z.isDirectory())return"config_rename_unavailable:ENOTDIR";if(Z.dev!==A(Q).dev)return"config_rename_unavailable:EXDEV";let $=[C(V,"probe"),C(V,"probe")];try{k("a",$[0]),k("b",$[1]),J.exchange($[0],$[1])}catch(X){return`config_rename_unavailable:${G(X)??"exchange_failed"}`}finally{for(let X of $)Y(()=>U(X),"ENOENT")}let z=wJ(V);for(let X of IJ){let B=W(K(V,X)),w=W(K(Q,X));if(B&&w&&B.ino!==w.ino)XJ(`${z}-replaced`,{mode:448,recursive:!0}),_(K(V,X),K(`${z}-replaced`,X))}let q={linked:new Map,unitsKept:new Set};MJ(Q,V,"",q);let M=C(V,"rename");k(O(V),M);try{J.exchange(Q,M)}catch(X){return Y(()=>U(M),"ENOENT"),`config_rename_unavailable:${G(X)??"exchange_failed"}`}return BJ(M,V,q,z),null}function h(J){return J===""||!J.includes(jJ)}function MJ(J,Q,V,Z){let $=h(V)&&S(K(Q,V),K(J,V));if($)Z.unitsKept.add(V);for(let z of H(K(J,V))){if($&&(v.has(z)||g.has(z)))continue;let q=K(V,z),M=K(J,q),X=K(Q,q),B=W(M);if(!B)continue;let w=W(X);if(B.isDirectory()){if(!w)Y(()=>XJ(X,{mode:B.mode&4095}),"EEXIST"),ZJ(X,B.mode&4095);if(T(X))MJ(J,Q,q,Z)}else if(!w){if(B.isSymbolicLink())Y(()=>k(E(M),X),"EEXIST");else if(Y(()=>$J(M,X),"EEXIST","ENOENT"))Z.linked.set(q,B.ino)}}}function vJ(J,Q){let V;try{if(!T(J))return;V=H(J)}catch{return}for(let Z of V){let $=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(Z);if(!$)continue;let z=K(J,Z),q=W(z);if(!q)continue;if(!q.isDirectory()){if(!JJ(Number($[2])))Y(()=>U(z),"ENOENT");continue}let M=Q(),X=null;if(M){try{X=M.lock(z)}catch{continue}if(!X)continue}else if(JJ(Number($[2])))continue;try{let B=C(J,"claim");if(Y(()=>_(z,B),"ENOENT"))BJ(B,J,null,wJ(J))}finally{X?.()}}}function BJ(J,Q,V,Z){for(let[$,z]of V?.linked??[])if(!W(K(J,$))&&W(K(Q,$))?.ino===z)Y(()=>U(K(Q,$)),"ENOENT");if(WJ(J,Q,"",V),Y(()=>KJ(J),"ENOTEMPTY","EEXIST"))return;_(J,Z),ZJ(Z,448)}function WJ(J,Q,V,Z){let $=h(V)&&(Z?Z.unitsKept.has(V):S(K(Q,V),K(J,V)));for(let z of H(K(J,V))){let q=K(V,z),M=K(J,q),X=K(Q,q),B=A(M),w=W(X);if(w&&B.ino===w.ino&&B.dev===w.dev){U(M);continue}if(B.isFile()&&w?.isFile()&&Z?.linked.get(q)===w.ino){_(M,X);continue}if($&&(v.has(z)||g.has(z)))continue;if(!w){if(B.isFile()){if(Y(()=>$J(M,X),"EEXIST"))U(M)}else Y(()=>_(M,X),"EEXIST","ENOTEMPTY");continue}if(B.isDirectory()&&w.isDirectory())WJ(J,Q,q,Z),Y(()=>KJ(M),"ENOTEMPTY","EEXIST")}}function LQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=["",...H(Q,{withFileTypes:!0}).filter(($)=>$.isDirectory()&&!$.name.startsWith(".")).map(($)=>$.name)];for(let $ of Z){let z=K(Q,$),q=K(V,$);if(!S(z,q)||!S(q,z))continue;if([...v,...g].some((X)=>d(K(z,X),K(q,X))===!1))return $}return null}function UQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=($)=>{for(let z of H(K(Q,$))){let q=K($,z);if(h($)&&(z==="connect"||z==="connect-once"))continue;let M=A(K(Q,q)),X=W(K(V,q));if(!X||M.ino===X.ino&&M.dev===X.dev)continue;if(M.isDirectory()&&X.isDirectory()&&!X.isSymbolicLink()){let B=Z(q);if(B!==null)return B}else if(M.isSymbolicLink()||X.isSymbolicLink()){if(!(M.isSymbolicLink()&&X.isSymbolicLink()&&E(K(Q,q))===E(K(V,q))))return q}else if(d(K(Q,q),K(V,q))!==!0)return q}return null};return Z("")}function d(J,Q){let V=W(J),Z=W(Q);if(!V&&!Z)return null;if(!V||!Z||V.isDirectory()!==Z.isDirectory())return!1;if(V.ino===Z.ino&&V.dev===Z.dev)return!0;if(V.isDirectory())return[...new Set([...H(J),...H(Q)])].every((z)=>d(K(J,z),K(Q,z))===!0);try{return t(J).equals(t(Q))}catch{return!1}}function S(J,Q){for(let V of v)if(YJ(K(J,V),K(Q,V)))return!0;return!1}function YJ(J,Q){let V=W(J);if(!V)return!1;let Z=W(Q);if(!Z)return!0;if(V.isDirectory()){if(!Z.isDirectory())return!0;return H(J).some(($)=>YJ(K(J,$),K(Q,$)))}if(V.isSymbolicLink())return!Z.isSymbolicLink()||E(J)!==E(Q);return V.ino!==Z.ino||V.dev!==Z.dev}function e(J){if(u(J))Y(()=>U(J),"ENOENT")}function wJ(J){return K(J,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${VJ(3).toString("hex")}`)}function u(J){try{return A(J).isSymbolicLink()&&E(J)===O(J)}catch{return!1}}function T(J){let Q=W(J);return Q!==null&&Q.isDirectory()}function fJ(J,Q){for(let V=0;V<40;V+=1){let Z=J.lock(Q);if(Z)return Z;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function C(J,Q){return K(J,`.${Q}-${process.pid}-${VJ(6).toString("hex")}`)}function JJ(J){if(J===process.pid)return!1;try{return process.kill(J,0),!0}catch(Q){return G(Q)==="EPERM"}}function W(J){try{return A(J)}catch(Q){if(G(Q)==="ENOENT"||G(Q)==="ENOTDIR")return null;throw Q}}function Y(J,...Q){try{return J(),!0}catch(V){if(Q.includes(G(V)??""))return!1;throw V}}function G(J){return J instanceof Error&&"code"in J&&typeof J.code==="string"?J.code:void 0}var F,xJ=2,gJ=4,hJ=2,dJ=2,QJ=-100;function LJ(){if(F!==void 0)return F;if(F=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let J;try{J=OJ(import.meta.url)("bun:ffi")}catch{return null}let Q=process.platform==="darwin",V=Q?"__error":"__errno_location",Z=Q?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:$}=J;for(let z of Z)try{let q=Q?"renamex_np":"renameat2",X=J.dlopen(z,{flock:{args:[$.i32,$.i32],returns:$.i32},[V]:{args:[],returns:$.ptr},[q]:Q?{args:[$.ptr,$.ptr,$.u32],returns:$.i32}:{args:[$.i32,$.ptr,$.i32,$.ptr,$.u32],returns:$.i32}}).symbols,B=X[V]();if(B===null)continue;let w=(R)=>{let P=J.read.i32(B),D=Object.entries(bJ.errno).find(([,b])=>b===P)?.[0]??`errno_${P}`;return Object.assign(Error(`${R} failed: ${D}`),{code:D})},p=(R)=>Buffer.from(`${R}\x00`,"utf8");return F={exchange(R,P){let D=p(R),b=p(P);if((Q?X[q](J.ptr(D),J.ptr(b),hJ):X[q](QJ,J.ptr(D),QJ,J.ptr(b),dJ))!==0)throw w("exchange")},lock(R){let P=CJ(R,FJ.O_RDONLY);if(X.flock(P,xJ|gJ)===0)return()=>a(P);let D=w("lock");if(a(P),D.code==="EWOULDBLOCK"||D.code==="EAGAIN")return null;throw D}},F}catch{}return null}
3
- export{m as wh,DJ as xh,x as yh,lJ as zh,I as Ah,iJ as Bh,y as Ch,rJ as Dh,oJ as Eh,aJ as Fh,tJ as Gh,r as Hh,NJ as Ih,YQ as Jh,wQ as Kh,LQ as Lh,UQ as Mh,LJ as Nh};
3
+ export{m as sh,DJ as th,x as uh,lJ as vh,I as wh,iJ as xh,y as yh,rJ as zh,oJ as Ah,aJ as Bh,tJ as Ch,r as Dh,NJ as Eh,YQ as Fh,wQ as Gh,LQ as Hh,UQ as Ih,LJ as Jh};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var U=".reason/workspace",T="workspace_base",y="sessions",W="workspace_layout",g=".reason/workspace/sessions",B=/^[0-9a-f]{8}$/;function C(j){if(!J(j))return!1;let q=".reason/workspace/sessions/";if(!j.startsWith(q))return!1;let z=j.slice(q.length).split("/");return z.length===2&&B.test(z[0])}var G=4096,X="workspaces/pi";function J(j){if(typeof j!=="string"||!j||j.length>G)return!1;if(j.startsWith("/")||j.includes("\x00")||j.includes("\\"))return!1;return j.split("/").every((q)=>q!==""&&q!=="."&&q!=="..")}function Z(j){if(j.kind==="root"){if(j.path===void 0)return".";if(!J(j.path))throw Error("invalid_device_workspace_identity");return j.path}if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/.test(j.workspaceId)||j.workspaceId==="."||j.workspaceId==="..")throw Error("invalid_device_workspace_identity");let q=j.layout==="sessions"?"sessions":X;return`${j.base?`${j.base}/`:""}${q}/${j.workspaceId}/repo`}function L(j){if(!j||typeof j!=="object"||Array.isArray(j))return null;let q=j;if(q.kind==="root"&&Object.keys(q).length===1)return{kind:"root"};if(q.kind==="root"&&Object.keys(q).length===2&&J(q.path))return{kind:"root",path:q.path};if(q.kind!=="managed"||typeof q.workspaceId!=="string"||Object.keys(q).length!==2+(q.base===void 0?0:1)+(q.layout===void 0?0:1)||q.base!==void 0&&q.base!==".reason/workspace"||q.layout!==void 0&&q.layout!=="sessions")return null;let z={kind:"managed",workspaceId:q.workspaceId,...q.base===".reason/workspace"?{base:".reason/workspace"}:{},...q.layout==="sessions"?{layout:"sessions"}:{}};try{return Z(z),z}catch{return null}}var b="/home/runner",P=10001,x="/run/reason/sessions",f=/^(?:\/[A-Za-z0-9._-]+)+$/,M=/-sidechat-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/,H=/^(.+)-repository-[a-z0-9][a-z0-9._-]*-[0-9a-f]{12}$/;function K(j){return M.exec(j)?.[1]??H.exec(j)?.[1]??j}var $=/^((?:\/[A-Za-z0-9._-]+)+)\/\.reason\/workspace\/(workspaces\/pi|sessions)\/([^/]+)$/,A="*/.reason/workspace/workspaces/pi/*|*/.reason/workspace/sessions/*";function N(j,q=b,z="sessions"){if(!f.test(q)||q.split("/").some((V)=>V==="."||V===".."))throw Error("invalid_cloud_payload_home");let Q=`${q}/${Z({kind:"managed",workspaceId:j,base:".reason/workspace",...z?{layout:z}:{}})}`,F=`${x}/${K(j)}`;return{home:q,root:Q.slice(0,-5),checkout:Q,control:F,jobEnv:`${F}/job.env`,cloudAccess:`${F}/cloud-access`,logs:`${F}/logs`,pin:`${F}/ws`}}function Y(j){return $.exec(j.replace(/\/+$/,""))?.[2]==="sessions"?"sessions":null}function D(j){return{kind:"managed",workspaceId:j,layout:"sessions"}}function R(j){let q=$.exec(j.replace(/\/+$/,""));if(!q)return null;try{let z=N(q[3],q[1],Y(j));return z.root===j.replace(/\/+$/,"")?z:null}catch{return null}}
3
- export{U as Th,T as Uh,y as Vh,W as Wh,g as Xh,B as Yh,C as Zh,J as _h,Z as $h,L as ai,b as bi,P as ci,x as di,M as ei,H as fi,$ as gi,A as hi,N as ii,Y as ji,D as ki,R as li};
3
+ export{U as Ph,T as Qh,y as Rh,W as Sh,g as Th,B as Uh,C as Vh,J as Wh,Z as Xh,L as Yh,b as Zh,P as _h,x as $h,M as ai,H as bi,$ as ci,A as di,N as ei,Y as fi,D as gi,R as hi};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{ge as xe}from"./vm-hands-entry-lite-36xzwsxn.js";import{Ee as W,Fe as oe,He as _t,Ie as Ne,Le as St,Me as wt,Ne as $,We as z,Xe as Je}from"./vm-hands-entry-lite-wgjqxtxj.js";import{af as Se}from"./vm-hands-entry-lite-pa111vpq.js";import{cf as Jt,ff as xt,if as Z,kf as zt,lf as ae}from"./vm-hands-entry-lite-449p9dx7.js";import{Pf as Ae,Qf as se}from"./vm-hands-entry-lite-yeahy7rk.js";import{Ih as Ot,wh as v,yh as tt,zh as D}from"./vm-hands-entry-lite-1xjtcxpn.js";import{Oh as q}from"./vm-hands-entry-lite-9dx3at21.js";import{ni as pe,ti as ye}from"./vm-hands-entry-lite-0jar357h.js";import{ui as _}from"./vm-hands-entry-lite-gt5pkv4h.js";import{spawn as I}from"child_process";import{randomUUID as Oe}from"crypto";import{closeSync as Vr,copyFileSync as de,existsSync as ut,fstatSync as Er,mkdirSync as fe,openSync as vr,readdirSync as V,readFileSync as ge,readlinkSync as to,renameSync as eo,rmSync as ro,statSync as oo}from"fs";import{connect as so}from"net";import{userInfo as Te}from"os";import{basename as le,dirname as mt,join as b}from"path";var At=`import { spawn, execFileSync } from "node:child_process";
2
+ import{ce as xe}from"./vm-hands-entry-lite-qf01e5f1.js";import{Ae as W,Be as oe,De as _t,Ee as Ne,He as St,Ie as wt,Je as $,Se as z,Te as Je}from"./vm-hands-entry-lite-pztap0be.js";import{Ye as Se}from"./vm-hands-entry-lite-xhjbc3e4.js";import{_e as Jt,bf as xt,ef as Z,gf as zt,hf as ae}from"./vm-hands-entry-lite-gkd1gkfc.js";import{Lf as Ae,Mf as se}from"./vm-hands-entry-lite-c9wp99nr.js";import{Eh as Ot,sh as v,uh as tt,vh as D}from"./vm-hands-entry-lite-6qfax5p2.js";import{Kh as q}from"./vm-hands-entry-lite-5b29hq7h.js";import{ji as pe,pi as ye}from"./vm-hands-entry-lite-6f5eypjm.js";import{qi as _}from"./vm-hands-entry-lite-tj1y61bg.js";import{spawn as I}from"child_process";import{randomUUID as Oe}from"crypto";import{closeSync as Vr,copyFileSync as de,existsSync as ut,fstatSync as Er,mkdirSync as fe,openSync as vr,readdirSync as V,readFileSync as ge,readlinkSync as to,renameSync as eo,rmSync as ro,statSync as oo}from"fs";import{connect as so}from"net";import{userInfo as Te}from"os";import{basename as le,dirname as mt,join as b}from"path";var At=`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";
@@ -757,4 +757,4 @@ WantedBy=default.target
757
757
  `),1;if(t.length===1&&t[0]==="doctor"){let i=await(e.grants??Ae)(o);if(!i)return r.write(`Reason computer use: Reason's permissions could not be read (computer_use_permission_status_unavailable)
758
758
  `),1;return(e.stdout??process.stdout).write(wo(i)),0}if(t.length!==1||t[0]!=="mcp")return r.write(`Usage: reason __computer-use mcp|doctor
759
759
  `),2;let[a,...c]=o;return(e.run??xo)(a,[...c,s.ocu,"mcp"],{...process.env,OPEN_COMPUTER_USE_DISABLE_APP_AGENT_PROXY:"1"})}function Ks(t=$){return t()?.userChrome??{code:"user_chrome_browser_use_missing"}}function Ce(t,e,r,o){return new Promise((s)=>{let a=I(t,e,{env:r,stdio:"ignore"}),c=setTimeout(()=>{a.kill("SIGKILL"),s(-1)},o);a.once("error",()=>{clearTimeout(c),s(-1)}),a.once("exit",(i)=>{clearTimeout(c),s(i??-1)})})}function So(t,e,r,o){return new Promise((s)=>{let a=I(t,e,{env:r,stdio:["ignore","pipe","ignore"]}),c="";a.stdout.setEncoding("utf8").on("data",(d)=>{c+=d});let i=setTimeout(()=>{a.kill("SIGKILL"),s(null)},o);a.once("error",()=>{clearTimeout(i),s(null)}),a.once("close",(d)=>{clearTimeout(i),s(d===0?c:null)})})}var po="/tmp/open-browser-use",yo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ao=33554432;function No(t,e){let r;try{r=t===null?null:JSON.parse(t)}catch{return null}let o=H(r)&&H(r.result)?r.result.metadata:null;if(!H(o)||o.extensionId!==e)return null;return typeof o.extensionInstanceId==="string"&&yo.test(o.extensionInstanceId)?o.extensionInstanceId:null}async function Be(t,e,r){let o=r.storages.map((i)=>{try{return V(i).filter((d)=>d.endsWith(".log")||d.endsWith(".ldb")).map((d)=>b(i,d))}catch{return[]}}),s;try{s=o.some((i)=>i.length>0)?V(r.socketDir).filter((i)=>i.endsWith(".sock")):[]}catch{return[]}let a=[];for(let i of s){let d=b(r.socketDir,i),f=No(await So(t,["info","--socket",d,"--timeout","2s"],e,5000),r.extensionId);if(f)a.push({instance:f,socket:d})}let c=[];for(let[i,d]of(a.length>0?o:[]).entries())for(let f of d)try{if(oo(f).size>Ao)continue;let n=ge(f),l=a.find((u)=>n.includes(u.instance));if(l){c.push({storage:r.storages[i],...l});break}}catch{}return c}async function Oo(t,e,r){return(await Be(t,e,r))[0]?.instance??null}function Ie(t,e,r){return Oo(t,e,{socketDir:po,extensionId:_t,storages:[b(r,"browser-profile","Default","Local Extension Settings",_t)]})}var ue=/^(Default|Profile ([0-9]+))$/;async function go(t,e,r=q(),o=St){let s=b(r,"Library","Application Support","Google","Chrome"),a=[];try{a=V(s)}catch(n){if(n.code==="EPERM")throw new _("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 c=(n)=>Number(ue.exec(n)?.[2]??-1),i=a.filter((n)=>ue.test(n)&&ut(b(s,n,"Extensions",W))).sort((n,l)=>c(n)-c(l)),d=(n)=>b(s,n,"Local Extension Settings",W);return(await Be(t,e,{socketDir:o,extensionId:W,storages:i.map(d)})).map(({storage:n,instance:l,socket:u})=>({profile:i.find((m)=>d(m)===n),instance:l,socket:u}))}async function To(t,e,r=q(),o=St){let s=(await go(t,e,r,o))[0]?.instance;if(!s)throw new _("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 me(t){return new Promise((e)=>{let r=so({path:t}),o=(s)=>{r.destroy(),e(s)};r.setTimeout(1000,()=>o(!1)),r.once("error",()=>o(!1)),r.once("connect",()=>o(!0))})}async function $e(t,e){let r=Date.now()+e;while(Date.now()<r){if(await t())return!0;await new Promise((o)=>setTimeout(o,200))}return!1}var ft=new Map;function lt(t,e){let r=ft.get(t);if(!r)r=e().finally(()=>ft.delete(t)),ft.set(t,r);return r}async function qo(t,e){if(await me(t))return;if(ro(t,{force:!0}),await Ce("dbus-daemon",["--session",`--address=unix:path=${t}`,"--fork"],e,1e4)!==0||!await $e(()=>me(t),5000))throw new _("automation_unavailable","Reason could not start the desktop session bus.")}async function be(t,e,r){let o=t.platform==="darwin-arm64"?async()=>await Ie(t.nativeHost,e,r)!==null:async()=>await Ce(t.nativeHost,["info"],e,5000)===0;if(await o())return;let s=["--profile-directory=Default",`--load-extension=${t.extensionDir}`,"--no-first-run","--no-default-browser-check","--window-size=1280,800","about:blank"],a,c=null,i=0;if(t.platform==="darwin-arm64"){let n=b(r,"browser-profile");z(n);let l=b(n,"NativeMessagingHosts");fe(l,{recursive:!0,mode:448});let u=wt(t.platform).nativeHostManifests[0];de(u,b(l,le(u)));let m=t.browser.slice(0,t.browser.indexOf(".app/")+4),S=s.filter((B)=>B!=="about:blank").concat("--no-startup-window","--use-mock-keychain");a=I("/usr/bin/open",["-g","-n","-a",m,"--args",`--user-data-dir=${n}`,...S],{env:e,stdio:"ignore"})}else{let n=b(e.HOME,".config","google-chrome"),l=b(n,"NativeMessagingHosts");fe(l,{recursive:!0,mode:448});let u=wt(t.platform).nativeHostManifests[0];de(u,b(l,le(u)));let m=process.geteuid?.()===0?["--no-sandbox"]:[];c=b(r,"browser.log");let S=vr(c,"a",384);i=Er(S).size,a=I(t.browser,[`--user-data-dir=${n}`,...s,...m,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",S,S],env:{...e,ACCESSIBILITY_ENABLED:"1"}}),Vr(S)}let d=!1;a.once("error",()=>{d=!0}),a.once("exit",(n)=>{d||=n!==0}),a.unref();let f=!1;if(await $e(async()=>d||(f=await o()),_o),!f){if(c&&ge(c).subarray(i).toString("utf8").includes("No usable sandbox"))throw new _("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 _("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function Vs(t){await Ge(t,!0)}function Es(t){return Fe(t,Re(t))}function Fe(t,e){return t.platform==="darwin-arm64"?b(e,"browser-profile"):b(e,"home",".config","google-chrome")}function Re(t){let e=b(t.root,"automation");if(!ut(e)||!Co(t.automation))return t.automation;if(!Bo(Fe(t,e)))try{eo(e,t.automation)}catch{}return ut(e)?e:t.automation}function Co(t){try{return V(t).length===0}catch(e){return e.code==="ENOENT"}}function Bo(t){let e;try{e=to(b(t,"SingletonLock"))}catch{return!1}let r=Number(e.slice(e.lastIndexOf("-")+1));if(!Number.isSafeInteger(r)||r<=0)return!0;try{return process.kill(r,0),!0}catch(o){return o.code==="EPERM"}}async function Ge(t,e){pe({root:t.root,automation:t.automation,extensionDir:t.extensionDir});let r=Re(t);z(r);let o=Te().username,s={USER:o,LOGNAME:o,REASON_AUTOMATION_OCU:t.ocu,REASON_AUTOMATION_OBU:t.nativeHost};if(t.platform==="darwin-arm64"){let n={...s,HOME:q(),PATH:`${mt(t.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:bo};if(!e)return n;await lt("browser",()=>be(t,n,r));let l=await Ie(t.nativeHost,n,r);if(!l)throw new _("automation_browser_unavailable","Reason could not connect the desktop browser.");return{...n,REASON_AUTOMATION_OBU_INSTANCE:l,REASON_AUTOMATION_BACKGROUND_TABS:"1"}}let a=await Je(),c=b(r,"home"),i=b(r,"runtime");z(c),z(i);let d=b(r,"bus"),f={...s,HOME:c,PATH:`${mt(t.node)}:/usr/bin:/bin`,DISPLAY:a.display,XAUTHORITY:a.xauthority,XDG_RUNTIME_DIR:i,DBUS_SESSION_BUS_ADDRESS:`unix:path=${d}`,...a.sound?{PULSE_SERVER:Ne(a.sound)}:{}};if(await lt("bus",()=>qo(d,f)),e)await lt("browser",()=>be(t,f,r));return f}async function Io(t,e,r){let o=Te().username,s={USER:o,LOGNAME:o,HOME:q(),PATH:`${mt(t.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OBU:e,REASON_AUTOMATION_BACKGROUND_TABS:"1"},a=await To(e,s);return r.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:a}}function Ue(t,e,r,o){if(typeof _e!=="string")return Promise.reject(new _("automation_unavailable","This Reason build has no automation runtime."));let s=_e;return new Promise((a,c)=>{let i=I(t,["--input-type=module","--eval",s],{env:{...e,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:!0}),d=[],f=0,n="",l=null,u=!1,m=(w)=>{l??=w;try{process.kill(-i.pid,"SIGKILL")}catch{i.kill("SIGKILL")}},S=(w)=>{if(u)return;u=!0,clearTimeout(B),o.removeEventListener("abort",g),w()},B=setTimeout(()=>m(new _("automation_timed_out","Reason automation did not finish in time.")),no),g=()=>m(new _("cancelled","Reason cancelled the automation call."));if(o.addEventListener("abort",g,{once:!0}),i.stdout.on("data",(w)=>{if(f+=w.byteLength,f>ao)m(new _("automation_output_too_large","Reason automation output is too large."));else d.push(w)}),i.stderr.setEncoding("utf8").on("data",(w)=>{n=(n+w).slice(-io)}),i.stdin.on("error",()=>{}),i.once("error",()=>S(()=>c(l??new _("automation_unavailable","Reason could not start the automation runtime.")))),i.once("close",(w)=>S(()=>{if(l)c(l);else a({code:w??1,stdout:Buffer.concat(d),stderr:n})})),o.aborted)g();i.stdin.end(r)})}var C=new Map;function $o(t,e,r){for(let[s,a]of C)if(a.expiresAt<=r)C.delete(s);while(C.size>=lo)C.delete(C.keys().next().value);let o=Oe();return C.set(o,{runId:t,bytes:e,expiresAt:r+fo}),o}async function Le(t,e,r,o={}){let s=await(o.environment??Ge)(t,e.kind==="browser");return r.throwIfAborted(),await(o.runtime??Ue)(t.node,s,JSON.stringify(e),r)}async function vs(t,e){let r=qe({call:t});if(!("call"in r))K();let o=$();if(!o?.features.computer||r.call.kind==="browser"&&!o.features.browser)throw new _("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");return await Le(o,r.call,e)}function we(t,e,r){let o=t.stdout.byteLength>bt?$o(e,t.stdout,r):void 0;return{code:t.code,stderr:t.stderr,instance_id:mo,output_bytes:t.stdout.byteLength,chunk:t.stdout.subarray(0,bt).toString("base64"),...o?{output_id:o}:{}}}async function ta(t,e={}){let r=qe(t.payload),o=(e.now??Date.now)();if("output_id"in r){let m=C.get(r.output_id);if(!m||m.runId!==t.runId||m.expiresAt<=o||r.offset>m.bytes.byteLength)throw new _("automation_output_unavailable","Reason automation output expired.");return{chunk:m.bytes.subarray(r.offset,r.offset+bt).toString("base64")}}let s=(e.components??$)(),a=(e.platform??process.platform)==="darwin",c=a?(e.macIdentity??xt)():[],i=e.macSetup??X,d=!s?.features.computer||r.call.kind==="browser"&&!r.userChrome&&!s.features.browser;if(a&&(d||c.length===0||r.call.kind==="browser"&&r.userChrome&&!t.userChrome))return we(await ce({runId:t.runId,call:r.call,identity:c,desktopMissing:d,signal:t.signal},i),t.runId,o);if(!s?.features.computer)throw new _("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let f=r.userChrome?t.userChrome:void 0;if(r.userChrome&&!f)throw new _("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(r.call.kind==="browser"&&!f&&!s.features.browser)throw new _("automation_browser_not_installed",s.platform==="darwin-arm64"?"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`.");t.signal.throwIfAborted();let n=await ye(t.runId,t.signal,e.now),l="account"in e?e.account??null:Se(),u;try{if(f){let m=await(e.userChromeEnvironment??Io)(s,f,t.signal);t.signal.throwIfAborted(),u=await(e.runtime??Ue)(s.node,m,JSON.stringify(r.call),t.signal)}else if(l)u=await(e.delegate??Nt)(l,r.call,t.signal);else u=await Le(s,r.call,t.signal,e)}finally{n()}if(a)u=await ne({runId:t.runId,call:r.call,identity:c,output:u,signal:t.signal},i);return we(u,t.runId,o)}
760
- export{Ut as Kc,at as Lc,Dt as Mc,A as Nc,Mt as Oc,cs as Pc,kt as Qc,ns as Rc,dt as Sc,Ur as Tc,ds as Uc,fs as Vc,ls as Wc,_s as Xc,us as Yc,ms as Zc,We as _c,bt as $c,qe as ad,Ws as bd,xo as cd,Hs as dd,Ks as ed,go as fd,To as gd,Vs as hd,Es as id,vs as jd,ta as kd};
760
+ export{Ut as Gc,at as Hc,Dt as Ic,A as Jc,Mt as Kc,cs as Lc,kt as Mc,ns as Nc,dt as Oc,Ur as Pc,ds as Qc,fs as Rc,ls as Sc,_s as Tc,us as Uc,ms as Vc,We as Wc,bt as Xc,qe as Yc,Ws as Zc,xo as _c,Hs as $c,Ks as ad,go as bd,To as cd,Vs as dd,Es as ed,vs as fd,ta as gd};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Af as $}from"./vm-hands-entry-lite-h1642n10.js";var O=$.version,Z=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function S(B,D){if(!Z.test(B)||!Z.test(D))throw Error("cannot compare invalid CLI versions");let J=(q)=>{let y=q.indexOf("-");return y===-1?[q,void 0]:[q.slice(0,y),q.slice(y+1)]},[j,F]=J(B),[w,G]=J(D),K=j.split(".").map(BigInt),M=w.split(".").map(BigInt);for(let q=0;q<3;q+=1){if(K[q]===M[q])continue;return K[q]<M[q]?-1:1}if(F===void 0||G===void 0){if(F===G)return 0;return F===void 0?1:-1}let Q=F.split("."),U=G.split("."),A=Math.max(Q.length,U.length);for(let q=0;q<A;q+=1){let y=Q[q],z=U[q];if(y===void 0||z===void 0){if(y===z)return 0;return y===void 0?-1:1}if(y===z)continue;let H=/^\d+$/.test(y),W=/^\d+$/.test(z);if(H&&W){let X=BigInt(y),Y=BigInt(z);if(X===Y)continue;return X<Y?-1:1}if(H!==W)return H?-1:1;return y<z?-1:1}return 0}function k(B,D){return D?`cli ${B} \xB7 agent ${D}`:`cli ${B}`}
3
- export{O as wf,Z as xf,S as yf,k as zf};
2
+ import{wf as $}from"./vm-hands-entry-lite-q2z2f9n4.js";var O=$.version,Z=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function S(B,D){if(!Z.test(B)||!Z.test(D))throw Error("cannot compare invalid CLI versions");let J=(q)=>{let y=q.indexOf("-");return y===-1?[q,void 0]:[q.slice(0,y),q.slice(y+1)]},[j,F]=J(B),[w,G]=J(D),K=j.split(".").map(BigInt),M=w.split(".").map(BigInt);for(let q=0;q<3;q+=1){if(K[q]===M[q])continue;return K[q]<M[q]?-1:1}if(F===void 0||G===void 0){if(F===G)return 0;return F===void 0?1:-1}let Q=F.split("."),U=G.split("."),A=Math.max(Q.length,U.length);for(let q=0;q<A;q+=1){let y=Q[q],z=U[q];if(y===void 0||z===void 0){if(y===z)return 0;return y===void 0?-1:1}if(y===z)continue;let H=/^\d+$/.test(y),W=/^\d+$/.test(z);if(H&&W){let X=BigInt(y),Y=BigInt(z);if(X===Y)continue;return X<Y?-1:1}if(H!==W)return H?-1:1;return y<z?-1:1}return 0}function k(B,D){return D?`cli ${B} \xB7 agent ${D}`:`cli ${B}`}
3
+ export{O as sf,Z as tf,S as uf,k as vf};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{mi as w}from"./vm-hands-entry-lite-2xh7sjs0.js";var $="inference.custom.v1",K=32768,O=67108864,P=16384,Q=204800,x=600000,S=["content-type","anthropic-version","user-agent"],L=w.enum(["openai-completions","openai-responses","anthropic-messages"]),T=new Set(S),U=w.record(w.string(),w.string().max(2048)).refine((j)=>Object.keys(j).every((A)=>T.has(A))&&Object.values(j).every((A)=>!/[\r\n\0]/.test(A)),"Only non-secret custom endpoint request headers are permitted");function F(j){try{let A=new URL(j);return["http:","https:"].includes(A.protocol)&&!A.username&&!A.password&&!A.search&&!A.hash?A:null}catch{return null}}function V(j,A){let B=F(j.baseUrl),H=F(A.baseUrl),D=F(j.url);if(!B||!H||!D||j.method!=="POST"||A.execution!=="device")return!1;let I=(J)=>J.origin+J.pathname.replace(/\/+$/,"");if(I(B)!==I(H)||D.origin!==B.origin)return!1;let N=A.api==="openai-completions"?"/chat/completions":A.api==="openai-responses"?"/responses":"/v1/messages";return D.pathname===B.pathname.replace(/\/+$/,"")+N}var C=w.object({baseUrl:w.string().max(2048),url:w.string().max(4096),method:w.literal("POST"),body:w.string().refine((j)=>new TextEncoder().encode(j).byteLength<=Q).optional(),headers:U,credentialOrganizationId:w.string().uuid(),accountKey:w.string().min(1).max(256).optional()}).strict().refine((j)=>L.options.some((A)=>V(j,{baseUrl:j.baseUrl,api:A,execution:"device"})),"Invalid custom endpoint inference URL"),E=w.object({status:w.number().int().min(200).max(599),statusText:w.string().max(256).refine((j)=>!/[\r\n\0]/.test(j)),headers:w.record(w.string(),w.string().max(4096)).refine((j)=>Object.keys(j).every((A)=>["content-type","retry-after","x-request-id","request-id"].includes(A))&&Object.values(j).every((A)=>!/[\r\n\0]/.test(A)))}).strict(),M=w.union([w.object({eof:w.literal(!0)}).strict(),w.object({eof:w.literal(!1),data:w.string().max(Math.ceil(K/3)*4).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/).refine((j)=>j.length>0&&j.length*3/4-(j.endsWith("==")?2:j.endsWith("=")?1:0)<=K)}).strict()]),R=w.object({bytes:w.number().int().min(0).max(O),chunks:w.number().int().min(0).max(P)}).strict(),z=w.object({apiKey:w.string().min(1).max(16384).refine((j)=>!/[\r\n\0]/.test(j)),api:L}).strict(),W=["custom_endpoint_host_not_found","custom_endpoint_connection_failed","custom_endpoint_tls_failed"];function p(j){return typeof j==="string"&&W.includes(j)}var X="Ollama listens only on 127.0.0.1 unless it is started with OLLAMA_HOST=0.0.0.0.",G={custom_endpoint_host_not_found:"Your computer couldn't resolve your model server's hostname. Check the hostname in the Base URL, and that this computer is on the network or tailnet that resolves it.",custom_endpoint_connection_failed:`Your computer's connection to your model server was refused or timed out. Check that the server is running and listening on the Base URL's address and port. ${X}`,custom_endpoint_tls_failed:"Your computer couldn't make a secure (TLS) connection to your model server. Check the server's https certificate, or use an http:// Base URL for a server on your computer or private network.",401:"Your model server refused the request (HTTP 401). Check the API key saved for it in Models.",403:"Your model server refused the request (HTTP 403). Ollama refuses requests addressed to a hostname other than localhost, such as a *.ts.net name from tailscale serve or funnel: restart it with OLLAMA_HOST=0.0.0.0, or use http://localhost:11434/v1 when it runs on the session's computer. For another server, check the API key and its access rules.",404:"Your model server answered HTTP 404 (not found). Check that the Base URL is the API root (for Ollama, http://localhost:11434/v1) and that each model ID is one the server lists."},Y=new Set(Object.values(G));function b(j){return Object.hasOwn(G,j)?G[j]:null}function k(j){return typeof j==="string"&&Y.has(j)}var Z=/^Your model endpoint \S+ (?:returned HTTP 40[34]|was unreachable: it refused the connection)\.$/;function y(j,A){if(!/^[a-z0-9.-]+$/i.test(j))return null;if(A==="connection_refused")return`Your model endpoint ${j} was unreachable: it refused the connection.`;return A===403||A===404?`Your model endpoint ${j} returned HTTP ${A}.`:null}function q(j){return typeof j==="string"&&Z.test(j)}
3
- export{$ as rc,K as sc,O as tc,P as uc,Q as vc,x as wc,S as xc,V as yc,C as zc,E as Ac,M as Bc,R as Cc,z as Dc,W as Ec,p as Fc,b as Gc,k as Hc,y as Ic,q as Jc};
2
+ import{ii as w}from"./vm-hands-entry-lite-k17ntg9v.js";var $="inference.custom.v1",K=32768,O=67108864,P=16384,Q=204800,x=600000,S=["content-type","anthropic-version","user-agent"],L=w.enum(["openai-completions","openai-responses","anthropic-messages"]),T=new Set(S),U=w.record(w.string(),w.string().max(2048)).refine((j)=>Object.keys(j).every((A)=>T.has(A))&&Object.values(j).every((A)=>!/[\r\n\0]/.test(A)),"Only non-secret custom endpoint request headers are permitted");function F(j){try{let A=new URL(j);return["http:","https:"].includes(A.protocol)&&!A.username&&!A.password&&!A.search&&!A.hash?A:null}catch{return null}}function V(j,A){let B=F(j.baseUrl),H=F(A.baseUrl),D=F(j.url);if(!B||!H||!D||j.method!=="POST"||A.execution!=="device")return!1;let I=(J)=>J.origin+J.pathname.replace(/\/+$/,"");if(I(B)!==I(H)||D.origin!==B.origin)return!1;let N=A.api==="openai-completions"?"/chat/completions":A.api==="openai-responses"?"/responses":"/v1/messages";return D.pathname===B.pathname.replace(/\/+$/,"")+N}var C=w.object({baseUrl:w.string().max(2048),url:w.string().max(4096),method:w.literal("POST"),body:w.string().refine((j)=>new TextEncoder().encode(j).byteLength<=Q).optional(),headers:U,credentialOrganizationId:w.string().uuid(),accountKey:w.string().min(1).max(256).optional()}).strict().refine((j)=>L.options.some((A)=>V(j,{baseUrl:j.baseUrl,api:A,execution:"device"})),"Invalid custom endpoint inference URL"),E=w.object({status:w.number().int().min(200).max(599),statusText:w.string().max(256).refine((j)=>!/[\r\n\0]/.test(j)),headers:w.record(w.string(),w.string().max(4096)).refine((j)=>Object.keys(j).every((A)=>["content-type","retry-after","x-request-id","request-id"].includes(A))&&Object.values(j).every((A)=>!/[\r\n\0]/.test(A)))}).strict(),M=w.union([w.object({eof:w.literal(!0)}).strict(),w.object({eof:w.literal(!1),data:w.string().max(Math.ceil(K/3)*4).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/).refine((j)=>j.length>0&&j.length*3/4-(j.endsWith("==")?2:j.endsWith("=")?1:0)<=K)}).strict()]),R=w.object({bytes:w.number().int().min(0).max(O),chunks:w.number().int().min(0).max(P)}).strict(),z=w.object({apiKey:w.string().min(1).max(16384).refine((j)=>!/[\r\n\0]/.test(j)),api:L}).strict(),W=["custom_endpoint_host_not_found","custom_endpoint_connection_failed","custom_endpoint_tls_failed"];function p(j){return typeof j==="string"&&W.includes(j)}var X="Ollama listens only on 127.0.0.1 unless it is started with OLLAMA_HOST=0.0.0.0.",G={custom_endpoint_host_not_found:"Your computer couldn't resolve your model server's hostname. Check the hostname in the Base URL, and that this computer is on the network or tailnet that resolves it.",custom_endpoint_connection_failed:`Your computer's connection to your model server was refused or timed out. Check that the server is running and listening on the Base URL's address and port. ${X}`,custom_endpoint_tls_failed:"Your computer couldn't make a secure (TLS) connection to your model server. Check the server's https certificate, or use an http:// Base URL for a server on your computer or private network.",401:"Your model server refused the request (HTTP 401). Check the API key saved for it in Models.",403:"Your model server refused the request (HTTP 403). Ollama refuses requests addressed to a hostname other than localhost, such as a *.ts.net name from tailscale serve or funnel: restart it with OLLAMA_HOST=0.0.0.0, or use http://localhost:11434/v1 when it runs on the session's computer. For another server, check the API key and its access rules.",404:"Your model server answered HTTP 404 (not found). Check that the Base URL is the API root (for Ollama, http://localhost:11434/v1) and that each model ID is one the server lists."},Y=new Set(Object.values(G));function b(j){return Object.hasOwn(G,j)?G[j]:null}function k(j){return typeof j==="string"&&Y.has(j)}var Z=/^Your model endpoint \S+ (?:returned HTTP 40[34]|was unreachable: it refused the connection)\.$/;function y(j,A){if(!/^[a-z0-9.-]+$/i.test(j))return null;if(A==="connection_refused")return`Your model endpoint ${j} was unreachable: it refused the connection.`;return A===403||A===404?`Your model endpoint ${j} returned HTTP ${A}.`:null}function q(j){return typeof j==="string"&&Z.test(j)}
3
+ export{$ as nc,K as oc,O as pc,P as qc,Q as rc,x as sc,S as tc,V as uc,C as vc,E as wc,M as xc,R as yc,z as zc,W as Ac,p as Bc,b as Cc,k as Dc,y as Ec,q as Fc};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{ui as l}from"./vm-hands-entry-lite-gt5pkv4h.js";import{execFile as zj,spawn as I}from"child_process";var Cj="h264_ws_v1",kj="video",h=["smooth","sharp","data_saver","balanced"];var Yj="video_presets";var V=8388608,Y=65536,Lj="control",Aj="v1",d=200;function s(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q,J=(Q)=>typeof Q==="string"&&Q.length>0&&Q.length<=d;if(Object.keys(j).length!==2||!J(j.user_id)||!J(j.name))return null;return{user_id:j.user_id,name:j.name}}var xj="windows",Mj="v1",A=200,o=(q)=>typeof q==="string"&&h.includes(q);function fj(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q;if(Object.keys(j).length!==2||j.format!=="h264_ws_v1"||!o(j.preset))return null;return{format:"h264_ws_v1",preset:j.preset}}var $={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23};class U extends Error{constructor(q){super(q);this.name="DisplayVideoProtocolError"}}var e=new TextEncoder,jj=new TextDecoder("utf-8",{fatal:!0});function H(q,j){if(j.byteLength+1>V)throw new U("message_too_large");let J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,j.byteLength+1),Q.setUint8(4,q),J.set(j,5),J}function R(q){let j=e.encode(q);if(j.byteLength>Y)throw new U("text_too_large");return j}function f(q,j){if(!Number.isInteger(q)||q<0||q>65535)throw new U(`invalid_${j}`);return q}function qj(q){if(!Number.isFinite(q))throw new U("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(q)))}function hj(q){switch(q.type){case"hello":{let j=R(q.codec),J=new Uint8Array(6+j.byteLength),Q=new DataView(J.buffer);return Q.setUint16(0,f(q.width,"width")),Q.setUint16(2,f(q.height,"height")),Q.setUint8(4,Math.max(1,Math.min(240,Math.round(q.fps)))),Q.setUint8(5,h.indexOf(q.preset)),J.set(j,6),H($.hello,J)}case"frame":{let j=new Uint8Array(13+q.data.byteLength),J=new DataView(j.buffer);return J.setUint8(0,q.key?1:0),J.setUint32(1,q.seq>>>0),J.setBigUint64(5,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,13),H($.frame,j)}case"stats":return H($.stats,R(JSON.stringify(q.stats)));case"pong":case"ping":{let j=new Uint8Array(8);return new DataView(j.buffer).setFloat64(0,q.token),H(q.type==="ping"?$.ping:$.pong,j)}case"serverClipboard":return H($.serverClipboard,R(q.text));case"clientClipboard":return H($.clientClipboard,R(q.text));case"error":return H($.error,R(q.code));case"pointer":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint16(0,f(q.x,"x")),J.setUint16(2,f(q.y,"y")),J.setUint8(4,q.buttons&255),H($.pointer,j)}case"key":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint8(0,q.down?1:0),J.setUint32(1,q.keysym>>>0),H($.key,j)}case"config":return H($.config,Uint8Array.of(h.indexOf(q.preset)));case"keyframeRequest":return H($.keyframeRequest,new Uint8Array(0));case"audioHello":{let j=R(q.codec),J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,q.sampleRate>>>0),Q.setUint8(4,q.channels&255),J.set(j,5),H($.audioHello,J)}case"audio":{let j=new Uint8Array(8+q.data.byteLength);return new DataView(j.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,8),H($.audio,j)}case"control":return H($.control,R(JSON.stringify(q.control)));case"windows":{let j=q.bounds.slice(0,A),J=new Uint8Array(j.length*16),Q=new DataView(J.buffer);return j.forEach((Z,z)=>{[Z.x,Z.y,Z.width,Z.height].forEach((G,F)=>Q.setInt32(z*16+F*4,qj(G)))}),H($.windows,J)}case"audioEnable":return H($.audioEnable,Uint8Array.of(q.on?1:0));case"ack":{let j=new Uint8Array(4);return new DataView(j.buffer).setUint32(0,q.seq>>>0),H($.ack,j)}}}function T(q){let j=h[q];if(!j)throw new U("invalid_preset");return j}function C(q,j){if(q.byteLength!==j)throw new U("invalid_length")}function k(q){if(q.byteLength>Y)throw new U("text_too_large");try{return jj.decode(q)}catch{throw new U("invalid_text")}}function Jj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_stats")}let J=j;if(!J||typeof J!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((Z)=>typeof J[Z]!=="number"||!Number.isFinite(J[Z])))throw new U("invalid_stats");return{fps:J.fps,kbps:J.kbps,dropped:J.dropped,restarts:J.restarts,queued_bytes:J.queued_bytes}}function Qj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_control")}let J=j;if(!J||typeof J!=="object"||typeof J.you!=="boolean"||typeof J.same_user!=="boolean")throw new U("invalid_control");let Q=J.holder===null?null:s(J.holder);if(Q===null&&J.holder!==null)throw new U("invalid_control");return{holder:Q,you:J.you,same_user:J.same_user}}function Zj(q,j){let J=new DataView(j.buffer,j.byteOffset,j.byteLength);switch(q){case $.hello:if(j.byteLength<6)throw new U("invalid_length");return{type:"hello",width:J.getUint16(0),height:J.getUint16(2),fps:J.getUint8(4),preset:T(J.getUint8(5)),codec:k(j.subarray(6))};case $.frame:if(j.byteLength<14)throw new U("invalid_length");if(J.getUint8(0)>1)throw new U("invalid_frame_flags");return{type:"frame",key:J.getUint8(0)===1,seq:J.getUint32(1),captureMicros:Number(J.getBigUint64(5)),data:j.subarray(13)};case $.stats:return{type:"stats",stats:Jj(j)};case $.ping:case $.pong:return C(j,8),{type:q===$.ping?"ping":"pong",token:J.getFloat64(0)};case $.serverClipboard:return{type:"serverClipboard",text:k(j)};case $.clientClipboard:return{type:"clientClipboard",text:k(j)};case $.error:return{type:"error",code:k(j)};case $.pointer:return C(j,5),{type:"pointer",x:J.getUint16(0),y:J.getUint16(2),buttons:J.getUint8(4)};case $.key:if(C(j,5),J.getUint8(0)>1)throw new U("invalid_key_flags");return{type:"key",down:J.getUint8(0)===1,keysym:J.getUint32(1)};case $.config:return C(j,1),{type:"config",preset:T(J.getUint8(0))};case $.keyframeRequest:return C(j,0),{type:"keyframeRequest"};case $.audioHello:if(j.byteLength<5)throw new U("invalid_length");return{type:"audioHello",sampleRate:J.getUint32(0),channels:J.getUint8(4),codec:k(j.subarray(5))};case $.audio:if(j.byteLength<9)throw new U("invalid_length");return{type:"audio",captureMicros:Number(J.getBigUint64(0)),data:j.subarray(8)};case $.audioEnable:if(C(j,1),J.getUint8(0)>1)throw new U("invalid_audio_flags");return{type:"audioEnable",on:J.getUint8(0)===1};case $.control:return{type:"control",control:Qj(j)};case $.windows:{if(j.byteLength%16!==0||j.byteLength>A*16)throw new U("invalid_length");let Q=[];for(let Z=0;Z<j.byteLength;Z+=16)Q.push({x:J.getInt32(Z),y:J.getInt32(Z+4),width:J.getInt32(Z+8),height:J.getInt32(Z+12)});return{type:"windows",bounds:Q}}case $.ack:return C(j,4),{type:"ack",seq:J.getUint32(0)};default:return null}}class $j{buffer=new Uint8Array(0);push(q){let j=new Uint8Array(this.buffer.byteLength+q.byteLength);j.set(this.buffer),j.set(q,this.buffer.byteLength);let J=[],Q=0;while(j.byteLength-Q>=4){let Z=new DataView(j.buffer,j.byteOffset+Q,4).getUint32(0);if(Z<1||Z>V)throw new U("invalid_message_length");if(j.byteLength-Q-4<Z)break;let z=j[Q+4],G=j.slice(Q+5,Q+4+Z),F=Zj(z,G);if(F)J.push(F);Q+=4+Z}return this.buffer=j.slice(Q),J}}var t="/usr/bin/osascript",Gj=5000,Kj=1048576,Uj=String.raw`
2
+ import{qi as l}from"./vm-hands-entry-lite-tj1y61bg.js";import{execFile as zj,spawn as I}from"child_process";var Cj="h264_ws_v1",kj="video",h=["smooth","sharp","data_saver","balanced"];var Yj="video_presets";var V=8388608,Y=65536,Lj="control",Aj="v1",d=200;function s(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q,J=(Q)=>typeof Q==="string"&&Q.length>0&&Q.length<=d;if(Object.keys(j).length!==2||!J(j.user_id)||!J(j.name))return null;return{user_id:j.user_id,name:j.name}}var xj="windows",Mj="v1",A=200,o=(q)=>typeof q==="string"&&h.includes(q);function fj(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q;if(Object.keys(j).length!==2||j.format!=="h264_ws_v1"||!o(j.preset))return null;return{format:"h264_ws_v1",preset:j.preset}}var $={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23};class U extends Error{constructor(q){super(q);this.name="DisplayVideoProtocolError"}}var e=new TextEncoder,jj=new TextDecoder("utf-8",{fatal:!0});function H(q,j){if(j.byteLength+1>V)throw new U("message_too_large");let J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,j.byteLength+1),Q.setUint8(4,q),J.set(j,5),J}function R(q){let j=e.encode(q);if(j.byteLength>Y)throw new U("text_too_large");return j}function f(q,j){if(!Number.isInteger(q)||q<0||q>65535)throw new U(`invalid_${j}`);return q}function qj(q){if(!Number.isFinite(q))throw new U("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(q)))}function hj(q){switch(q.type){case"hello":{let j=R(q.codec),J=new Uint8Array(6+j.byteLength),Q=new DataView(J.buffer);return Q.setUint16(0,f(q.width,"width")),Q.setUint16(2,f(q.height,"height")),Q.setUint8(4,Math.max(1,Math.min(240,Math.round(q.fps)))),Q.setUint8(5,h.indexOf(q.preset)),J.set(j,6),H($.hello,J)}case"frame":{let j=new Uint8Array(13+q.data.byteLength),J=new DataView(j.buffer);return J.setUint8(0,q.key?1:0),J.setUint32(1,q.seq>>>0),J.setBigUint64(5,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,13),H($.frame,j)}case"stats":return H($.stats,R(JSON.stringify(q.stats)));case"pong":case"ping":{let j=new Uint8Array(8);return new DataView(j.buffer).setFloat64(0,q.token),H(q.type==="ping"?$.ping:$.pong,j)}case"serverClipboard":return H($.serverClipboard,R(q.text));case"clientClipboard":return H($.clientClipboard,R(q.text));case"error":return H($.error,R(q.code));case"pointer":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint16(0,f(q.x,"x")),J.setUint16(2,f(q.y,"y")),J.setUint8(4,q.buttons&255),H($.pointer,j)}case"key":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint8(0,q.down?1:0),J.setUint32(1,q.keysym>>>0),H($.key,j)}case"config":return H($.config,Uint8Array.of(h.indexOf(q.preset)));case"keyframeRequest":return H($.keyframeRequest,new Uint8Array(0));case"audioHello":{let j=R(q.codec),J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,q.sampleRate>>>0),Q.setUint8(4,q.channels&255),J.set(j,5),H($.audioHello,J)}case"audio":{let j=new Uint8Array(8+q.data.byteLength);return new DataView(j.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,8),H($.audio,j)}case"control":return H($.control,R(JSON.stringify(q.control)));case"windows":{let j=q.bounds.slice(0,A),J=new Uint8Array(j.length*16),Q=new DataView(J.buffer);return j.forEach((Z,z)=>{[Z.x,Z.y,Z.width,Z.height].forEach((G,F)=>Q.setInt32(z*16+F*4,qj(G)))}),H($.windows,J)}case"audioEnable":return H($.audioEnable,Uint8Array.of(q.on?1:0));case"ack":{let j=new Uint8Array(4);return new DataView(j.buffer).setUint32(0,q.seq>>>0),H($.ack,j)}}}function T(q){let j=h[q];if(!j)throw new U("invalid_preset");return j}function C(q,j){if(q.byteLength!==j)throw new U("invalid_length")}function k(q){if(q.byteLength>Y)throw new U("text_too_large");try{return jj.decode(q)}catch{throw new U("invalid_text")}}function Jj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_stats")}let J=j;if(!J||typeof J!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((Z)=>typeof J[Z]!=="number"||!Number.isFinite(J[Z])))throw new U("invalid_stats");return{fps:J.fps,kbps:J.kbps,dropped:J.dropped,restarts:J.restarts,queued_bytes:J.queued_bytes}}function Qj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_control")}let J=j;if(!J||typeof J!=="object"||typeof J.you!=="boolean"||typeof J.same_user!=="boolean")throw new U("invalid_control");let Q=J.holder===null?null:s(J.holder);if(Q===null&&J.holder!==null)throw new U("invalid_control");return{holder:Q,you:J.you,same_user:J.same_user}}function Zj(q,j){let J=new DataView(j.buffer,j.byteOffset,j.byteLength);switch(q){case $.hello:if(j.byteLength<6)throw new U("invalid_length");return{type:"hello",width:J.getUint16(0),height:J.getUint16(2),fps:J.getUint8(4),preset:T(J.getUint8(5)),codec:k(j.subarray(6))};case $.frame:if(j.byteLength<14)throw new U("invalid_length");if(J.getUint8(0)>1)throw new U("invalid_frame_flags");return{type:"frame",key:J.getUint8(0)===1,seq:J.getUint32(1),captureMicros:Number(J.getBigUint64(5)),data:j.subarray(13)};case $.stats:return{type:"stats",stats:Jj(j)};case $.ping:case $.pong:return C(j,8),{type:q===$.ping?"ping":"pong",token:J.getFloat64(0)};case $.serverClipboard:return{type:"serverClipboard",text:k(j)};case $.clientClipboard:return{type:"clientClipboard",text:k(j)};case $.error:return{type:"error",code:k(j)};case $.pointer:return C(j,5),{type:"pointer",x:J.getUint16(0),y:J.getUint16(2),buttons:J.getUint8(4)};case $.key:if(C(j,5),J.getUint8(0)>1)throw new U("invalid_key_flags");return{type:"key",down:J.getUint8(0)===1,keysym:J.getUint32(1)};case $.config:return C(j,1),{type:"config",preset:T(J.getUint8(0))};case $.keyframeRequest:return C(j,0),{type:"keyframeRequest"};case $.audioHello:if(j.byteLength<5)throw new U("invalid_length");return{type:"audioHello",sampleRate:J.getUint32(0),channels:J.getUint8(4),codec:k(j.subarray(5))};case $.audio:if(j.byteLength<9)throw new U("invalid_length");return{type:"audio",captureMicros:Number(J.getBigUint64(0)),data:j.subarray(8)};case $.audioEnable:if(C(j,1),J.getUint8(0)>1)throw new U("invalid_audio_flags");return{type:"audioEnable",on:J.getUint8(0)===1};case $.control:return{type:"control",control:Qj(j)};case $.windows:{if(j.byteLength%16!==0||j.byteLength>A*16)throw new U("invalid_length");let Q=[];for(let Z=0;Z<j.byteLength;Z+=16)Q.push({x:J.getInt32(Z),y:J.getInt32(Z+4),width:J.getInt32(Z+8),height:J.getInt32(Z+12)});return{type:"windows",bounds:Q}}case $.ack:return C(j,4),{type:"ack",seq:J.getUint32(0)};default:return null}}class $j{buffer=new Uint8Array(0);push(q){let j=new Uint8Array(this.buffer.byteLength+q.byteLength);j.set(this.buffer),j.set(q,this.buffer.byteLength);let J=[],Q=0;while(j.byteLength-Q>=4){let Z=new DataView(j.buffer,j.byteOffset+Q,4).getUint32(0);if(Z<1||Z>V)throw new U("invalid_message_length");if(j.byteLength-Q-4<Z)break;let z=j[Q+4],G=j.slice(Q+5,Q+4+Z),F=Zj(z,G);if(F)J.push(F);Q+=4+Z}return this.buffer=j.slice(Q),J}}var t="/usr/bin/osascript",Gj=5000,Kj=1048576,Uj=String.raw`
3
3
  ObjC.import("CoreGraphics");
4
4
  ObjC.import("ApplicationServices");
5
5
  ObjC.import("AppKit");
@@ -109,4 +109,4 @@ function run() {
109
109
  `);X>=0;X=B.indexOf(`
110
110
  `)){let S=B.slice(0,X);if(B=B.slice(X+1),!S.startsWith("c "))continue;let O=S.slice(2);if(O.length>Math.ceil(Y/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(O)){K({reason:"display_protocol"});return}let _=Buffer.from(O,"base64");if(_.byteLength<=Y)q.clipboard(_.toString("utf8"));if(z)return}if(B.length>Math.ceil(Y/3)*4+2)K({reason:"display_protocol"})}),G.once("error",()=>W("Reason could not watch this Mac's desktop clipboard.")),G.once("exit",()=>{if(!z)W("Reason could not watch this Mac's desktop clipboard.")})};return J.stdout.on("data",(B)=>{if(z||Z===null)return;Z+=B.toString("utf8");let N=Z.indexOf(`
111
111
  `);if(N<0){if(Z.length>4096)K({reason:"display_protocol"});return}let X=y(Z.slice(0,N));if(Z=null,!X)K({reason:"display_protocol"});else if(!X.screen||!X.accessibility)W(j.length>0?"Reason's background worker needs Screen Recording and Accessibility on this Mac (its own Reason entry in System Settings > Privacy & Security, not the Reason app's): run `reason permissions allow` on this Mac.":"Allow Screen Recording and Accessibility for this Mac's Reason worker, then restart it.");else i(),q.ready({width:X.width,height:X.height})}),J.stdin.on("error",()=>{return}),J.once("error",()=>W("Reason could not start this Mac's desktop input.")),J.once("exit",()=>{if(Z!==null)W("Reason could not start this Mac's desktop input.");else K({reason:"display_closed"})}),{pointer:(B,N,X)=>L(Q.pointer(B,N,X)),key:(B,N)=>L(Q.key(B,N)),clipboard:(B)=>L([`c ${Buffer.from(B,"utf8").toString("base64")}`]),close(){z=!0,F()}}}
112
- export{Cj as Bf,kj as Cf,h as Df,Yj as Ef,Y as Ff,Lj as Gf,Aj as Hf,s as If,xj as Jf,Mj as Kf,fj as Lf,hj as Mf,$j as Nf,y as Of,Sj as Pf,_j as Qf,Hj as Rf,Tj as Sf,a as Tf,Vj as Uf};
112
+ export{Cj as xf,kj as yf,h as zf,Yj as Af,Y as Bf,Lj as Cf,Aj as Df,s as Ef,xj as Ff,Mj as Gf,fj as Hf,hj as If,$j as Jf,y as Kf,Sj as Lf,_j as Mf,Hj as Nf,Tj as Of,a as Pf,Vj as Qf};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{xi as e}from"./vm-hands-entry-lite-mhsv58hw.js";var i=e((o,t)=>{t.exports={name:"playwright-core",version:"1.60.0",description:"A high-level API to automate web browsers",repository:{type:"git",url:"git+https://github.com/microsoft/playwright.git"},homepage:"https://playwright.dev",engines:{node:">=18"},author:{name:"Microsoft Corporation"},license:"Apache-2.0",exports:{".":{types:"./index.d.ts",import:"./index.mjs",require:"./index.js",default:"./index.js"},"./package.json":"./package.json","./lib/bootstrap":"./lib/bootstrap.js","./lib/coreBundle":"./lib/coreBundle.js","./lib/utilsBundle":"./lib/utilsBundle.js","./lib/tools/cli-client/program":"./lib/tools/cli-client/program.js"},bin:{"playwright-core":"cli.js"},types:"types/types.d.ts"}});
2
+ import{ti as e}from"./vm-hands-entry-lite-nd1k2jz9.js";var i=e((o,t)=>{t.exports={name:"playwright-core",version:"1.60.0",description:"A high-level API to automate web browsers",repository:{type:"git",url:"git+https://github.com/microsoft/playwright.git"},homepage:"https://playwright.dev",engines:{node:">=18"},author:{name:"Microsoft Corporation"},license:"Apache-2.0",exports:{".":{types:"./index.d.ts",import:"./index.mjs",require:"./index.js",default:"./index.js"},"./package.json":"./package.json","./lib/bootstrap":"./lib/bootstrap.js","./lib/coreBundle":"./lib/coreBundle.js","./lib/utilsBundle":"./lib/utilsBundle.js","./lib/tools/cli-client/program":"./lib/tools/cli-client/program.js"},bin:{"playwright-core":"cli.js"},types:"types/types.d.ts"}});
3
3
  export{i as Q};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Sb as D}from"./vm-hands-entry-lite-wmxksawm.js";import{ui as j}from"./vm-hands-entry-lite-gt5pkv4h.js";import{statSync as i}from"fs";import{delimiter as n,join as t}from"path";function _(q,z=process.env.PATH??""){if(!q||q.includes("/")||q.includes("\x00"))return!1;return z.split(n).some((G)=>{if(!G)return!1;try{let Q=i(t(G,q));return Q.isFile()&&(Q.mode&73)!==0}catch{return!1}})}import{spawn as r,spawnSync as e}from"child_process";import{existsSync as k,mkdtempSync as E,readFileSync as O,readdirSync as o,realpathSync as qq,rmSync as b,statSync as zq}from"fs";import{platform as y,tmpdir as g}from"os";import{dirname as A,join as Z}from"path";import{fileURLToPath as Gq,pathToFileURL as T}from"url";var Hq=["bwrap","socat","rg"],Jq=2000,v=20000,Qq=3,P=4000,Vq=new Set([".git",".hg",".svn","node_modules"]),Wq=["runAsHostUid","sysrq-trigger"],Yq=Z(A(A(Gq(import.meta.url))),"packages/sandbox-runtime/src/index.ts"),h=!1;function fq(){h=!0}async function u(){let z=h?Z(A(qq(process.execPath)),"runtime","srt"):void 0;if(z&&process.platform==="linux"&&!k(Z(z,"vendor","seccomp",process.arch,"apply-seccomp")))throw Error("packaged_sandbox_runtime_vendor_missing");if(z){let J=O(Z(z,"sandbox-runtime.mjs"),"utf8");for(let Y of Wq)if(!J.includes(Y))throw Error(`packaged_sandbox_runtime_fork_missing:${Y}`)}let H=(await import(z?T(Z(z,"sandbox-runtime.mjs")).href:T(Yq).href)).SandboxManager;if(!H||typeof H.initialize!=="function"||typeof H.wrapWithSandboxArgv!=="function")throw Error("sandbox-runtime does not expose the expected SandboxManager API.");return{SandboxManager:H}}function Zq(q={}){if((q.platformName??y())!=="linux")return!1;let G=q.fileExists??k,Q=q.readFile??((H)=>O(H,"utf8"));for(let H of["/.dockerenv","/run/.containerenv"])try{if(G(H))return!0}catch{}try{return/docker|containerd|kubepods|lxc|libpod/.test(Q("/proc/1/cgroup"))}catch{return!1}}function l(q){return["/bin/true","/usr/bin/true"].find((z)=>q(z))??null}function $q(q,z){return q==="strict"?["--ro-bind","/","/","--unshare-pid","--unshare-user","--cap-drop","ALL","--proc","/proc","--",z]:["--ro-bind","/","/","--unshare-pid","--unshare-user","--bind","/proc","/proc","--",z]}function jq(q,z){try{let G=e("bwrap",$q(q,z),{stdio:"ignore",timeout:Jq});return!G.error&&G.status===0}catch{return!1}}function Bq(q){let z=q.platformName??y();if(z!=="linux")return null;let G=q.hasExecutable??_;if(!Hq.every((V)=>G(V)))return null;let Q=q.fileExists??k,H=l(Q);if(!H)return null;let J=B??(q.containerized??Zq({platformName:z})?"weak":"strict");return(q.probeNamespaces??((V)=>jq(V,H)))(J)?J:null}var L=null,C=!1,K=null,S=null,f=null,B=null,F=null;function M(){throw I("sandbox_mode_conflict"),new j("sandbox_unavailable","Sandbox process policy conflicts with an existing probe or session. Restart the worker.")}function xq(q){if(B!==null&&B!==q||C&&L!==null&&L!==q||F!==null&&F!==q)M();B=q}function I(q){K=q}function c(q){if(K)return!1;if(!C){if(L=Bq(q??{}),C=!0,L&&!q)d()}return L!==null}function Lq(){return c()?L:null}var U=null,w=0;function m(q){if(K)throw new j("sandbox_unavailable","Confined execution is unavailable in this worker process.");if(B&&q.sandboxMode&&B!==q.sandboxMode)M();let z=B??q.sandboxMode??Lq();if(!z)throw new j("sandbox_unavailable","Confined command execution is unavailable on this operating system.");if(F&&F!==z)M();return F=z,U??=(async()=>{let{SandboxManager:G}=await(q.loadSandboxRuntime??u)();return await G.initialize(Iq(z)),G})().catch((G)=>{throw U=null,I(`initialize_failed: ${String(G)}`),G instanceof j?G:new j("sandbox_unavailable","The confined execution sandbox failed to start.")}),U.then((G)=>{if(K)throw new j("sandbox_unavailable","Confined execution became unavailable during sandbox initialization.");return G})}async function Kq(){let q=U;if(U=null,!q)return;try{await(await q).reset()}catch{}}async function d(q={}){if(K)return!1;if(q.loadSandboxRuntime)return x(q.loadSandboxRuntime);if(!c())return!1;return S??=x(u),S}async function x(q){try{let{SandboxManager:z}=await q(),G=z.checkDependencies().errors;if(G.length>0)return I(`dependencies_missing: ${G.join(", ")}`),!1;return!K}catch(z){return I(`load_failed: ${String(z)}`),!1}}async function Rq(q={}){if(!q.loadSandboxRuntime&&!q.sandboxMode){if(!await d())return!1;return f??=R({}),f}return R(q)}async function R(q){let z;try{z=await m(q)}catch{return!1}let G=await Xq(z);if(!G)I("confined_command_failed");if(w===0)await Kq();return G}async function Xq(q){let z=l(k);if(!z)return!1;let G=E(Z(g(),"reason-device-probe-"));try{let{argv:Q}=await q.wrapWithSandboxArgv(a([z]),p(),{filesystem:s({root:G,allowWrite:!1,temporaryDirectory:G,protectedPaths:[]})},void 0,G),[H,...J]=Q;if(!H)return!1;return await Fq(H,J,G)}catch{return!1}finally{try{q.cleanupAfterCommand()}catch{}b(G,{recursive:!0,force:!0})}}function Fq(q,z,G,Q={}){return new Promise((H)=>{let J=!1,Y,V=(X)=>{if(J)return;J=!0,clearTimeout(Y),H(X)},W;try{W=(Q.spawnChild??r)(q,z,{cwd:G,env:{PATH:D,HOME:G,TMPDIR:G},stdio:"ignore"})}catch{V(!1);return}W.once("error",()=>V(!1));let $=(X,N)=>V(X===0&&N===null);if(W.once("exit",$),W.once("close",$),W.exitCode!==null||W.signalCode!==null)$(W.exitCode,W.signalCode);if(J)return;Y=setTimeout(()=>{V(!1);try{W.kill("SIGKILL")}catch{}},Math.min(Q.timeoutMs??v,v))})}function p(q=k){return["/bin/bash","/bin/sh"].find((z)=>q(z))??"/bin/sh"}function a(q){return q.map((z)=>`'${z.replaceAll("'","'\\''")}'`).join(" ")}function Uq(q,z,G=(Q)=>o(Q,{withFileTypes:!0}).filter((H)=>H.isDirectory()||H.isFile()).map((H)=>H.name)){let Q=[],H=[{path:q,depth:0}],J=0;while(H.length>0&&J<P){let Y=H.pop(),V;try{V=G(Y.path)}catch{continue}for(let W of V){if(J+=1,J>P)break;let $=Z(Y.path,W);if(z($)){Q.push($);continue}if(Y.depth+1<Qq&&!Vq.has(W))H.push({path:$,depth:Y.depth+1})}}return Q}function s(q){let z=Z(q.root,".git"),G=[];try{if(zq(z).isDirectory())G=[Z(z,"config"),Z(z,"hooks")]}catch{}return{denyRead:["/home","/root","/tmp","/tmp/.X11-unix",...q.protectedPaths],allowRead:[q.root,q.temporaryDirectory],allowWrite:[...q.allowWrite?[q.root]:[],q.temporaryDirectory],denyWrite:[...q.protectedPaths,...G]}}function Iq(q){return{network:{allowedDomains:[],deniedDomains:[]},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},...q==="weak"?{enableWeakerNestedSandbox:!0}:{}}}function Dq(q){let z=q.createTemporaryDirectory??(()=>E(Z(g(),"reason-device-"))),G=q.removeTemporaryDirectory??((Q)=>b(Q,{recursive:!0,force:!0}));return async(Q,H,J)=>{let Y=await m(q),V=z();w+=1;try{let W;try{W=await Y.wrapWithSandboxArgv(a([Q,...H]),q.shell??p(),{filesystem:s({root:J.root,allowWrite:J.allowWrite,temporaryDirectory:V,protectedPaths:Uq(J.root,q.isProtectedPath)})},J.signal,J.cwd)}catch(N){throw N instanceof j?N:new j("sandbox_unavailable","The confined execution sandbox could not wrap the command.")}let[$,...X]=W.argv;if(!$)throw new j("sandbox_unavailable","The confined execution sandbox produced no command.");return await q.spawnCaptured($,X,{cwd:J.cwd,timeoutMs:J.timeoutMs,signal:J.signal,env:q.scrubEnvironment(J.root,V)})}finally{w-=1;try{Y.cleanupAfterCommand()}catch{}G(V)}}}
3
- export{_ as Lb,fq as Mb,xq as Nb,c as Ob,Rq as Pb,p as Qb,Dq as Rb};
2
+ import{Rb as D}from"./vm-hands-entry-lite-wpx6sg6d.js";import{qi as j}from"./vm-hands-entry-lite-tj1y61bg.js";import{statSync as i}from"fs";import{delimiter as n,join as t}from"path";function _(q,z=process.env.PATH??""){if(!q||q.includes("/")||q.includes("\x00"))return!1;return z.split(n).some((G)=>{if(!G)return!1;try{let Q=i(t(G,q));return Q.isFile()&&(Q.mode&73)!==0}catch{return!1}})}import{spawn as r,spawnSync as e}from"child_process";import{existsSync as k,mkdtempSync as E,readFileSync as O,readdirSync as o,realpathSync as qq,rmSync as b,statSync as zq}from"fs";import{platform as y,tmpdir as g}from"os";import{dirname as A,join as Z}from"path";import{fileURLToPath as Gq,pathToFileURL as T}from"url";var Hq=["bwrap","socat","rg"],Jq=2000,v=20000,Qq=3,P=4000,Vq=new Set([".git",".hg",".svn","node_modules"]),Wq=["runAsHostUid","sysrq-trigger"],Yq=Z(A(A(Gq(import.meta.url))),"packages/sandbox-runtime/src/index.ts"),h=!1;function fq(){h=!0}async function u(){let z=h?Z(A(qq(process.execPath)),"runtime","srt"):void 0;if(z&&process.platform==="linux"&&!k(Z(z,"vendor","seccomp",process.arch,"apply-seccomp")))throw Error("packaged_sandbox_runtime_vendor_missing");if(z){let J=O(Z(z,"sandbox-runtime.mjs"),"utf8");for(let Y of Wq)if(!J.includes(Y))throw Error(`packaged_sandbox_runtime_fork_missing:${Y}`)}let H=(await import(z?T(Z(z,"sandbox-runtime.mjs")).href:T(Yq).href)).SandboxManager;if(!H||typeof H.initialize!=="function"||typeof H.wrapWithSandboxArgv!=="function")throw Error("sandbox-runtime does not expose the expected SandboxManager API.");return{SandboxManager:H}}function Zq(q={}){if((q.platformName??y())!=="linux")return!1;let G=q.fileExists??k,Q=q.readFile??((H)=>O(H,"utf8"));for(let H of["/.dockerenv","/run/.containerenv"])try{if(G(H))return!0}catch{}try{return/docker|containerd|kubepods|lxc|libpod/.test(Q("/proc/1/cgroup"))}catch{return!1}}function l(q){return["/bin/true","/usr/bin/true"].find((z)=>q(z))??null}function $q(q,z){return q==="strict"?["--ro-bind","/","/","--unshare-pid","--unshare-user","--cap-drop","ALL","--proc","/proc","--",z]:["--ro-bind","/","/","--unshare-pid","--unshare-user","--bind","/proc","/proc","--",z]}function jq(q,z){try{let G=e("bwrap",$q(q,z),{stdio:"ignore",timeout:Jq});return!G.error&&G.status===0}catch{return!1}}function Bq(q){let z=q.platformName??y();if(z!=="linux")return null;let G=q.hasExecutable??_;if(!Hq.every((V)=>G(V)))return null;let Q=q.fileExists??k,H=l(Q);if(!H)return null;let J=B??(q.containerized??Zq({platformName:z})?"weak":"strict");return(q.probeNamespaces??((V)=>jq(V,H)))(J)?J:null}var L=null,C=!1,K=null,S=null,f=null,B=null,F=null;function M(){throw I("sandbox_mode_conflict"),new j("sandbox_unavailable","Sandbox process policy conflicts with an existing probe or session. Restart the worker.")}function xq(q){if(B!==null&&B!==q||C&&L!==null&&L!==q||F!==null&&F!==q)M();B=q}function I(q){K=q}function c(q){if(K)return!1;if(!C){if(L=Bq(q??{}),C=!0,L&&!q)d()}return L!==null}function Lq(){return c()?L:null}var U=null,w=0;function m(q){if(K)throw new j("sandbox_unavailable","Confined execution is unavailable in this worker process.");if(B&&q.sandboxMode&&B!==q.sandboxMode)M();let z=B??q.sandboxMode??Lq();if(!z)throw new j("sandbox_unavailable","Confined command execution is unavailable on this operating system.");if(F&&F!==z)M();return F=z,U??=(async()=>{let{SandboxManager:G}=await(q.loadSandboxRuntime??u)();return await G.initialize(Iq(z)),G})().catch((G)=>{throw U=null,I(`initialize_failed: ${String(G)}`),G instanceof j?G:new j("sandbox_unavailable","The confined execution sandbox failed to start.")}),U.then((G)=>{if(K)throw new j("sandbox_unavailable","Confined execution became unavailable during sandbox initialization.");return G})}async function Kq(){let q=U;if(U=null,!q)return;try{await(await q).reset()}catch{}}async function d(q={}){if(K)return!1;if(q.loadSandboxRuntime)return x(q.loadSandboxRuntime);if(!c())return!1;return S??=x(u),S}async function x(q){try{let{SandboxManager:z}=await q(),G=z.checkDependencies().errors;if(G.length>0)return I(`dependencies_missing: ${G.join(", ")}`),!1;return!K}catch(z){return I(`load_failed: ${String(z)}`),!1}}async function Rq(q={}){if(!q.loadSandboxRuntime&&!q.sandboxMode){if(!await d())return!1;return f??=R({}),f}return R(q)}async function R(q){let z;try{z=await m(q)}catch{return!1}let G=await Xq(z);if(!G)I("confined_command_failed");if(w===0)await Kq();return G}async function Xq(q){let z=l(k);if(!z)return!1;let G=E(Z(g(),"reason-device-probe-"));try{let{argv:Q}=await q.wrapWithSandboxArgv(a([z]),p(),{filesystem:s({root:G,allowWrite:!1,temporaryDirectory:G,protectedPaths:[]})},void 0,G),[H,...J]=Q;if(!H)return!1;return await Fq(H,J,G)}catch{return!1}finally{try{q.cleanupAfterCommand()}catch{}b(G,{recursive:!0,force:!0})}}function Fq(q,z,G,Q={}){return new Promise((H)=>{let J=!1,Y,V=(X)=>{if(J)return;J=!0,clearTimeout(Y),H(X)},W;try{W=(Q.spawnChild??r)(q,z,{cwd:G,env:{PATH:D,HOME:G,TMPDIR:G},stdio:"ignore"})}catch{V(!1);return}W.once("error",()=>V(!1));let $=(X,N)=>V(X===0&&N===null);if(W.once("exit",$),W.once("close",$),W.exitCode!==null||W.signalCode!==null)$(W.exitCode,W.signalCode);if(J)return;Y=setTimeout(()=>{V(!1);try{W.kill("SIGKILL")}catch{}},Math.min(Q.timeoutMs??v,v))})}function p(q=k){return["/bin/bash","/bin/sh"].find((z)=>q(z))??"/bin/sh"}function a(q){return q.map((z)=>`'${z.replaceAll("'","'\\''")}'`).join(" ")}function Uq(q,z,G=(Q)=>o(Q,{withFileTypes:!0}).filter((H)=>H.isDirectory()||H.isFile()).map((H)=>H.name)){let Q=[],H=[{path:q,depth:0}],J=0;while(H.length>0&&J<P){let Y=H.pop(),V;try{V=G(Y.path)}catch{continue}for(let W of V){if(J+=1,J>P)break;let $=Z(Y.path,W);if(z($)){Q.push($);continue}if(Y.depth+1<Qq&&!Vq.has(W))H.push({path:$,depth:Y.depth+1})}}return Q}function s(q){let z=Z(q.root,".git"),G=[];try{if(zq(z).isDirectory())G=[Z(z,"config"),Z(z,"hooks")]}catch{}return{denyRead:["/home","/root","/tmp","/tmp/.X11-unix",...q.protectedPaths],allowRead:[q.root,q.temporaryDirectory],allowWrite:[...q.allowWrite?[q.root]:[],q.temporaryDirectory],denyWrite:[...q.protectedPaths,...G]}}function Iq(q){return{network:{allowedDomains:[],deniedDomains:[]},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},...q==="weak"?{enableWeakerNestedSandbox:!0}:{}}}function Dq(q){let z=q.createTemporaryDirectory??(()=>E(Z(g(),"reason-device-"))),G=q.removeTemporaryDirectory??((Q)=>b(Q,{recursive:!0,force:!0}));return async(Q,H,J)=>{let Y=await m(q),V=z();w+=1;try{let W;try{W=await Y.wrapWithSandboxArgv(a([Q,...H]),q.shell??p(),{filesystem:s({root:J.root,allowWrite:J.allowWrite,temporaryDirectory:V,protectedPaths:Uq(J.root,q.isProtectedPath)})},J.signal,J.cwd)}catch(N){throw N instanceof j?N:new j("sandbox_unavailable","The confined execution sandbox could not wrap the command.")}let[$,...X]=W.argv;if(!$)throw new j("sandbox_unavailable","The confined execution sandbox produced no command.");return await q.spawnCaptured($,X,{cwd:J.cwd,timeoutMs:J.timeoutMs,signal:J.signal,env:q.scrubEnvironment(J.root,V)})}finally{w-=1;try{Y.cleanupAfterCommand()}catch{}G(V)}}}
3
+ export{_ as Kb,fq as Lb,xq as Mb,c as Nb,Rq as Ob,p as Pb,Dq as Qb};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{mi as j}from"./vm-hands-entry-lite-2xh7sjs0.js";var q=25,K=j.object({machine:j.string().min(1).max(200),person:j.string().min(1).max(200),team:j.string().min(1).max(200),version:j.string().max(64).optional(),wait_seconds:j.number().int().min(0).max(q).optional()}),v=j.discriminatedUnion("kind",[j.object({id:j.string(),kind:j.literal("who")}),j.object({id:j.string(),kind:j.literal("send"),to:j.string(),body:j.string(),from_name:j.string(),from_agent:j.string(),wake:j.boolean()})]),P=j.object({job:v.nullable(),retry_after_seconds:j.number().optional()}),x=j.object({address:j.string(),person:j.string(),machine:j.string(),agent:j.string(),repo:j.string().nullable(),branch:j.string().nullable(),status:j.string(),since:j.number().nullable(),doing:j.string().nullable(),worker:j.boolean()}),B=j.object({person:j.string(),machine:j.string(),online:j.boolean()}),F=j.object({team:j.string().nullable(),sessions:j.array(x).max(2000),machines:j.array(B).max(500)}),Q=j.union([j.object({who:F}),j.object({sent:j.object({ids:j.array(j.string().max(100)).max(500),recipients:j.array(j.string().max(300)).max(500),from:j.string().max(300)})}),j.object({error:j.string().min(1).max(2000)})]),G=j.object({id:j.string().max(100),from:j.string().max(300),from_agent:j.string().max(100).nullable(),to:j.string().max(300),reply_to:j.string().max(100).nullable(),body:j.string().max(64000),sent_at:j.number()}),U=j.object({messages:j.array(G).max(100)});
2
+ import{ii as j}from"./vm-hands-entry-lite-k17ntg9v.js";var q=25,K=j.object({machine:j.string().min(1).max(200),person:j.string().min(1).max(200),team:j.string().min(1).max(200),version:j.string().max(64).optional(),wait_seconds:j.number().int().min(0).max(q).optional()}),v=j.discriminatedUnion("kind",[j.object({id:j.string(),kind:j.literal("who")}),j.object({id:j.string(),kind:j.literal("send"),to:j.string(),body:j.string(),from_name:j.string(),from_agent:j.string(),wake:j.boolean()})]),P=j.object({job:v.nullable(),retry_after_seconds:j.number().optional()}),x=j.object({address:j.string(),person:j.string(),machine:j.string(),agent:j.string(),repo:j.string().nullable(),branch:j.string().nullable(),status:j.string(),since:j.number().nullable(),doing:j.string().nullable(),worker:j.boolean()}),B=j.object({person:j.string(),machine:j.string(),online:j.boolean()}),F=j.object({team:j.string().nullable(),sessions:j.array(x).max(2000),machines:j.array(B).max(500)}),Q=j.union([j.object({who:F}),j.object({sent:j.object({ids:j.array(j.string().max(100)).max(500),recipients:j.array(j.string().max(300)).max(500),from:j.string().max(300)})}),j.object({error:j.string().min(1).max(2000)})]),G=j.object({id:j.string().max(100),from:j.string().max(300),from_agent:j.string().max(100).nullable(),to:j.string().max(300),reply_to:j.string().max(100).nullable(),body:j.string().max(64000),sent_at:j.number()}),U=j.object({messages:j.array(G).max(100)});
3
3
  export{q as L,P as M};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  function r(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}
3
- export{r as qc};
3
+ export{r as mc};