@reason-machines/cli-linux-x64 0.2.567 → 0.2.568
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.
- package/bin/reason +1 -1
- package/bin/vm-hands/{agent-network-0sng03r6.js → agent-network-dw7yrrwt.js} +1 -1
- package/bin/vm-hands/{api-credentials-h4neeejt.js → api-credentials-ntpwt7rg.js} +1 -1
- package/bin/vm-hands/{api-mr6xds10.js → api-xvjq0bka.js} +1 -1
- package/bin/vm-hands/{ask-relay-c0v30hh6.js → ask-relay-hfa5kzxn.js} +2 -2
- package/bin/vm-hands/connect-cli-2ja7aj4w.js +2 -0
- package/bin/vm-hands/{desktop-components-7ngf8byq.js → desktop-components-577haqrs.js} +1 -1
- package/bin/vm-hands/{local-automation-3mdhfw08.js → local-automation-fxdb4ynz.js} +1 -1
- package/bin/vm-hands/{local-capabilities-6e0gkrqq.js → local-capabilities-8fgrfpj4.js} +1 -1
- package/bin/vm-hands/{local-display-session-r6s0wghh.js → local-display-session-8b2hx1k6.js} +1 -1
- package/bin/vm-hands/local-display-video-511qjgmq.js +2 -0
- package/bin/vm-hands/{local-managed-process-p8xd7m5f.js → local-managed-process-h0fypn67.js} +1 -1
- package/bin/vm-hands/{managed-runtime-4s8q8r7f.js → managed-runtime-e4cj6r2s.js} +1 -1
- package/bin/vm-hands/{network-auto-update-wep7067g.js → network-auto-update-8f2745gk.js} +2 -2
- package/bin/vm-hands/{network-sign-in-rdnerhpz.js → network-sign-in-s00679q9.js} +1 -1
- package/bin/vm-hands/{permissions-mmg1gbdx.js → permissions-74rj58e1.js} +1 -1
- package/bin/vm-hands/{serve-service-k3mpxpj6.js → serve-service-19s965ze.js} +1 -1
- package/bin/vm-hands/{status-2s3zjapg.js → status-099b2ec1.js} +3 -3
- package/bin/vm-hands/{version-41q9twfs.js → version-avq09c5d.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-tv5mcw97.js → vm-hands-entry-lite-2qh3rat2.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-6g9we34r.js → vm-hands-entry-lite-7jmt3q38.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-dzdjwa06.js → vm-hands-entry-lite-8s5n4wps.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-vedb5r12.js → vm-hands-entry-lite-9meg54bs.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-ax2w9ywb.js → vm-hands-entry-lite-bcz4qpp6.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-3r063pb4.js → vm-hands-entry-lite-dhn0fs5e.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-zaj1vnnd.js → vm-hands-entry-lite-ezkb7f6j.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-dtw6cj95.js → vm-hands-entry-lite-fp3gaa2c.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-n5jyzccm.js → vm-hands-entry-lite-h5x725z8.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-9gn7k5rp.js → vm-hands-entry-lite-jm9jpj77.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-b3mfma12.js → vm-hands-entry-lite-ksfd234v.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-07wr95rz.js → vm-hands-entry-lite-kzygj0q8.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-cy8yc9gb.js → vm-hands-entry-lite-mktndd2r.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-298kzt93.js → vm-hands-entry-lite-mzw2vcah.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-crjaacc2.js → vm-hands-entry-lite-n9277v11.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-xd393rm3.js → vm-hands-entry-lite-rd7bm9we.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-rmcdfbkk.js → vm-hands-entry-lite-rpf4t8r4.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-dfphra23.js → vm-hands-entry-lite-y2vqwds4.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-31ea40aw.js → vm-hands-executor-xd8v5v0e.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-6r390v3d.js → vm-hands-op-runner-nr4ncs4p.js} +1 -1
- package/bin/vm-hands/vm-hands-runtime-qvy5s122.js +4 -0
- package/package.json +1 -1
- package/bin/vm-hands/connect-cli-jc4m755k.js +0 -2
- package/bin/vm-hands/local-display-video-61peg1pj.js +0 -2
- package/bin/vm-hands/vm-hands-runtime-z9m50n9p.js +0 -4
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ra}from"./vm-hands-entry-lite-r131db1f.js";import{R}from"./vm-hands-entry-lite-ys4jhf7n.js";import{W}from"./vm-hands-entry-lite-0xfme8gg.js";import{Q,so,ve,ao}from"./vm-hands-entry-lite-4kb5rq3d.js";import{Ir}from"./vm-hands-entry-lite-crjaacc2.js";import{t,o,_,d,n,ll,we,c,i}from"./vm-hands-entry-lite-bt6skt4h.js";var E=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function k(e){let s=typeof e==="string"?E.exec(e):null;return s?{major:Number(s[1]),minor:Number(s[2])}:null}import{createHash as q,randomBytes as P}from"crypto";import{createInterface as M}from"readline";var v=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var Ge=v.filter((e)=>e!=="network:read"&&e!=="network:write");class y extends Error{oauthCode;constructor(e,s=null){super(e);this.oauthCode=s;this.name="LoginError"}}function Aa(){let e=P(48).toString("base64url"),s=q("sha256").update(e).digest("base64url");return{verifier:e,challenge:s,state:P(32).toString("base64url")}}function z(e,s){let r=typeof e.error==="string"?e.error:null,a=typeof e.error_description==="string"?e.error_description:r?r:s;return new y(a,r)}async function L(e,s,r,a){let l=await r(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:s,signal:a}),u=await l.json().catch(()=>({}));if(!l.ok)throw z(u,`OAuth token request failed (${l.status})`);return u}var j=1e4;async function D(e,s={}){let r=s.fetchImpl??fetch,a=await L(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),r,AbortSignal.timeout(j)).catch((u)=>{if(u instanceof Error&&u.name==="TimeoutError")throw new y("Reason did not answer the login refresh in time. Check the network and retry.");throw u});if(typeof a.access_token!=="string"||typeof a.refresh_token!=="string"||typeof a.expires_in!=="number")throw new y("Reason returned an incomplete refreshed login.");let l={...e,accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:new Date(Date.now()+a.expires_in*1000).toISOString(),scopes:typeof a.scope==="string"?a.scope.split(/\s+/).filter(Boolean):e.scopes};return so(l,s.path??Q()),l}var w=new Map,N=2000,H=100;function I(e,s){if(!s)return e;if(s.aborted)return Promise.reject(s.reason);return new Promise((r,a)=>{let l=()=>a(s.reason);s.addEventListener("abort",l,{once:!0}),e.then(r,a).finally(()=>s.removeEventListener("abort",l))})}async function be(e={}){let s=e.path??Q(),r=ve(s);if(!r)return null;let a=e.apiOrigin??R(process.env,"REASON_API_URL")?.trim();if(a&&!W(r.apiOrigin,new URL(a).origin))return null;if(!(Date.parse(r.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&r.accessToken!==e.refused))return r;let u=[s,r.apiOrigin,r.clientId,r.refreshToken].join("\x00"),g=w.get(u);if(g)return I(g,e.signal);let h;return h=D(r,{fetchImpl:e.fetchImpl,path:s}).catch(async(p)=>{if(!(p instanceof y)||p.oauthCode!=="invalid_grant"&&p.oauthCode!=="invalid_client")throw p;let S=(f)=>f!==null&&(p.oauthCode==="invalid_client"?f.clientId!==r.clientId:f.refreshToken!==r.refreshToken),O=Date.now()+N;while(!S(ve(s))&&Date.now()<O)await new Promise((f)=>setTimeout(f,H));if(S(ve(s)))return be({fetchImpl:e.fetchImpl,path:s});return ao(s),null}).finally(()=>{if(w.get(u)===h)w.delete(u)}),w.set(u,h),I(h,e.signal)}function Pa(e,s){return new Promise((r)=>{let a=M({input:e}),l=!1,u=(h)=>{if(l)return;l=!0,s.removeEventListener("abort",g),a.close(),e.pause(),r(h)},g=()=>u(null);s.addEventListener("abort",g,{once:!0}),a.once("line",(h)=>u(h)),a.once("close",()=>u(null))})}var F=n({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:_().nullable()}),B=n({groups:d(n({selectable:_().optional(),accounts:d(n({source_id:t().min(1),model_ids:d(t().min(1)).optional()}))}))});function G(e){let s=B.safeParse(e);if(!s.success)return;return s.data.groups.some((r)=>r.selectable!==!1&&r.accounts.some((a)=>a.model_ids===void 0||a.model_ids.length>0))}class C extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;refusal;constructor(e,s,r,a,l,u,g){super(r);this.status=e;this.code=s;this.suggestedModel=a;this.retryAfterMs=l;this.resolutionReason=u;this.refusal=g;this.name="ApiError"}static rateLimitDelayMs(e,s){if(!(e instanceof C)||e.status!==429)return null;return Math.min(60000,Math.max(s,e.retryAfterMs??0))}}var J=["minimal","low","medium","high","xhigh","max"],K=n({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:_(),compatible:_().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:d(n({id:t().min(1),label:t()}))}),V=n({devices:d(K),end_cursor:t().nullish(),has_next_page:_().optional()}),Y=n({id:t().min(1),name:t()}),Z=n({items:d(Y)}),X=n({id:t().min(1),name:t(),main:_(),mine:_(),session_id:t().nullish(),appearance:n({color:t().nullish()}).nullish().catch(null)}),ee=n({items:d(X)}),ne=n({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:d(t()).default([]),is_enabled:_().default(!0)}),te=n({items:d(ne).default([])}),se=n({id:t().min(1),kind:t(),enabled:_(),schedule:n({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:n({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),A=n({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:_(),triggers:d(se).default([])}),oe=n({items:d(A).default([]),end_cursor:t().nullish(),has_next_page:_().optional()}),re=n({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:_()}),ie=n({items:d(re).default([])}),ae=n({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),x=n({tags:d(t()).default([])}),le=c(["linux","macos"]),T=n({id:t().min(1),name:t().min(1),platform:le.nullable(),workers:n({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:n({queued:o().int(),running:o().int()})}),ce=n({machines:d(T)}),de=n({machine:T}),ue=n({deleted:i(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),ge=n({token:n({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),U=ll({machine_id:t().min(1),machine_name:t().min(1)}),he=U.extend({organization_id:t().min(1)}),tn=n({id:t().min(1),name:t().min(1),state:c(["waiting","placed"]),queue_position:o().int().nullable()});var sn=we([n({kind:i("cloud")}),n({kind:c(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function m(e,s,r){let a=e.safeParse(s);if(!a.success)throw new C(502,r,"Reason returned an unexpected response.");return a.data}var pe=n({error:n({type:t(),message:t()})});function b(e,s,r){let a=pe.safeParse(s),l=typeof s.error==="string"?s.error:a.success?a.data.error.type:`http_${e}`,u=typeof s.detail==="string"?s.detail:typeof s.message==="string"?s.message:a.success?a.data.error.message:`Reason request failed (${e}${typeof s.error==="string"?` ${s.error}`:""})`,g=l==="github_connection_required"&&typeof s.connect_url==="string"&&/^https?:\/\//.test(s.connect_url)?` Connect it at ${s.connect_url}`:"",h=r===null||r.trim()===""?NaN:Number(r);return new C(e,l,`${u}${g}`,typeof s.suggested_model==="string"?s.suggested_model:void 0,Number.isFinite(h)&&h>=0?h*1000:void 0,typeof s.resolution_reason==="string"?s.resolution_reason:void 0,typeof s.code==="string"?{code:s.code,...typeof s.billing_path==="string"&&/^\/(?![/\\])/.test(s.billing_path)?{billingPath:s.billing_path}:{}}:void 0)}async function io(e){let s=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),r=await s.json().catch(()=>({}));if(!s.ok)throw b(s.status,r,s.headers.get("retry-after"));return m(he,r,"invalid_machine_ticket")}var fe=n({items:d(n({name:t()}))}),_e=n({name:t(),scope:t(),result:c(["created","updated"]).optional(),warning:n({message:t()}).optional()});class me{options;credentials;constructor(e,s={}){this.options=s;this.credentials=e}trackEvent(e,s={}){}async request(e,s={}){let{status:r,headers:a,json:l}=await this.exchange(e,s);if(r<200||r>299)throw b(r,l,a.get("retry-after"));return l}async exchange(e,s={},r=!1){let a=this.options.fetchImpl??fetch;if(!r&&s.retryUnauthorized!==!1)await this.renewBeforeExpiry(a,s.signal);let l=await a(`${this.credentials.apiOrigin}/v3${e}`,{method:s.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Ir,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...s.raw?{"content-type":s.raw.contentType}:s.body===void 0?{}:{"content-type":"application/json"},...s.headers,...s.ifNoneMatch?{"if-none-match":s.ifNoneMatch}:{}},body:s.raw?s.raw.bytes:s.body===void 0?void 0:JSON.stringify(s.body),signal:s.signal,redirect:s.ifNoneMatch?"manual":"error"}),u=await l.json().catch(()=>({}));if(l.status===401&&!r&&s.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let g=await be({fetchImpl:a,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:s.signal});if(g)return this.credentials=g,this.exchange(e,s,!0)}return{status:l.status,headers:l.headers,json:u}}async renewBeforeExpiry(e,s){let r=this.credentials;if(r.credentialKind==="api_key"||!(Date.parse(r.expiresAt)<=Date.now()+60000))return;let a=await be({fetchImpl:e,path:this.options.credentialsPath,signal:s}).catch(()=>null);if(a&&a.apiOrigin===r.apiOrigin&&a.orgId===r.orgId&&a.clientId===r.clientId)this.credentials=a}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(s){if(s instanceof C&&(s.status===404||s.status===405||s.status===403&&s.code==="endpoint_not_available"))return null;throw s}}addDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(s)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,s=""){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?r:`${r}/${encodeURIComponent(e)}${s}`}async listMachines(){return m(ce,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let s=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return m(de,s,"invalid_machine").machine}async deleteMachine(e){let s=await this.request(this.machinePath(e),{method:"DELETE"});return m(ue,s,"invalid_machine_deletion")}async listSecretNames(e){let s=await this.request(`${this.secretsPath()}?scope=${e}`);return m(fe,s,"invalid_secret_list").items.map((r)=>r.name)}async setSecret(e){let s=await this.request(this.secretsPath(),{method:"POST",body:e});return m(_e,s,"invalid_secret_write")}secretsPath(){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/secrets`}async createMachineToken(e){let s=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return m(ge,s,"invalid_machine_token")}async createMachineEnrollmentTicket(e,s){let r=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:s,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return m(U,r,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(e=AbortSignal.timeout(30000)){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:e})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async registerNetworkTeam(e){await this.request("/network/teams",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:s});return m(Ra,r,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((s)=>typeof s.email==="string"?[{email:s.email,role:typeof s.role==="string"?s.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,s,r={}){let a=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:r.retryUnauthorized,signal:r.signal,body:{...a,...s?{account_key:s}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((s)=>{let r=typeof s.full_name==="string"?s.full_name:typeof s.repo_full_name==="string"?s.repo_full_name:null;if(!r)return[];return[{repo_id:typeof s.repo_id==="string"?s.repo_id:void 0,full_name:r,provider:s.provider==="gitlab"?"gitlab":"github",default_branch:typeof s.default_branch==="string"?s.default_branch:null,private:typeof s.private==="boolean"?s.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),s=Z.safeParse(e);if(!s.success)throw new C(502,"invalid_project_list","Reason returned an unexpected project list.");return s.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return m(ee,e,"invalid_reason_list").items}async openReasonConversation(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return m(n({session_id:t().min(1)}),s,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return m(te,e,"invalid_skill_list").items}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],s=null;for(let r=0;r<50;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${s?`?after=${encodeURIComponent(s)}`:""}`),l=V.safeParse(a);if(!l.success)throw new C(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...l.data.devices),s=l.data.has_next_page?l.data.end_cursor??null:null,!s)break}return e}async listModels(){try{let s=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((l)=>l.hidden!==!0),r=s.filter((l)=>l.available!==!1).map(({reasoning_efforts:l,hidden:u,available:g,...h})=>({...h,...Array.isArray(l)?{reasoning_efforts:J.filter((p)=>l.includes(p))}:{}})),a=new Set(r.map((l)=>l.detail));return{models:r.length>1&&a.size===1?r.map(({detail:l,...u})=>u):r,runnable:r.length>0||s.length===0}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let s=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return k(s.reason_version)?s.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=F.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let s;try{s=G(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:s}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let s=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)s.set("origin",e.origin);s.set("fields",e.fields.join(","));let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${s.toString()}`,{status:a,headers:l,json:u}=await this.exchange(r,e.etag?{ifNoneMatch:e.etag}:{});if(a===304)return null;if(a<200||a>299)throw b(a,u,l.get("retry-after"));return{items:Array.isArray(u.items)?u.items:[],etag:l.get("etag")}}async listSessions(e=50,s,r={}){let a=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:r.status??"active"});if(s)a.set("project_id",s);if(r.origin)a.set("origin",r.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${a.toString()}`)).items??[]}getSession(e,s){let r=s?.fields.length?`?fields=${encodeURIComponent(s.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`)}async prestartSession(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return s?.status==="starting"||s?.status==="ready"}async createSession(e){let s=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(s||e.runtimeProfile){let l=await this.request("/deployment");if(s&&(!Array.isArray(l.session_modes)||!l.session_modes.includes(e.mode??"standard")||!Array.isArray(l.workspace_ownerships)||!l.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(l.experimental_runtime_profiles)||!l.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),a=await this.getSession(r.session_id);if(s){let l=a.session_policy,u=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!l||l.version!==1||l.mode!==(e.mode??"standard")||l.workspaceOwnership!==(e.workspaceOwnership??"managed")||!l.components||u.some((g)=>l.components[g]!==!0))throw await this.cancelSession(r.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&a.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(r.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return a}async getEvents(e,s=-1,r={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${s}&limit=500${r.waitMs?`&wait_ms=${r.waitMs}`:""}`,r.signal?{signal:r.signal}:{})}catch(a){if(!(a instanceof C)||a.status!==403&&a.status!==404)throw a;return{session:await this.getSession(e),items:[],next_seq:s}}}async getMessages(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${s===void 0?"":`&after_seq=${s}`}`)}async getAttachments(e,s){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${s?`?view=${s}`:""}`)).items??[]}catch(r){if(r instanceof C&&(r.status===403||r.status===404))return[];throw r}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let s=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,r=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,a=[s,r].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${a?` (${a})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,s,r={}){if(r.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:s,...r.attachments?.length?{attachments:r.attachments}:{},...r.model?{model:r.model}:{},...r.reasoningEffort?{reasoning_effort:r.reasoningEffort}:{},...r.target?{target:r.target}:{},...r.delivery?{delivery:r.delivery}:{}}})}async steerQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/queued`,{method:"DELETE"})}async getConversation(e){let s=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${r?`?after=${encodeURIComponent(r)}`:""}`);if(s.push(...l.items??[]),!l.has_next_page||!l.end_cursor)break;r=l.end_cursor}return s}createSharedLink(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:s.url,...s.label?{label:s.label}:{},...s.expiresInSeconds!==void 0?{expires_in_seconds:s.expiresInSeconds}:{}}})}sessionAction(e,s,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${s}`,{method:"POST",body:r})}renameSession(e,s){return this.sessionAction(e,"rename",{title:s||null})}moveSessionToProject(e,s){return this.sessionAction(e,"project",{project_id:s})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,s){return this.sessionAction(e,"rewind",{message_id:s.messageId,content:s.content,request_id:s.requestId})}forkSession(e,s){return this.sessionAction(e,"fork",{...s.message?{message:s.message}:{},client_session_id:s.clientSessionId})}cancelSession(e,s={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:s.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,s=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${s}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return m(x,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,s){let r=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:s}});return m(x,r,"invalid_session_tags").tags}async sessionInsight(e,s=!1){let r=await this.request(this.sessionPath(e,s?"/insights/generate":"/insights"),s?{method:"POST",body:{}}:{});return m(ae,r,"invalid_session_insight")}async listAutomations(){let e=[],s=null;for(let r=0;r<20;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${s?`&after=${encodeURIComponent(s)}`:""}`),l=m(oe,a,"invalid_automation_list");if(e.push(...l.items),s=l.has_next_page?l.end_cursor??null:null,!s)break}return e}async createScheduledAutomation(e,s){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,a=m(A,await this.request(r,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${r}/${encodeURIComponent(a.id)}/triggers`,{method:"POST",body:s})}catch(l){throw await this.deleteAutomation(a.id).catch(()=>{return}),l}return a}async setAutomationEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:s}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:s}});return m(n({transcript:t()}),r,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return m(ie,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:s}})}}
|
|
2
|
+
import{Ra}from"./vm-hands-entry-lite-r131db1f.js";import{R}from"./vm-hands-entry-lite-ys4jhf7n.js";import{W}from"./vm-hands-entry-lite-0xfme8gg.js";import{Q,so,ve,ao}from"./vm-hands-entry-lite-4kb5rq3d.js";import{Ir}from"./vm-hands-entry-lite-n9277v11.js";import{t,o,_,d,n,ll,we,c,i}from"./vm-hands-entry-lite-bt6skt4h.js";var E=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function k(e){let s=typeof e==="string"?E.exec(e):null;return s?{major:Number(s[1]),minor:Number(s[2])}:null}import{createHash as q,randomBytes as P}from"crypto";import{createInterface as M}from"readline";var v=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var Ge=v.filter((e)=>e!=="network:read"&&e!=="network:write");class y extends Error{oauthCode;constructor(e,s=null){super(e);this.oauthCode=s;this.name="LoginError"}}function Aa(){let e=P(48).toString("base64url"),s=q("sha256").update(e).digest("base64url");return{verifier:e,challenge:s,state:P(32).toString("base64url")}}function z(e,s){let r=typeof e.error==="string"?e.error:null,a=typeof e.error_description==="string"?e.error_description:r?r:s;return new y(a,r)}async function L(e,s,r,a){let l=await r(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:s,signal:a}),u=await l.json().catch(()=>({}));if(!l.ok)throw z(u,`OAuth token request failed (${l.status})`);return u}var j=1e4;async function D(e,s={}){let r=s.fetchImpl??fetch,a=await L(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),r,AbortSignal.timeout(j)).catch((u)=>{if(u instanceof Error&&u.name==="TimeoutError")throw new y("Reason did not answer the login refresh in time. Check the network and retry.");throw u});if(typeof a.access_token!=="string"||typeof a.refresh_token!=="string"||typeof a.expires_in!=="number")throw new y("Reason returned an incomplete refreshed login.");let l={...e,accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:new Date(Date.now()+a.expires_in*1000).toISOString(),scopes:typeof a.scope==="string"?a.scope.split(/\s+/).filter(Boolean):e.scopes};return so(l,s.path??Q()),l}var w=new Map,N=2000,H=100;function I(e,s){if(!s)return e;if(s.aborted)return Promise.reject(s.reason);return new Promise((r,a)=>{let l=()=>a(s.reason);s.addEventListener("abort",l,{once:!0}),e.then(r,a).finally(()=>s.removeEventListener("abort",l))})}async function be(e={}){let s=e.path??Q(),r=ve(s);if(!r)return null;let a=e.apiOrigin??R(process.env,"REASON_API_URL")?.trim();if(a&&!W(r.apiOrigin,new URL(a).origin))return null;if(!(Date.parse(r.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&r.accessToken!==e.refused))return r;let u=[s,r.apiOrigin,r.clientId,r.refreshToken].join("\x00"),g=w.get(u);if(g)return I(g,e.signal);let h;return h=D(r,{fetchImpl:e.fetchImpl,path:s}).catch(async(p)=>{if(!(p instanceof y)||p.oauthCode!=="invalid_grant"&&p.oauthCode!=="invalid_client")throw p;let S=(f)=>f!==null&&(p.oauthCode==="invalid_client"?f.clientId!==r.clientId:f.refreshToken!==r.refreshToken),O=Date.now()+N;while(!S(ve(s))&&Date.now()<O)await new Promise((f)=>setTimeout(f,H));if(S(ve(s)))return be({fetchImpl:e.fetchImpl,path:s});return ao(s),null}).finally(()=>{if(w.get(u)===h)w.delete(u)}),w.set(u,h),I(h,e.signal)}function Pa(e,s){return new Promise((r)=>{let a=M({input:e}),l=!1,u=(h)=>{if(l)return;l=!0,s.removeEventListener("abort",g),a.close(),e.pause(),r(h)},g=()=>u(null);s.addEventListener("abort",g,{once:!0}),a.once("line",(h)=>u(h)),a.once("close",()=>u(null))})}var F=n({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:_().nullable()}),B=n({groups:d(n({selectable:_().optional(),accounts:d(n({source_id:t().min(1),model_ids:d(t().min(1)).optional()}))}))});function G(e){let s=B.safeParse(e);if(!s.success)return;return s.data.groups.some((r)=>r.selectable!==!1&&r.accounts.some((a)=>a.model_ids===void 0||a.model_ids.length>0))}class C extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;refusal;constructor(e,s,r,a,l,u,g){super(r);this.status=e;this.code=s;this.suggestedModel=a;this.retryAfterMs=l;this.resolutionReason=u;this.refusal=g;this.name="ApiError"}static rateLimitDelayMs(e,s){if(!(e instanceof C)||e.status!==429)return null;return Math.min(60000,Math.max(s,e.retryAfterMs??0))}}var J=["minimal","low","medium","high","xhigh","max"],K=n({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:_(),compatible:_().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:d(n({id:t().min(1),label:t()}))}),V=n({devices:d(K),end_cursor:t().nullish(),has_next_page:_().optional()}),Y=n({id:t().min(1),name:t()}),Z=n({items:d(Y)}),X=n({id:t().min(1),name:t(),main:_(),mine:_(),session_id:t().nullish(),appearance:n({color:t().nullish()}).nullish().catch(null)}),ee=n({items:d(X)}),ne=n({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:d(t()).default([]),is_enabled:_().default(!0)}),te=n({items:d(ne).default([])}),se=n({id:t().min(1),kind:t(),enabled:_(),schedule:n({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:n({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),A=n({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:_(),triggers:d(se).default([])}),oe=n({items:d(A).default([]),end_cursor:t().nullish(),has_next_page:_().optional()}),re=n({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:_()}),ie=n({items:d(re).default([])}),ae=n({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),x=n({tags:d(t()).default([])}),le=c(["linux","macos"]),T=n({id:t().min(1),name:t().min(1),platform:le.nullable(),workers:n({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:n({queued:o().int(),running:o().int()})}),ce=n({machines:d(T)}),de=n({machine:T}),ue=n({deleted:i(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),ge=n({token:n({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),U=ll({machine_id:t().min(1),machine_name:t().min(1)}),he=U.extend({organization_id:t().min(1)}),tn=n({id:t().min(1),name:t().min(1),state:c(["waiting","placed"]),queue_position:o().int().nullable()});var sn=we([n({kind:i("cloud")}),n({kind:c(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function m(e,s,r){let a=e.safeParse(s);if(!a.success)throw new C(502,r,"Reason returned an unexpected response.");return a.data}var pe=n({error:n({type:t(),message:t()})});function b(e,s,r){let a=pe.safeParse(s),l=typeof s.error==="string"?s.error:a.success?a.data.error.type:`http_${e}`,u=typeof s.detail==="string"?s.detail:typeof s.message==="string"?s.message:a.success?a.data.error.message:`Reason request failed (${e}${typeof s.error==="string"?` ${s.error}`:""})`,g=l==="github_connection_required"&&typeof s.connect_url==="string"&&/^https?:\/\//.test(s.connect_url)?` Connect it at ${s.connect_url}`:"",h=r===null||r.trim()===""?NaN:Number(r);return new C(e,l,`${u}${g}`,typeof s.suggested_model==="string"?s.suggested_model:void 0,Number.isFinite(h)&&h>=0?h*1000:void 0,typeof s.resolution_reason==="string"?s.resolution_reason:void 0,typeof s.code==="string"?{code:s.code,...typeof s.billing_path==="string"&&/^\/(?![/\\])/.test(s.billing_path)?{billingPath:s.billing_path}:{}}:void 0)}async function io(e){let s=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),r=await s.json().catch(()=>({}));if(!s.ok)throw b(s.status,r,s.headers.get("retry-after"));return m(he,r,"invalid_machine_ticket")}var fe=n({items:d(n({name:t()}))}),_e=n({name:t(),scope:t(),result:c(["created","updated"]).optional(),warning:n({message:t()}).optional()});class me{options;credentials;constructor(e,s={}){this.options=s;this.credentials=e}trackEvent(e,s={}){}async request(e,s={}){let{status:r,headers:a,json:l}=await this.exchange(e,s);if(r<200||r>299)throw b(r,l,a.get("retry-after"));return l}async exchange(e,s={},r=!1){let a=this.options.fetchImpl??fetch;if(!r&&s.retryUnauthorized!==!1)await this.renewBeforeExpiry(a,s.signal);let l=await a(`${this.credentials.apiOrigin}/v3${e}`,{method:s.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Ir,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...s.raw?{"content-type":s.raw.contentType}:s.body===void 0?{}:{"content-type":"application/json"},...s.headers,...s.ifNoneMatch?{"if-none-match":s.ifNoneMatch}:{}},body:s.raw?s.raw.bytes:s.body===void 0?void 0:JSON.stringify(s.body),signal:s.signal,redirect:s.ifNoneMatch?"manual":"error"}),u=await l.json().catch(()=>({}));if(l.status===401&&!r&&s.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let g=await be({fetchImpl:a,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:s.signal});if(g)return this.credentials=g,this.exchange(e,s,!0)}return{status:l.status,headers:l.headers,json:u}}async renewBeforeExpiry(e,s){let r=this.credentials;if(r.credentialKind==="api_key"||!(Date.parse(r.expiresAt)<=Date.now()+60000))return;let a=await be({fetchImpl:e,path:this.options.credentialsPath,signal:s}).catch(()=>null);if(a&&a.apiOrigin===r.apiOrigin&&a.orgId===r.orgId&&a.clientId===r.clientId)this.credentials=a}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(s){if(s instanceof C&&(s.status===404||s.status===405||s.status===403&&s.code==="endpoint_not_available"))return null;throw s}}addDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(s)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,s=""){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?r:`${r}/${encodeURIComponent(e)}${s}`}async listMachines(){return m(ce,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let s=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return m(de,s,"invalid_machine").machine}async deleteMachine(e){let s=await this.request(this.machinePath(e),{method:"DELETE"});return m(ue,s,"invalid_machine_deletion")}async listSecretNames(e){let s=await this.request(`${this.secretsPath()}?scope=${e}`);return m(fe,s,"invalid_secret_list").items.map((r)=>r.name)}async setSecret(e){let s=await this.request(this.secretsPath(),{method:"POST",body:e});return m(_e,s,"invalid_secret_write")}secretsPath(){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/secrets`}async createMachineToken(e){let s=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return m(ge,s,"invalid_machine_token")}async createMachineEnrollmentTicket(e,s){let r=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:s,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return m(U,r,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(e=AbortSignal.timeout(30000)){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:e})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async registerNetworkTeam(e){await this.request("/network/teams",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:s});return m(Ra,r,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((s)=>typeof s.email==="string"?[{email:s.email,role:typeof s.role==="string"?s.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,s,r={}){let a=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:r.retryUnauthorized,signal:r.signal,body:{...a,...s?{account_key:s}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((s)=>{let r=typeof s.full_name==="string"?s.full_name:typeof s.repo_full_name==="string"?s.repo_full_name:null;if(!r)return[];return[{repo_id:typeof s.repo_id==="string"?s.repo_id:void 0,full_name:r,provider:s.provider==="gitlab"?"gitlab":"github",default_branch:typeof s.default_branch==="string"?s.default_branch:null,private:typeof s.private==="boolean"?s.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),s=Z.safeParse(e);if(!s.success)throw new C(502,"invalid_project_list","Reason returned an unexpected project list.");return s.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return m(ee,e,"invalid_reason_list").items}async openReasonConversation(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return m(n({session_id:t().min(1)}),s,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return m(te,e,"invalid_skill_list").items}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],s=null;for(let r=0;r<50;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${s?`?after=${encodeURIComponent(s)}`:""}`),l=V.safeParse(a);if(!l.success)throw new C(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...l.data.devices),s=l.data.has_next_page?l.data.end_cursor??null:null,!s)break}return e}async listModels(){try{let s=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((l)=>l.hidden!==!0),r=s.filter((l)=>l.available!==!1).map(({reasoning_efforts:l,hidden:u,available:g,...h})=>({...h,...Array.isArray(l)?{reasoning_efforts:J.filter((p)=>l.includes(p))}:{}})),a=new Set(r.map((l)=>l.detail));return{models:r.length>1&&a.size===1?r.map(({detail:l,...u})=>u):r,runnable:r.length>0||s.length===0}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let s=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return k(s.reason_version)?s.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=F.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let s;try{s=G(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:s}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let s=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)s.set("origin",e.origin);s.set("fields",e.fields.join(","));let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${s.toString()}`,{status:a,headers:l,json:u}=await this.exchange(r,e.etag?{ifNoneMatch:e.etag}:{});if(a===304)return null;if(a<200||a>299)throw b(a,u,l.get("retry-after"));return{items:Array.isArray(u.items)?u.items:[],etag:l.get("etag")}}async listSessions(e=50,s,r={}){let a=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:r.status??"active"});if(s)a.set("project_id",s);if(r.origin)a.set("origin",r.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${a.toString()}`)).items??[]}getSession(e,s){let r=s?.fields.length?`?fields=${encodeURIComponent(s.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`)}async prestartSession(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return s?.status==="starting"||s?.status==="ready"}async createSession(e){let s=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(s||e.runtimeProfile){let l=await this.request("/deployment");if(s&&(!Array.isArray(l.session_modes)||!l.session_modes.includes(e.mode??"standard")||!Array.isArray(l.workspace_ownerships)||!l.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(l.experimental_runtime_profiles)||!l.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),a=await this.getSession(r.session_id);if(s){let l=a.session_policy,u=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!l||l.version!==1||l.mode!==(e.mode??"standard")||l.workspaceOwnership!==(e.workspaceOwnership??"managed")||!l.components||u.some((g)=>l.components[g]!==!0))throw await this.cancelSession(r.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&a.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(r.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return a}async getEvents(e,s=-1,r={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${s}&limit=500${r.waitMs?`&wait_ms=${r.waitMs}`:""}`,r.signal?{signal:r.signal}:{})}catch(a){if(!(a instanceof C)||a.status!==403&&a.status!==404)throw a;return{session:await this.getSession(e),items:[],next_seq:s}}}async getMessages(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${s===void 0?"":`&after_seq=${s}`}`)}async getAttachments(e,s){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${s?`?view=${s}`:""}`)).items??[]}catch(r){if(r instanceof C&&(r.status===403||r.status===404))return[];throw r}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let s=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,r=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,a=[s,r].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${a?` (${a})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,s,r={}){if(r.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:s,...r.attachments?.length?{attachments:r.attachments}:{},...r.model?{model:r.model}:{},...r.reasoningEffort?{reasoning_effort:r.reasoningEffort}:{},...r.target?{target:r.target}:{},...r.delivery?{delivery:r.delivery}:{}}})}async steerQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/queued`,{method:"DELETE"})}async getConversation(e){let s=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${r?`?after=${encodeURIComponent(r)}`:""}`);if(s.push(...l.items??[]),!l.has_next_page||!l.end_cursor)break;r=l.end_cursor}return s}createSharedLink(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:s.url,...s.label?{label:s.label}:{},...s.expiresInSeconds!==void 0?{expires_in_seconds:s.expiresInSeconds}:{}}})}sessionAction(e,s,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${s}`,{method:"POST",body:r})}renameSession(e,s){return this.sessionAction(e,"rename",{title:s||null})}moveSessionToProject(e,s){return this.sessionAction(e,"project",{project_id:s})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,s){return this.sessionAction(e,"rewind",{message_id:s.messageId,content:s.content,request_id:s.requestId})}forkSession(e,s){return this.sessionAction(e,"fork",{...s.message?{message:s.message}:{},client_session_id:s.clientSessionId})}cancelSession(e,s={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:s.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,s=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${s}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return m(x,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,s){let r=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:s}});return m(x,r,"invalid_session_tags").tags}async sessionInsight(e,s=!1){let r=await this.request(this.sessionPath(e,s?"/insights/generate":"/insights"),s?{method:"POST",body:{}}:{});return m(ae,r,"invalid_session_insight")}async listAutomations(){let e=[],s=null;for(let r=0;r<20;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${s?`&after=${encodeURIComponent(s)}`:""}`),l=m(oe,a,"invalid_automation_list");if(e.push(...l.items),s=l.has_next_page?l.end_cursor??null:null,!s)break}return e}async createScheduledAutomation(e,s){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,a=m(A,await this.request(r,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${r}/${encodeURIComponent(a.id)}/triggers`,{method:"POST",body:s})}catch(l){throw await this.deleteAutomation(a.id).catch(()=>{return}),l}return a}async setAutomationEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:s}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:s}});return m(n({transcript:t()}),r,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return m(ie,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:s}})}}
|
|
3
3
|
export{Aa,be,Pa,C,io,me};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{R}from"./vm-hands-entry-lite-ys4jhf7n.js";import{w}from"./vm-hands-entry-lite-0xfme8gg.js";import{ot,cs,Mi,We}from"./vm-hands-entry-lite-8twdd0ff.js";import{ms,$n,jc}from"./vm-hands-entry-lite-
|
|
2
|
+
import{R}from"./vm-hands-entry-lite-ys4jhf7n.js";import{w}from"./vm-hands-entry-lite-0xfme8gg.js";import{ot,cs,Mi,We}from"./vm-hands-entry-lite-8twdd0ff.js";import{ms,$n,jc}from"./vm-hands-entry-lite-2qh3rat2.js";import{B}from"./vm-hands-entry-lite-04nx5y4f.js";import{spawnSync as v}from"child_process";import{createHash as Se,randomUUID as we}from"crypto";import{chmodSync as $e,existsSync as T,mkdirSync as ye,readdirSync as Fe,readFileSync as p,renameSync as ve,rmSync as u,statSync as be,writeFileSync as Ae}from"fs";import{dirname as xe,isAbsolute as q,join as g}from"path";import{spawnSync as ue}from"child_process";import{readFileSync as me}from"fs";import{userInfo as O}from"os";import{join as fe}from"path";var ge="REASON_SCHEDULED_TASK";function Ni(r){return fe(r,"AppData","Local","Reason","Tasks")}function S(r){if(/[\0-\x1f\x7f"%]/.test(r))throw Error(`A background task cannot use a value with a double quote, percent sign or control character: ${r}`);return`'${r.replace(/['\u2018\u2019\u201a\u201b]/g,"$&$&")}'`}function D(r){if(!/^[A-Za-z0-9._-]+$/.test(r))throw Error(`Invalid Windows Scheduled Task name: ${r}`);return`$env:${ge}=${S(r)};`}function H(r){let e=Object.entries(r.environment).map(([t,i])=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw Error(`Invalid Windows Scheduled Task environment name: ${t}`);return`$env:${t}=${S(i)};`}),n=`$global:LASTEXITCODE=1; & ${[r.program,...r.args].map(S).join(" ")} 2>&1 | ForEach-Object { Add-Content -LiteralPath ${S(r.log)} -Value $_.ToString() -Encoding UTF8 }; $c=$LASTEXITCODE;`;return[D(r.name),...e,"$ErrorActionPreference='Continue';",r.keepAlive?`do { ${n} if ($c) { Start-Sleep -Seconds 10 } } while ($c)`:`${n} exit $c`].join(" ")}function I(r){return r.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function pe(){let r=process.env.USERDOMAIN?.trim();return r?`${r}\\${O().username}`:O().username}function M(r){let e=I(r.user??pe()),n=r.schedule==="logon",t=r.schedule==="logon"?`<LogonTrigger><Enabled>true</Enabled><UserId>${e}</UserId></LogonTrigger>`:`<TimeTrigger><Repetition><Interval>PT${r.schedule.everyMinutes}M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition><StartBoundary>2026-01-01T00:00:00</StartBoundary><Enabled>true</Enabled></TimeTrigger>`,i=`-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -Command "${r.script}"`;return`<?xml version="1.0" encoding="UTF-16"?>
|
|
3
3
|
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
4
4
|
<RegistrationInfo>
|
|
5
5
|
<Description>${I(r.description)}</Description>
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var Mn={name:"github-native-engineer-device-worker-production",version:"0.2.
|
|
2
|
+
var Mn={name:"github-native-engineer-device-worker-production",version:"0.2.568",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@agentclientprotocol/sdk":"1.9.0","@anthropic-ai/sandbox-runtime":"^0.0.80","@earendil-works/pi-tui":"1.0.0","@reason/runtime-distribution":"workspace:*",diff:"8.0.4","open-browser-use-sdk":"0.1.42","playwright-core":"1.60.0",toml:"5.0.1",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.4",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^5.0.1",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
|
|
3
3
|
export{Mn};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{R}from"./vm-hands-entry-lite-ys4jhf7n.js";import{ji,Hi,St,Yt,gs,_s}from"./vm-hands-entry-lite-
|
|
2
|
+
import{R}from"./vm-hands-entry-lite-ys4jhf7n.js";import{ji,Hi,St,Yt,gs,_s}from"./vm-hands-entry-lite-2qh3rat2.js";import{uc,dc}from"./vm-hands-entry-lite-chve4vmh.js";import{Ii,Di,vn,yr,l,mc,Oi,gc,Sn,Gt,En}from"./vm-hands-entry-lite-sb1xtqxr.js";import{s}from"./vm-hands-entry-lite-tzv8s0e7.js";import{G}from"./vm-hands-entry-lite-04nx5y4f.js";import{randomUUID as L}from"crypto";import{chmodSync as Z,closeSync as J,constants as C,existsSync as S,fstatSync as ke,lstatSync as h,mkdirSync as q,openSync as Ie,readFileSync as K,readdirSync as re,readlinkSync as w,realpathSync as x,renameSync as k,rmSync as T,statSync as V,symlinkSync as Q,unlinkSync as p,writeFileSync as U}from"fs";import{basename as H,dirname as E,isAbsolute as je,join as m,relative as We,resolve as M,sep as me}from"path";import{spawnSync as ee}from"child_process";import{createRequire as Te}from"module";var ae=1,xe=1,Xe=128,Qe=65536,Qc="https://reasonmachines.com/api/runtime-manifest-v2",et=30000,tt=600000,Ee=1e4,nt=60000,rt=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;var Me=/^[a-z0-9_.-]{1,80}$/,it=64,at="so.ara.device-broker",Pe=[at,"com.reasonmachines.device-broker"],Ln=Hi(Pe),we=["com.apple.security.cs.allow-jit","com.apple.security.cs.allow-unsigned-executable-memory"],ot=["service.install_started","service.install_completed","service.install_failed","service.launcher_adopted","service.launcher_conflict","service.started","service.reconnecting","service.reconnected","service.idle_sleep_held","service.idle_sleep_released","service.idle_sleep_failed","service.start_failed","service.stopped","service.exit_failed","service.singleton_rejected","credential.migration_started","credential.migration_completed","credential.migration_failed","credential.store_started","credential.store_completed","credential.store_failed","credential.delete_started","credential.delete_completed","credential.delete_failed","update.check_started","update.not_available","update.download_started","update.downloaded","update.verified","update.activated","update.rollback","update.failed","executor.update.check_started","executor.update.not_available","executor.update.download_started","executor.update.downloaded","executor.update.verified","executor.update.activated","executor.update.rollback","executor.update.failed","identity.refresh_completed","identity.refresh_failed","update.device_moved","update.components_installed","update.deferred","update.deferral_expired","worker.previous_exit","worker.capabilities_withheld","identity.computer_use_unavailable"];function W(e){if(e?.aborted)throw new l("update_cancelled","Managed runtime update request was cancelled.")}function fe(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function ge(e,t,n=[]){let r=new Set([...t,...n]);return t.every((i)=>(i in e))&&Object.keys(e).every((i)=>r.has(i))}function b(e){return typeof e==="string"&&rt.test(e)}function De(e){return typeof e==="string"&&!Number.isNaN(Date.parse(e))&&new Date(e).toISOString()===e}function st(e){return yr.includes(e)}function P(e){q(e,{recursive:!0,mode:448}),Z(e,448)}function Oe(e,t){P(E(e));let n=`${e}.${process.pid}.${L()}.tmp`;try{U(n,t,{mode:384,flag:"wx"}),Z(n,384),k(n,e)}finally{if(S(n))p(n)}}function Lt(e={}){if((e.platform??process.platform)!=="darwin")throw new l("unsupported_platform","The managed Reason runtime is currently available only on macOS.");let n=e.environment??process.env,r=R(n,"REASON_CLI_CHANNEL")==="staging",i=r?R(n,"REASON_MANAGED_RUNTIME_ROOT")?.trim():void 0,o=e.root!==void 0||Boolean(i&&je(i))?null:m(e.home??s(),"Library","Application Support"),c=e.root??(o?m(o,r?"Reason Staging":"Reason","CLI"):i);return{executableName:"reason",root:c,...o?{legacyRoot:m(o,"Ara",...r?["staging","runtime"]:["runtime"])}:{},versions:m(c,"versions"),current:m(c,"current"),previous:m(c,"previous"),brokerLock:m(c,"broker.lock"),transitionLock:m(c,"transition.lock"),lifecycleEvents:m(c,"lifecycle-events")}}function bl(e){let t=e.legacyRoot;if(!t)return null;return{root:t,versions:m(t,"versions"),current:m(t,"current"),previous:m(t,"previous"),brokerLock:m(t,"broker.lock"),transitionLock:m(t,"transition.lock"),lifecycleEvents:m(t,"lifecycle-events")}}function F(e,t){if(!b(t))throw new l("invalid_version","Invalid managed Reason runtime version.");let n=m(e.versions,t,"ara");if(!e.executableName)return n;let r=m(e.versions,t,e.executableName),i=(c)=>{try{return h(c),!0}catch(d){if(d.code==="ENOENT")return!1;throw d}},a=i(n),o=i(r);if(a&&o)throw new l("installed_artifact_mismatch","Ambiguous managed runtime executable layout.");return a?n:r}function oe(e,t){if(!b(t))throw new l("invalid_version","Invalid managed Reason runtime version.");return _e(F(e,t))}function _e(e){return m(E(e),H(e)==="reason"?Di:Ii)}function Ce(e,t){if(!b(e)||!b(t))throw new l("invalid_version","Invalid managed Reason runtime version.");let[n,r]=e.split("-",2),[i,a]=t.split("-",2),o=n.split(".").map(Number),c=i.split(".").map(Number);for(let _=0;_<3;_+=1){let g=o[_]-c[_];if(g!==0)return g<0?-1:1}if(r===void 0||a===void 0){if(r===a)return 0;return r===void 0?1:-1}let d=r.split("."),u=a.split("."),f=Math.max(d.length,u.length);for(let _=0;_<f;_+=1){let g=d[_],y=u[_];if(g===void 0||y===void 0){if(g===y)return 0;return g===void 0?-1:1}if(g===y)continue;let v=/^\d+$/.test(g),A=/^\d+$/.test(y);if(v&&A)return Number(g)<Number(y)?-1:1;if(v!==A)return v?-1:1;return g<y?-1:1}return 0}function ct(e=process.arch){let t=`darwin-${e}`;if(!st(t))throw new l("unsupported_architecture","The managed Reason runtime supports only Apple Silicon and Intel Macs.");return t}function Re(e){return[...e.matchAll(/<key>\s*([^<]+?)\s*<\/key>/g)].map((t)=>t[1].trim())}function pe(e){let t=e.match(/^CodeDirectory .*$/gm)??[];return t.length>0&&t.every((n)=>(/ flags=0x[0-9a-f]+\(([^)]*)\)(?: |$)/.exec(n)?.[1]?.split(/[ ,]+/).filter(Boolean)??[]).includes("runtime"))}function lt(e){let t=`TeamIdentifier=${ji}`,n=Pe.map((a)=>`Identifier=${a}`),r=Re(e.brokerEntitlements),i=Re(e.credentialLibraryEntitlements);if(!e.brokerDetail.split(`
|
|
3
3
|
`).includes(t)||!e.brokerDetail.split(`
|
|
4
4
|
`).some((a)=>n.includes(a))||!pe(e.brokerDetail)||r.length!==we.length||we.some((a)=>!new RegExp(`<key>\\s*${a.replaceAll(".","\\.")}\\s*</key>\\s*<true\\s*/>`).test(e.brokerEntitlements)))throw new l("invalid_code_signature","Managed runtime broker has an invalid Reason signature, identifier, or entitlement set.");if(!e.credentialLibraryDetail.split(`
|
|
5
5
|
`).includes(t)||!pe(e.credentialLibraryDetail)||i.length!==0)throw new l("invalid_code_signature","Managed runtime credential library has an invalid signature or entitlement.")}function D(e,t){let n=ee("/usr/bin/codesign",e,{stdio:["ignore","pipe","pipe"]});if(n.status!==0)throw new l("invalid_code_signature",t);return[new TextDecoder().decode(n.stdout??new Uint8Array),new TextDecoder().decode(n.stderr??new Uint8Array)].join("")}var ye=(e,t)=>{D(["--verify","--strict","--verbose=2",e],"Managed runtime broker code signature is invalid."),D(["--verify","--strict","--verbose=2",t],"Managed runtime credential library code signature is invalid."),lt({brokerDetail:D(["-d","--verbose=4",e],"Managed runtime broker signer could not be inspected."),brokerEntitlements:D(["-d","--entitlements",":-",e],"Managed runtime broker entitlements could not be inspected."),credentialLibraryDetail:D(["-d","--verbose=4",t],"Managed runtime credential library signer could not be inspected."),credentialLibraryEntitlements:D(["-d","--entitlements",":-",t],"Managed runtime credential library entitlements could not be inspected.")})};async function dt(e,t,n){let r=e.headers.get("content-length");if(r!==null){let f=Number(r);if(!Number.isSafeInteger(f)||f<0||f>t)throw new l("response_too_large","Managed runtime response exceeded its size limit.")}if(!e.body){let f=new Uint8Array(await e.arrayBuffer());if(f.byteLength>t)throw new l("response_too_large","Managed runtime response exceeded its size limit.");return f}let i=e.body.getReader(),a=[],o=0,c=()=>{if(!n)return i.read();return new Promise((f,_)=>{let g=()=>{n.removeEventListener("abort",g),i.cancel(n.reason).catch(()=>{}),_(n.reason??new DOMException("Aborted","AbortError"))};if(n.aborted){g();return}n.addEventListener("abort",g,{once:!0}),i.read().then((y)=>{n.removeEventListener("abort",g),f(y)},(y)=>{n.removeEventListener("abort",g),_(y)})})};try{while(!0){let f=await c();if(f.done)break;if(o+=f.value.byteLength,o>t)throw await i.cancel(),new l("response_too_large","Managed runtime response exceeded its size limit.");a.push(f.value)}}finally{try{i.releaseLock()}catch{}}let d=new Uint8Array(o),u=0;for(let f of a)d.set(f,u),u+=f.byteLength;return d}async function Yr(e){let t;try{t=new URL(e.url)}catch{throw new l("invalid_update_url","Managed runtime update URL is invalid.")}if(t.protocol!=="https:"||t.username||t.password||t.hash)throw new l("invalid_update_url","Managed runtime update URL must use HTTPS.");let n=new AbortController,r,i=()=>{r??="caller",n.abort(e.signal?.reason)};if(e.signal?.aborted)i();else e.signal?.addEventListener("abort",i,{once:!0});let a=setTimeout(()=>{r??="timeout",n.abort(Error("managed runtime fetch timed out"))},e.timeoutMs),o=(c,d)=>{if(c instanceof l)return c;if(r==="caller")return new l("update_cancelled","Managed runtime update request was cancelled.");if(r==="timeout")return new l("update_fetch_timeout","Managed runtime update request timed out.");return new l("update_fetch_failed",d)};try{let c;try{if(c=await e.fetchImpl(t,{headers:{accept:e.accept},signal:n.signal}),n.signal.aborted)throw o(n.signal.reason,"Managed runtime update request was cancelled.")}catch(d){throw o(d,"Managed runtime update request failed.")}if(!c.ok)throw new l("update_http_error","Managed runtime update request was rejected.");if(c.url&&new URL(c.url).protocol!=="https:")throw new l("insecure_redirect","Managed runtime update redirected to an insecure URL.");try{let d=await dt(c,e.maximumBytes,n.signal);if(n.signal.aborted)throw o(n.signal.reason,"Managed runtime update response was cancelled.");return d}catch(d){throw o(d,"Managed runtime update response failed.")}}finally{clearTimeout(a),e.signal?.removeEventListener("abort",i)}}async function Ve(e,t,n=Ee,r){let i=typeof n==="number"?n:Ee,a=typeof n==="number"?r:n;if(a?.aborted)return!1;let o=await uc([e,"--version"],{timeoutMs:i,...a?{signal:a}:{}});return o.exitCode===0&&o.stdout.trim().replace(/^v/,"")===t}async function ut(e){let t=!1,n=null,r=null,i=(a)=>{try{N(e.paths,a,{now:e.now})}catch{}};try{let a=e.home??s();if(!gs(e.manifest.version,a))return{status:"current"};r=Yt(a);let o=await Yr({url:new URL(mc,e.manifest.artifacts[e.target].broker.url).toString(),maximumBytes:vn,fetchImpl:async(g,y)=>{let v=await e.fetchImpl(g,y);return t=v.status===404,v},timeoutMs:e.timeoutMs,accept:"application/json",signal:e.signal}),{manifest:c}=gc(new TextDecoder().decode(o),e.trustedKeys);if(c.version!==e.manifest.version||c.published_at!==e.manifest.published_at)throw new l("identity_manifest_mismatch","Background identity manifest names another release.");let d=c.artifacts[e.target],u=await Yr({url:d.url,maximumBytes:d.size_bytes,fetchImpl:e.fetchImpl,timeoutMs:e.timeoutMs,accept:"application/octet-stream",signal:e.signal});Gt(u,d),P(e.workDirectory),n=m(e.workDirectory,`.identity-${process.pid}-${L()}`),q(n,{mode:448});let f=m(n,"identity.tgz");if(U(f,u,{mode:384,flag:"wx"}),ee("/usr/bin/tar",["-xzf",f,"-C",n],{stdio:"ignore",timeout:60000}).status!==0)throw new l("identity_extract_failed","Background identity archive could not be extracted.");return _s({sourceApp:m(n,"Reason.app"),home:a,releaseSigned:!0,...e.command?{command:e.command}:{}}),i({event:"identity.refresh_completed",runtime_version:e.manifest.version,...r?{from_version:r}:{},to_version:e.manifest.version}),{status:"installed"}}catch(a){if(t)return{status:"unpublished"};let o=a instanceof l||a instanceof St?a.code:"identity_install_failed";return process.stderr.write(`Reason background identity: identity_update_failed (${o})
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{us,ds,Mc,On}from"./vm-hands-entry-lite-hh0kba1y.js";import{A}from"./vm-hands-entry-lite-
|
|
2
|
+
import{us,ds,Mc,On}from"./vm-hands-entry-lite-hh0kba1y.js";import{A}from"./vm-hands-entry-lite-9meg54bs.js";import{Ue,wr,br}from"./vm-hands-entry-lite-g0bpdyfz.js";import{qr}from"./vm-hands-entry-lite-t3k90kdn.js";import{Go,Kt,_c,Ko,Jo,Xo,Jt}from"./vm-hands-entry-lite-ksfd234v.js";import{vi}from"./vm-hands-entry-lite-3594pdj0.js";import{Se}from"./vm-hands-entry-lite-1as6h9ed.js";import{s}from"./vm-hands-entry-lite-tzv8s0e7.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as se,spawn as ce}from"child_process";import{randomBytes as qe}from"crypto";import{chmodSync as Ce,existsSync as ne,lstatSync as Ge,mkdirSync as Oe,readFileSync as S,rmSync as ae,writeFileSync as R}from"fs";import{connect as he}from"net";import{join as p}from"path";var B=32,N=76;var M="./desktop-wallpaper-fd8f2wb2.jpg";var v="./dock-browser-y53t41cx.png";var Z="./dock-files-cp52htdw.png";var V="./dock-terminal-1es514yq.png";var z="./grok-wallpaper-71zwn2pj.jpg";var W="./grok-dock-browser-pzw59wnd.png";var j="./grok-dock-files-eckq444x.png";var U="./grok-dock-terminal-hcpz3e43.png";var ee=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
|
|
3
3
|
# The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
|
|
4
4
|
# python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
|
|
5
5
|
# Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{D,On,ps,Pr,hs,fs}from"./vm-hands-entry-lite-hh0kba1y.js";import{wc,bc,A,Qo}from"./vm-hands-entry-lite-
|
|
2
|
+
import{D,On,ps,Pr,hs,fs}from"./vm-hands-entry-lite-hh0kba1y.js";import{wc,bc,A,Qo}from"./vm-hands-entry-lite-9meg54bs.js";import{Ue}from"./vm-hands-entry-lite-g0bpdyfz.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as xt,spawn as _e}from"child_process";import{existsSync as vt}from"fs";import{connect as Et}from"net";function dt(){let e=new Set,t=null,s=(n)=>({holder:t?.viewer??null,you:t===n,same_user:Boolean(t?.viewer&&n.viewer&&t.viewer.user_id===n.viewer.user_id)}),i=()=>{for(let n of e)n.notify(s(n))};return{join(n){return e.add(n),n.notify(s(n)),()=>{if(!e.delete(n))return;if(t!==n)return;t=null,i()}},claim(n){if(t===n||!e.has(n))return;t=n,i()}}}var Ce=dt();import{spawn as pt}from"child_process";import{existsSync as ft}from"fs";import{connect as mt}from"net";import{join as j}from"path";var ze="reason_desktop",N={sampleRate:48000,channels:2,codec:"opus"},ht=5000,yt=107,gt=262144,Go=(e)=>j(e,"native"),Kt=(e)=>`unix:${e}`;function he(e,t=1000){if(!ft(e))return Promise.resolve(!1);return new Promise((s)=>{let i=mt({path:e}),n=(l)=>{i.destroy(),s(l)};i.setTimeout(t,()=>n(!1)),i.once("error",()=>n(!1)),i.once("close",()=>n(!1)),i.once("connect",()=>n(!0))})}async function _c(e,t){if(!t)return null;let s=Go(e);if(Buffer.byteLength(s)>yt||/["'\\\s]/.test(s))return null;try{if(await he(s))return s;let i=pt(t,["--daemonize=no","--system=no","--use-pid-file=no","--exit-idle-time=-1","--disallow-exit=yes","--realtime=no","--high-priority=no","--disallow-module-loading=yes","--log-level=warning",`--log-target=file:${j(e,"pulseaudio.log")}`,"-n",`--load=module-native-protocol-unix socket="${s}" auth-anonymous=1 auth-cookie-enabled=0`,`--load=module-null-sink sink_name=${ze} rate=${N.sampleRate} channels=${N.channels} sink_properties=device.description=Reason_desktop`],{detached:!0,stdio:"ignore",env:{HOME:e,PATH:"/usr/bin:/bin",XDG_RUNTIME_DIR:e,PULSE_RUNTIME_PATH:j(e,"runtime"),PULSE_STATE_PATH:j(e,"state")}});Ue(i.pid);let n=!1;i.once("error",()=>{n=!0}),i.once("exit",()=>{n=!0}),i.unref();let l=Date.now()+ht;while(Date.now()<l){if(await he(s))return s;if(n)return await he(s)?s:null;await new Promise((c)=>setTimeout(c,50))}if(!n)i.kill("SIGKILL");return null}catch{return null}}function Oe(){let{sampleRate:e,channels:t}=N;return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer","-f","pulse","-sample_rate",String(e),"-channels",String(t),"-fragment_size",String(e*t*2/50),"-i",`${ze}.monitor`,"-vn","-ac",String(t),"-ar",String(e),"-c:a","libopus","-b:a","64k","-application","lowdelay","-frame_duration","20","-flush_packets","1","-page_duration","20000","-f","ogg","pipe:1"]}var bt=[79,103,103,83],wt=Buffer.from("OpusHead"),_t=Buffer.from("OpusTags"),Be=(e,t)=>e.byteLength>=t.byteLength&&t.every((s,i)=>e[i]===s);class ye extends Error{constructor(e){super(e);this.name="OggProtocolError"}}class ge{buffer=new Uint8Array(0);partial=[];partialBytes=0;push(e){let t=new Uint8Array(this.buffer.byteLength+e.byteLength);t.set(this.buffer),t.set(e,this.buffer.byteLength);let s=[],i=0;while(t.byteLength-i>=27){if(bt.some((b,f)=>t[i+f]!==b)||t[i+4]!==0)throw new ye("invalid_page");let n=(t[i+5]&1)!==0,l=t[i+26];if(t.byteLength-i<27+l)break;let c=t.subarray(i+27,i+27+l),h=c.reduce((b,f)=>b+f,0),g=27+l+h;if(t.byteLength-i<g)break;if(!n&&this.partialBytes>0)this.resetPartial();let m=n&&this.partialBytes===0,p=i+27+l,w=p;for(let b of c){if(p+=b,b===255)continue;if(this.appendPartial(t.subarray(w,p),m),w=p,!m){let f=this.takePartial();if(f.byteLength>0&&!Be(f,wt)&&!Be(f,_t))s.push(f)}m=!1,this.resetPartial()}if(w<p)this.appendPartial(t.subarray(w,p),m);i+=g}return this.buffer=t.slice(i),s}appendPartial(e,t){if(t||e.byteLength===0)return;if(this.partialBytes+=e.byteLength,this.partialBytes>gt)throw new ye("packet_too_large");this.partial.push(e.slice())}takePartial(){if(this.partial.length===1)return this.partial[0];let e=new Uint8Array(this.partialBytes),t=0;for(let s of this.partial)e.set(s,t),t+=s.byteLength;return e}resetPartial(){this.partial=[],this.partialBytes=0}}import{spawn as kt}from"child_process";var Ve=1048576,St=String.raw`
|
|
3
3
|
import gi, json, os, sys
|
|
4
4
|
gi.require_version("Gtk", "3.0")
|
|
5
5
|
from gi.repository import Gtk, Gdk, GLib
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Xt,yc,le,Sr,Er,A}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Xt,yc,le,Sr,Er,A}from"./vm-hands-entry-lite-9meg54bs.js";import{ue}from"./vm-hands-entry-lite-t2rhwchw.js";import{Rr}from"./vm-hands-entry-lite-hh0kba1y.js";import{Tr}from"./vm-hands-entry-lite-2qh3rat2.js";import{Fi}from"./vm-hands-entry-lite-bcz4qpp6.js";import{Ue,wr,br,Zo}from"./vm-hands-entry-lite-g0bpdyfz.js";import{Kt}from"./vm-hands-entry-lite-ksfd234v.js";import{qr,va}from"./vm-hands-entry-lite-t3k90kdn.js";import{Te,jt}from"./vm-hands-entry-lite-jm9jpj77.js";import{de,ze}from"./vm-hands-entry-lite-ezkb7f6j.js";import{$r}from"./vm-hands-entry-lite-vvhfaxpd.js";import{s}from"./vm-hands-entry-lite-tzv8s0e7.js";import{B}from"./vm-hands-entry-lite-04nx5y4f.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{spawn as S,spawnSync as De}from"child_process";import{createHash as Le,randomUUID as re}from"crypto";import{closeSync as $e,copyFileSync as J,existsSync as C,fstatSync as Be,mkdirSync as z,openSync as We,readdirSync as N,readFileSync as W,readlinkSync as qe,renameSync as ne,rmSync as Fe,statSync as He,writeFileSync as Ge}from"fs";import{connect as je}from"net";import{tmpdir as P,userInfo as ie}from"os";import{basename as V,delimiter as Xe,dirname as M,join as m}from"path";var q=`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";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{gt,gr,Se}from"./vm-hands-entry-lite-1as6h9ed.js";import{at,kt,Oe,xt,Ke,Dr,Zt,Ne,X,te,Vi}from"./vm-hands-entry-lite-hpw27zfb.js";import{Pn,Cr}from"./vm-hands-entry-lite-0xfme8gg.js";import{pc,F,qt,_t,Wt,He,Vt,qo,yt,bn,nt,Ee,ce,it,Ri,Ti,Vo}from"./vm-hands-entry-lite-bc9zq8gx.js";import{Ct,Je,ct,Le,Pt,xe,pe}from"./vm-hands-entry-lite-vvhfaxpd.js";import{cn,mi,dr,Re,U,H,T,To}from"./vm-hands-entry-lite-bbjsnjct.js";import{Ft,_i,Do,lc,je,Oo}from"./vm-hands-entry-lite-732hnx41.js";import{ue}from"./vm-hands-entry-lite-t2rhwchw.js";import{ba}from"./vm-hands-entry-lite-t3k90kdn.js";import{v,Bt,ln,pr,oc,ht,ft}from"./vm-hands-entry-lite-sxnvhzy5.js";import{b,m,y}from"./vm-hands-entry-lite-2927z566.js";import{L}from"./vm-hands-entry-lite-hpe54h0b.js";import{Mn}from"./vm-hands-entry-lite-dtw6cj95.js";import{s,Uc,zc,Ge,Wc}from"./vm-hands-entry-lite-tzv8s0e7.js";import{he,ma,ga,Xc,I,t,V,zr,o,_,d,n,h,P,$e,c,i}from"./vm-hands-entry-lite-bt6skt4h.js";import{ya}from"./vm-hands-entry-lite-1sy80ca9.js";import{Zc,Ye,Ea,B,It,Be,G}from"./vm-hands-entry-lite-04nx5y4f.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{readFileSync as ho,realpathSync as mo,statSync as Ni}from"fs";import{homedir as Li}from"os";import{dirname as Bi,isAbsolute as ji,join as dt,sep as Mi}from"path";var Hi=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function a(f){return e[f]??null}let l={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},u={nan:"NaN"};return(f)=>{switch(f.code){case"invalid_type":{let g=u[f.expected]??f.expected,k=Xc(f.input),R=u[k]??k;return`Invalid input: expected ${g}, received ${R}`}case"invalid_value":if(f.values.length===1)return`Invalid input: expected ${ga(f.values[0])}`;return`Invalid option: expected one of ${ma(f.values,"|")}`;case"too_big":{let g=f.inclusive?"<=":"<",k=a(f.origin);if(k)return`Too big: expected ${f.origin??"value"} to have ${g}${f.maximum.toString()} ${k.unit??"elements"}`;return`Too big: expected ${f.origin??"value"} to be ${g}${f.maximum.toString()}`}case"too_small":{let g=f.inclusive?">=":">",k=a(f.origin);if(k)return`Too small: expected ${f.origin} to have ${g}${f.minimum.toString()} ${k.unit}`;return`Too small: expected ${f.origin} to be ${g}${f.minimum.toString()}`}case"invalid_format":{let g=f;if(g.format==="starts_with")return`Invalid string: must start with "${g.prefix}"`;if(g.format==="ends_with")return`Invalid string: must end with "${g.suffix}"`;if(g.format==="includes")return`Invalid string: must include "${g.includes}"`;if(g.format==="regex")return`Invalid string: must match pattern ${g.pattern}`;return`Invalid ${l[g.format]??f.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${f.divisor}`;case"unrecognized_keys":return`Unrecognized key${f.keys.length>1?"s":""}: ${ma(f.keys,", ")}`;case"invalid_key":return`Invalid key in ${f.origin}`;case"invalid_union":if(f.options&&Array.isArray(f.options)&&f.options.length>0)return`Invalid discriminator value. Expected ${f.options.map((k)=>`'${k}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${f.origin}`;default:return"Invalid input"}}};function mn(){return{localeError:Hi()}}he(mn());var ri="--proxy",ni="--proxy-ca-file",Wi=262144;class K extends Error{}function gn(e){let a;try{a=new URL(e)}catch{throw new K("The proxy must be a URL like https://proxy.example.com:3128.")}if(a.protocol!=="https:"&&a.protocol!=="http:")throw new K("The proxy URL must use the https or http scheme.");if(!a.hostname)throw new K("The proxy URL must name a host.");if(a.port!==""&&Number(a.port)<1)throw new K("The proxy URL must use a port between 1 and 65535.");if(a.pathname!==""&&a.pathname!=="/"||a.search||a.hash)throw new K("The proxy URL must not carry a path, query, or fragment.");return a.toString()}function qa(e){let a=new URL(e.url),l=a.port||(a.protocol==="https:"?"443":"80");return`${a.hostname}:${l}`}function Fi(e={}){let a=e.home??Li(),l=e.statePath??gt();return[Bi(l),dt(a,".ssh"),dt(a,".aws"),dt(a,".gnupg"),dt(a,".kube"),dt(a,"Library","Keychains")]}function Ui(e,a){return a===e||a.startsWith(e+Mi)}function zi(e,a={}){if(!ji(e))throw new K("The proxy CA file must be an absolute path.");let l,u,f;try{l=mo(e);let R=Ni(l);u=R.size,f=R.isFile()}catch{throw new K("The proxy CA file does not exist or is not readable.")}if(!f)throw new K("The proxy CA file must be a regular file.");if(u>Wi)throw new K("The proxy CA file must be 256 KB or smaller.");let g=Fi(a).flatMap((R)=>{try{let w=mo(R);return w===R?[R]:[R,w]}catch{return[R]}});for(let R of[e,l])if(g.some((w)=>Ui(w,R)))throw new K("The proxy CA file must not live inside a credential directory.");let k;try{k=ho(l,"utf8")}catch{throw new K("The proxy CA file is not readable.")}if(!k.includes("-----BEGIN CERTIFICATE-----"))throw new K("The proxy CA file must be a PEM certificate bundle.");return l}function Wa(e,a={}){if(!e.proxyUrl)throw new K("A proxy URL is required.");let l=gn(e.proxyUrl),u=e.caFile===void 0?void 0:zi(e.caFile,a);return{version:gr,url:l,...u===void 0?{}:{caFile:u}}}function oe(e,a=fetch){if(!e)return a;let l,u=!1;return(g,k)=>{if(!u){if(e.caFile)try{l=ho(e.caFile,"utf8")}catch{throw new K(`The configured proxy CA file is not readable: ${e.caFile}`)}u=!0}let R={...k,proxy:e.url,...l===void 0?{}:{tls:{ca:l}}};return a(g,R)}}import{createHash as $i}from"crypto";import{isAbsolute as bo,join as wo,relative as yo,resolve as Tt,sep as Io}from"path";var At=t().min(1).refine(bo,"absolute path required"),go=h({version:i(1),apiOrigin:zr(),channel:c(["staging","production"]),stateDirectory:At,workspaceRoot:At,lifetime:c(["persistent","ephemeral"]),executionMode:c(["confined","host"]).default("confined"),name:t().min(1).max(160).default("Reason headless worker"),slots:o().int().min(1).max(4).default(1),shutdownGraceMs:o().int().min(0).max(300000).default(30000),proxy:h({version:i(gr),url:t().refine((e)=>{try{return gn(e)===e}catch{return!1}},"invalid proxy URL"),caFile:At.optional()}).optional(),userChrome:_().optional(),cloudSessions:i(!0).optional(),localLogins:_().optional(),folders:d(At).min(1).max(31).optional()}),Ki=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,x=P("channel",[go,go.extend({channel:i("local-qa"),apiOrigin:t()})]).superRefine((e,a)=>{if(e.channel==="local-qa"){if(!Ki.test(e.apiOrigin))a.addIssue({code:"custom",message:"local QA worker requires an exact HTTPS trycloudflare.com quick-tunnel origin"})}else{let u=new URL(e.apiOrigin);if(u.origin!==e.apiOrigin||u.username||u.password||u.protocol!=="https:"&&!(u.protocol==="http:"&&Cr(u.origin))||!Cr(u.origin)&&!Pn(e.channel,u.origin))a.addIssue({code:"custom",message:"API origin must match channel (or loopback)"})}if(!ge(e.workspaceRoot,e.stateDirectory))a.addIssue({code:"custom",message:"state and workspace must be disjoint"});let l=e.folders??[];if(new Set([e.workspaceRoot,...l]).size!==l.length+1||l.some((u)=>!ge(u,e.stateDirectory)))a.addIssue({code:"custom",message:"folders must be distinct and disjoint from state"})});function p(e){return wo(e.stateDirectory,`headless-${e.channel}`)}function vo(e,a={},l={}){let u=e.executionMode==="host"?"unsandboxed":"sandboxed";return{worker:Object.freeze({executionMode:u,runtimeDirectory:p(e),handsSlots:e.slots,...l.ownComputer?{ownComputer:!0}:{},readiness:Object.freeze({...a}),...l.persistentTerminals?{persistentTerminals:!0}:{},...l.probing?.length?{probing:Object.freeze([...l.probing])}:{},...l.displayVideo?{displayVideo:!0}:{},...l.handsBrowser&&a["hands.connect"]===!0?{handsBrowser:!0}:{},...l.githubSignedIn===void 0?{}:{githubSignedIn:l.githubSignedIn},...e.userChrome!==!1&&l.userChrome?{userChrome:l.userChrome}:{},...e.cloudSessions&&a["automation.call.v1"]===!0?{cloudSessions:!0}:{}}),proxy:e.proxy??null}}function ge(e,a){if(se(a,e))return!1;return!se(e,a)||L(wo(Io,yo(Tt(e),Tt(a))))}function se(e,a){let l=yo(Tt(e),Tt(a));return l===""||l!==".."&&!l.startsWith(`..${Io}`)&&!bo(l)}function O(e){let{proxy:a,userChrome:l,cloudSessions:u,localLogins:f,folders:g,...k}=e;return $i("sha256").update(JSON.stringify(k)).digest("hex")}var Gi=4,Ji=[2375,2376,9222,9229];function ii(e){let a=new Set(Ji);for(let l of e){let u=new URL(l);a.add(Number(u.port||(["https:","wss:"].includes(u.protocol)?443:80)))}return a}function yr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var qi=60000;function Ho(e){let a=new AbortController,l=new Map,u=(w)=>JSON.stringify([w.jobId,w.port]);function f(w){let A=e.authority.owner;if(a.signal.aborted||!e.isCurrent()||e.expiresAtMs<=Date.now()||w.organization_id!==A.organization_id||w.user_id!==A.user_id||w.device_id!==A.device_id)yr()}function g(w){let A;try{A=e.environment.current()}catch{return null}return A.binding.target_generation===w.generation&&A.binding.target_fence_id===w.fenceId&&A.run_id===e.runId&&A.device_id===e.authority.owner.device_id&&A.root_id===e.authority.rootId?A:null}async function k(w,A,N){let D=await R(w,A,N);if(D!=="moved")return D;let S=await R(w,A,N);return S==="moved"?null:S}async function R(w,A,N){try{f(e.authority.owner);let D=e.identity();if(!D||N.aborted||w.expiresAtMs<=Date.now()||w.expiresAtMs>e.expiresAtMs)return null;let S=A.opened,M=S!==void 0&&D.generation>S.generation,j=g(D);if(M){if(j){if(j.revision<=S.revision||w.expiresAtMs>Date.parse(j.expires_at)||j.binding.target_revision!==S.attachmentRevision||j.binding.root_grant_revision!==S.grantRevision)return null;A.recoveringSinceMs=void 0}else if(Date.now()-(A.recoveringSinceMs??=Date.now())>qi)return null}else if(!j||w.expiresAtMs>Date.parse(j.expires_at)||S&&(D.generation!==S.generation||D.fenceId!==S.fenceId))return null;let C=await e.inspect(w.jobId,N),z=e.identity(),Q=z&&g(z);f(e.authority.owner);let Y=j&&{generation:D.generation,fenceId:D.fenceId,snapshotId:j.snapshot_id,revision:j.revision,attachmentRevision:j.binding.target_revision,grantRevision:j.binding.root_grant_revision},re=M?S:Y;if(N.aborted||!z)return null;if(z.generation!==D.generation||z.fenceId!==D.fenceId||Q?.snapshot_id!==j?.snapshot_id||Q?.revision!==j?.revision)return"moved";let we=C.ok&&C.job.environmentSnapshotId!==void 0&&C.job.environmentRevision!==void 0?{snapshotId:C.job.environmentSnapshotId,revision:C.job.environmentRevision}:null;if(!C.ok||C.generation!==D.generation||!re||!we)return null;if((we.snapshotId!==re.snapshotId||we.revision!==re.revision)&&(M||!e.environment.carried(we.snapshotId,we.revision)))return null;if(!S&&D.generation===w.generation&&D.fenceId===w.fenceId)A.opened={...re,...we};return{executorLaunchId:e.executorLaunchId,job:C.job,binding:{organizationId:e.authority.owner.organization_id,userId:e.authority.owner.user_id,deviceId:e.authority.owner.device_id,rootId:e.authority.rootId,runId:e.runId,attachmentRevision:re.attachmentRevision,grantRevision:re.grantRevision,generation:re.generation,fenceId:re.fenceId,jobId:C.job.jobId,port:w.port,expiresAtMs:w.expiresAtMs}}}catch{return null}}return{async open(w,A,N){f(A);let{binding:D,deviceRelayUrl:S}=pr(w);if(N.aborted||D.expiresAtMs<=Date.now()||D.expiresAtMs>Date.now()+v.lifetimeMs||new URL(S).origin!==e.authority.relayOrigin)yr();let M=u(D),j=l.get(M);if(j){if(!Bt(j.binding,D)||j.relay!==S)yr();if(await j.opened,!await ln(()=>j.port.check())||N.aborted||j.abort.signal.aborted)yr();return{opened:!0,binding:D}}if(l.size>=Gi)yr();let C=new AbortController,z={},Q=ft({binding:D,deniedPorts:e.authority.deniedPorts,readCurrentJob:()=>k(D,z,C.signal)}),Y=()=>C.abort();if(N.addEventListener("abort",Y,{once:!0}),a.signal.addEventListener("abort",Y,{once:!0}),N.aborted||a.signal.aborted)Y();let re=ht({binding:D,deviceRelayUrl:S,port:Q,signal:C.signal}),we={binding:D,relay:S,abort:C,port:Q,opened:re};l.set(M,we);let Ie=()=>{if(N.removeEventListener("abort",Y),a.signal.removeEventListener("abort",Y),l.get(M)===we)l.delete(M)};try{if((await re).closed.then(Ie),N.removeEventListener("abort",Y),f(A),C.signal.aborted||!await ln(()=>Q.check()))yr();return{opened:!0,binding:D}}catch{C.abort(),Ie(),yr()}},async close(w,A){f(A);let{binding:N}=oc(w),D=l.get(u(N));if(!D||!Bt(D.binding,N))yr();return D.abort.abort(),await D.opened.then((S)=>S.closed,()=>{return}),{closed:!0,binding:N}},dispose(){a.abort();for(let w of l.values())w.abort.abort();l.clear()}}}import{WebSocket as wn}from"ws";var No=(e)=>("data"in e)?e.data.length:e.bytes,Lo=2*Vt;function Fe(e){throw new r(e,"The bound Hands terminal is unavailable or its outcome is unconfirmed.")}var Wr=(e)=>!["starting","running"].includes(e.state);function Va(e,a,l=Date.now()){let u=["relay_url","session_id","expires_at","cols","rows","pty","workspace"];if(Object.keys(e).length!==u.length||Object.keys(e).some((A)=>!u.includes(A))||!nt(a)||!nt(e.session_id)||typeof e.expires_at!=="string"||typeof e.relay_url!=="string"||e.relay_url.length>4096||![e.cols,e.rows].every((A)=>Number.isSafeInteger(A)&&Number(A)>=1&&Number(A)<=yt))Fe("invalid_pty_request");let f=e.pty;if(!f||typeof f!=="object"||Array.isArray(f))Fe("invalid_pty_request");let g=f;if(Object.keys(g).length!==2||g.version!==1||!it(g.jobId))Fe("invalid_pty_request");let k;try{k=new URL(e.relay_url)}catch{return Fe("invalid_pty_request")}if(!["ws:","wss:"].includes(k.protocol)||k.username||k.password||k.hash||k.protocol==="ws:"&&!["127.0.0.1","[::1]","localhost"].includes(k.hostname))Fe("invalid_pty_request");let R=Date.parse(e.expires_at);if(!Number.isSafeInteger(R)||R<=l)Fe("invalid_pty_request");return{workspace:te(e.workspace)??Fe("invalid_pty_request"),session:{jobId:g.jobId,sessionId:e.session_id,operationId:a,relayUrl:k.href,cols:Number(e.cols),rows:Number(e.rows),leaseExpiresAtMs:Math.min(R,l+43200000)}}}async function Bo(e){let{session:a,binding:l}=e;if(l.assertCurrent(),e.signal.aborted||Date.now()>=a.leaseExpiresAtMs)Fe("cancelled");let u=new wn(a.relayUrl,{followRedirects:!1,perMessageDeflate:!1,maxPayload:He}),f=new AbortController,g=()=>{},k=()=>{f.abort(),g()};e.signal.addEventListener("abort",k,{once:!0});let R=setTimeout(k,Math.max(1,a.leaseExpiresAtMs-Date.now())),w=[],A=0,N=0,D=0,S=!1,M=!1,j=!1,C,z,Q,Y=(W)=>{Q=new r(W,"Bound terminal input was refused."),k()};u.on("error",()=>Y("pty_relay_unavailable")),u.on("close",k),u.on("message",(W,q)=>{if(f.signal.aborted)return;if(!M){Y("pty_not_ready");return}let ne=Array.isArray(W)?Buffer.concat(W):W instanceof ArrayBuffer?Buffer.from(W):W;if(ne.length===0)return;let ye=w.at(-1),le=q&&ye!==void 0&&"data"in ye&&ye.data.length+ne.length<=He;if(ne.length>He||A+ne.length>qo){Y("pty_input_backpressure");return}if(le)ye.data=Buffer.concat([ye.data,ne]);else if(q)w.push({data:Buffer.from(ne)});else try{let fe=JSON.parse(ne.toString("utf8"));if(fe&&fe.t==="close"&&Object.keys(fe).length===1){j=!0,k();return}if(!fe||fe.t!=="resize"||Object.keys(fe).length!==3||![fe.cols,fe.rows].every((ee)=>Number.isSafeInteger(ee)&&ee>=1&&ee<=yt))throw Error("invalid_control");w.push({cols:fe.cols,rows:fe.rows,bytes:ne.length})}catch{Y("invalid_pty_control");return}A+=ne.length,g()});function re(W){return Vo(JSON.stringify({...l.scope,version:1,sessionId:a.sessionId,operationId:a.operationId,job:{...W,output:[],pty:W.pty?{...W.pty,output:[]}:void 0}}))}function we(W){if(!W.ok)Fe(W.error);let q=W.job;if(W.generation!==l.scope.generation||q.jobId!==a.jobId||!q.pty||q.leaseExpiresAtMs>a.leaseExpiresAtMs||q.process&&q.process.executorLaunchId!==l.scope.executorLaunchId||q.process&&z&&(q.process.pid!==z.pid||q.process.processGroupId!==z.processGroupId)||q.state!=="starting"&&(q.environmentRevision!==l.environment.revision||q.environmentSnapshotId!==l.environment.snapshotId))Fe("pty_binding_changed");if(re(q),q.process)z??={...q.process};return q}async function Ie(W){l.assertCurrent();let q=await l.request(W,f.signal);if(l.assertCurrent(),f.signal.aborted)Fe("cancelled");let ne=we(q);if(ne.inputSequence!==N)Fe("job_input_sequence");if(!Wr(ne)&&ne.leaseExpiresAtMs<=Date.now())Fe("pty_binding_changed");return ne}function Z(W){if(l.assertCurrent(),f.signal.aborted||u.readyState!==wn.OPEN||u.bufferedAmount+Buffer.byteLength(W)>Lo)Fe("pty_output_backpressure");u.send(W)}function be(W){if(W.firstCursor>D+1)D=W.firstCursor-1;for(let q of W.pty.output){if(q.cursor<=D)continue;if(q.cursor!==D+1)Fe("pty_output_gap");let ne=Buffer.from(q.dataBase64,"base64");if(u.bufferedAmount+ne.length>Lo)return!1;Z(ne),D=q.cursor}if(D!==W.nextCursor)Fe("pty_output_gap");return!0}async function ke(W,q){let ne;try{await Promise.race([e.emit(W,q),new Promise((ye,le)=>{ne=setTimeout(()=>le(new r("pty_event_unavailable","Terminal metadata delivery timed out.")),2000)})])}finally{clearTimeout(ne)}}async function ae(){let W=AbortSignal.timeout(bn),q=l.request({jobId:a.jobId,action:"cancel",input:{}},W),ne,ye=new Promise((le,fe)=>{if(ne=()=>fe(new r("pty_cleanup_unconfirmed","Terminal cleanup acknowledgement was not observed within authority.")),W.addEventListener("abort",ne,{once:!0}),W.aborted)ne()});try{let le=await Promise.race([q,ye]);if(W.aborted)Fe("pty_cleanup_unconfirmed");return we(le)}finally{W.removeEventListener("abort",ne)}}try{await new Promise((le,fe)=>{let ee=setTimeout(()=>{k(),fe(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),me=()=>{clearTimeout(ee),fe(new r("cancelled","Terminal pairing was cancelled."))};if(f.signal.addEventListener("abort",me,{once:!0}),u.once("open",()=>{clearTimeout(ee),f.signal.removeEventListener("abort",me),le()}),f.signal.aborted)me()}),l.assertCurrent(),S=!0,C=await Ie({jobId:a.jobId,action:"start",input:{mode:"pty",cols:a.cols,rows:a.rows,leaseExpiresAtMs:a.leaseExpiresAtMs}});let W=Date.now()+5000;while(C.state==="starting"){if(Date.now()>=W)Fe("pty_not_ready");await new Promise((le)=>setTimeout(le,25)),C=await Ie({jobId:a.jobId,action:"inspect",input:{after:D}})}if(C.state!=="running"||C.inputSequence!==0||C.leaseExpiresAtMs<=Date.now())Fe("pty_not_ready");await ke("pty.ready",re(C)),M=!0,Z(JSON.stringify({t:"open",cols:C.pty.cols,rows:C.pty.rows,receipt:re(C)}));let q=!1,ne=0,ye=!1;while(!f.signal.aborted){let le=C.firstCursor>D+1,fe=be(C);if(Wr(C)){if(fe)break}else if(le)q=!0;else if(q&&fe&&Date.now()>=ne){q=!1,ne=Date.now()+1000;let{cols:me,rows:De}=C.pty;for(let Me of[{cols:me,rows:De>1?De-1:2},{cols:me,rows:De}]){if(Wr(C))break;let rr=++N;if(C=await Ie({jobId:a.jobId,action:"resize",input:{sequence:rr,...Me}}),C.inputSequence!==rr)Fe("job_input_sequence")}continue}let ee=Wr(C)||ye?void 0:w.shift();if(ee){A-=No(ee);let me=++N;try{C=await Ie("data"in ee?{jobId:a.jobId,action:"input",input:{sequence:me,dataBase64:ee.data.toString("base64")}}:{jobId:a.jobId,action:"resize",input:{sequence:me,cols:ee.cols,rows:ee.rows}})}catch(De){if(!(De instanceof r)||De.code!=="job_input_backpressure")throw De;N-=1,w.unshift(ee),A+=No(ee),ye=!0;continue}if(C.inputSequence!==me)Fe("job_input_sequence")}else if(await new Promise((me)=>{let De=setTimeout(me,ye||!fe?10:50);if(g=()=>{clearTimeout(De),me()},f.signal.aborted||!ye&&w.length)g()}),ye=!1,g=()=>{},!f.signal.aborted&&fe)try{C=await Ie({jobId:a.jobId,action:"inspect",input:{after:D}})}catch(me){if(!j||!(me instanceof r)||me.code!=="cancelled")throw me}}}catch(W){Q??=W}finally{if(M=!1,w.length=0,clearTimeout(R),e.signal.removeEventListener("abort",k),k(),S&&(!C||!Wr(C)))try{C=await ae()}catch{C=void 0}try{if(!C||!Wr(C)||C.pty?.cleanup!=="confirmed")Fe("pty_cleanup_unconfirmed");let W=re(C);if(u.readyState===wn.OPEN)await new Promise((q)=>{let ne=setTimeout(q,500);u.send(JSON.stringify({t:"exit",code:C.exitCode,receipt:W}),()=>{clearTimeout(ne),q()})});await ke("pty.stopped",W)}catch(W){Q??=W}u.terminate()}if(Q)throw Q;if(e.signal.aborted)Fe("cancelled");if(!C)Fe("pty_cleanup_unconfirmed");return{receipt:re(C)}}import{createHash as Yi,randomUUID as Sn}from"crypto";import{spawnSync as Fo}from"child_process";import{closeSync as jo,constants as yn,fstatSync as Xi,fsyncSync as Zi,lstatSync as lt,mkdirSync as Qi,mkdtempSync as Uo,openSync as Mo,readFileSync as ea,readdirSync as zo,realpathSync as kr,rmSync as vn,unlinkSync as ra}from"fs";import{createConnection as ta}from"net";import{dirname as na,join as Ar,sep as kn}from"path";import{tmpdir as $o}from"os";var er=new Map,vr=new Map;function mr(e,a){return Yi("sha256").update(JSON.stringify([e,a])).digest("hex")}function Fr(e){try{Qi(e,{mode:448})}catch(l){if(!(l instanceof Error&&("code"in l)&&l.code==="EEXIST"))throw l}let a=lt(e);if(!a.isDirectory()||a.isSymbolicLink()||!G(a)||kr(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function oa(e){let a;try{a=lt(e)}catch(l){if(l instanceof Error&&"code"in l&&l.code==="ENOENT")return!1;throw l}return!a.isDirectory()||a.isSymbolicLink()||zo(e).length>0}function sa(e){if(process.platform==="win32")return Ea();let a=e.map((l)=>{try{return kr(l)}catch{return l}});for(let l of[()=>Ea(),()=>kr("/dev/shm"),()=>kr($o())]){let u;try{u=l()}catch{continue}if(!a.some((f)=>u===f||u.startsWith(f.endsWith(kn)?f:f+kn)))return u}throw new r("invalid_hands_workspace","A Session can't work in this computer's temporary folder itself; start it in a project folder inside it.")}function $t(e){let a=mr(e.root,e.runId),l=e.previousRuntimeDirectories?.find((k)=>oa(Ar(k,"jobs",a.slice(0,16))))??e.runtimeDirectory;Fr(l);let u=Ar(l,"jobs");Fr(u);let f=Ar(u,a.slice(0,16));if(e.maxScopes!==void 0){let k=zo(u);if(!Number.isSafeInteger(e.maxScopes)||e.maxScopes<1||k.length>e.maxScopes||!k.includes(a.slice(0,16))&&k.length>=e.maxScopes)throw new r("process_journal_capacity","Managed process receipt capacity is full; preserve uncertain jobs and reconcile their existing receipts before starting more work.")}Fr(f);let g=Uo(Ar(sa(e.folders??[]),"reason-j-"));try{return Fr(g),{journalDirectory:f,scopeId:a,launchDirectory:g,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${Sn()}`:Ar(g,"control.sock"),disposeSocket:()=>vn(g,{recursive:!0,force:!0})}}catch(k){throw vn(g,{recursive:!0,force:!0}),k}}var ia=60000,aa=5000;function ca(e){if(process.platform==="win32")return da(e);let a=Fo("ps",["-o","lstart=","-p",String(e)],{encoding:"utf8",timeout:2000,env:{...process.env,LC_ALL:"C",LANG:"C"}}),l=a.status===0?/^\w{3} (\w{3}) +(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/.exec(a.stdout.trim()):null,u=l?"JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(l[1]):-1;if(!l||u<0||u%3!==0)return null;let f=new Date(Number(l[6]),u/3,Number(l[2]),Number(l[3]),Number(l[4]),Number(l[5])).getTime();return Number.isFinite(f)?f:null}function da(e){let a=Fo(B("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().ToString('o')`],{encoding:"utf8",timeout:5000,windowsHide:!0,env:It()}),l=a.status===0?Date.parse(a.stdout.trim()):Number.NaN;return Number.isFinite(l)?l:null}function Ko(e,a={}){let l=Ar(e.journalDirectory,"owner.lock"),u;try{u=Mo(l,yn.O_RDONLY|yn.O_NOFOLLOW)}catch{return null}try{let f=Xi(u);if(!f.isFile()||f.nlink!==1||!G(f)||f.size>4096)return null;let g=null;try{g=JSON.parse(ea(u,"utf8"))}catch{}let k;if(g===null){if((a.now??Date.now)()-f.mtimeMs<ia)return null;k={reason:"never_written",executorLaunchId:null}}else{let{version:A,scopeId:N,pid:D,createdAtMs:S,executorLaunchId:M}=g;if(A!==1||N!==e.scopeId||typeof M!=="string"||typeof D!=="number"||!Number.isSafeInteger(D)||D<1||D===process.pid||typeof S!=="number"||!Number.isSafeInteger(S))return null;if(!(a.exists??((C)=>{try{return process.kill(C,0),!0}catch(z){return!(z instanceof Error&&("code"in z)&&z.code==="ESRCH")}}))(D))k={reason:"owner_exited",executorLaunchId:M};else{let C=(a.startedAtMs??ca)(D);if(C===null||C<=S+aa)return null;k={reason:"pid_reused",executorLaunchId:M}}}let R=lt(l);if(R.dev!==f.dev||R.ino!==f.ino)return null;ra(l);let w=Mo(e.journalDirectory,yn.O_RDONLY);try{Zi(w)}finally{jo(w)}return k}catch{return null}finally{jo(u)}}function Go(e){let a={...e,workspace:e.workspace&&Object.freeze({...e.workspace}),previewAuthority:e.previewAuthority&&Object.freeze({...e.previewAuthority,owner:Object.freeze({...e.previewAuthority.owner}),deniedPorts:new Set(e.previewAuthority.deniedPorts)})},l=mr(a.root,a.runId);if(er.has(l)||a.operationId!==void 0&&vr.has(a.operationId))throw new r("hands_jobs_busy","The Session already has a live Hands job supervisor.");let u={binding:a,key:l,terminals:new Map};if(a.previewAuthority&&a.environment)u.previews=Ho({authority:a.previewAuthority,runId:a.runId,expiresAtMs:a.expiresAtMs,executorLaunchId:a.executorLaunchId,environment:a.environment,isCurrent:()=>er.get(u.key)===u,identity:()=>{try{return Ur(a)}catch{return null}},inspect:(f,g)=>{if(er.get(u.key)!==u)throw new r("preview_unavailable","The Hands supervisor is no longer current.");return Jo(a,{jobId:f,action:"inspect",input:{after:0}},g)}});if(er.set(l,u),a.operationId!==void 0)vr.set(a.operationId,u);return()=>{if(er.get(u.key)===u)er.delete(u.key);if(a.operationId!==void 0&&vr.get(a.operationId)===u)vr.delete(a.operationId);u.previews?.dispose();for(let f of u.terminals.values())f.abort()}}var la=5000,ua=20;async function Ga(e){let a=(f)=>{throw new r("hands_rebind_unavailable",f)};if(!ce(e.operationId)||!ce(e.runId)||!ce(e.fenceId)||!Ee(e.targetGeneration))a("Reason sent an invalid Hands rebind.");let l=vr.get(e.operationId);if(!l||l.binding.root!==e.root)return a("No live Hands supervisor owns this operation.");for(let f=Date.now()+la;;){if(e.signal?.aborted)a("The Hands rebind was cancelled.");if(vr.get(e.operationId)!==l)a("The Hands supervisor is no longer current.");let g=null;try{g=Ur(l.binding)}catch{}if(g&&g.generation===e.targetGeneration&&g.fenceId===e.fenceId)break;if(g&&g.generation>e.targetGeneration||Date.now()>=f)a("The executor did not adopt this take.");await new Promise((k)=>setTimeout(k,ua))}if(vr.get(e.operationId)!==l||er.get(l.key)!==l)a("The Hands supervisor is no longer current.");let u=mr(e.root,e.runId);if(l.key===u)return;if(er.has(u))a("The taking run already has a live Hands job supervisor.");er.delete(l.key);for(let f of l.terminals.values())f.abort();l.key=u,er.set(u,l)}function Qe(e){let a="operationId"in e?vr.get(e.operationId):er.get(mr(e.root,e.runId)),l=a&&a.binding.root===e.root?a.binding:void 0;if(!l?.environment||l.expiresAtMs<=Date.now())throw new r("environment_unavailable","No live Hands supervisor owns this environment.");return l.environment.install(e.payload)}async function Ka(e){let a=er.get(mr(e.root,e.runId));if(!a?.previews||!e.owner)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return a.previews.open(e.payload,e.owner,e.signal)}async function Ja(e){let a=er.get(mr(e.root,e.runId));if(!a?.previews||!e.owner||e.signal.aborted)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return a.previews.close(e.payload,e.owner)}async function rn(e){let a=mr(e.root,e.runId),l=er.get(a),u=l?.binding,f=u?.runId,g=u?.previewAuthority,k=u?.environment,R=e.owner&&{...e.owner},w=e.authority&&{...e.authority},A=()=>{throw new r("pty_binding_unavailable","No current authenticated Hands scope owns this terminal.")};if(!l||!u||!g||!k||!R||!w||!u.workspace)return A();let N=Object.freeze({...u.workspace}),D=Ur(u),S=k.current(),M=()=>{if(er.get(a)!==l||R.organization_id!==g.owner.organization_id||R.user_id!==g.owner.user_id||R.device_id!==g.owner.device_id||e.deviceId!==g.owner.device_id||e.rootId!==g.rootId||X(e.workspace)!==X(N))A();let C=Ur(u),z=k.current();if(C.generation!==D.generation||C.fenceId!==D.fenceId||z.run_id!==f||z.device_id!==e.deviceId||z.root_id!==e.rootId||z.snapshot_id!==S.snapshot_id||z.revision!==S.revision||z.binding.target_generation!==D.generation||z.binding.target_fence_id!==D.fenceId||w.device_id!==e.deviceId||w.binding!==z.binding.kind||w.target_revision!==z.binding.target_revision||w.root_grant_revision!==z.binding.root_grant_revision||w.target_generation!==D.generation||w.target_fence_id!==D.fenceId)A()};if(M(),new URL(e.session.relayUrl).origin!==g.relayOrigin||l.terminals.has(e.session.jobId)||l.terminals.size>=4)return A();let j=new AbortController;l.terminals.set(e.session.jobId,j);try{return await Bo({session:{...e.session,leaseExpiresAtMs:Math.min(e.session.leaseExpiresAtMs,D.expiresAtMs,Date.parse(S.expires_at))},signal:AbortSignal.any([e.signal,j.signal]),emit:e.emit,binding:{assertCurrent:M,environment:{revision:S.revision,snapshotId:S.snapshot_id},scope:{runId:e.runId,deviceId:e.deviceId,rootId:e.rootId,workspace:N,binding:S.binding.kind,targetRevision:S.binding.target_revision,rootGrantRevision:S.binding.root_grant_revision,generation:D.generation,fenceId:D.fenceId,executorLaunchId:D.executorLaunchId},request:(C,z)=>oi(D,Ri(JSON.stringify({...C,type:"job",version:2,generation:D.generation,id:Sn()})),z)}})}finally{if(l.terminals.get(e.session.jobId)===j)l.terminals.delete(e.session.jobId)}}async function Xa(e){if(it(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let a=er.get(mr(e.root,e.runId))?.binding;if(!a||a.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","No live Hands supervisor owns this Session and root.");return Jo(a,e.payload,e.signal)}var fa=1e4,pa=20,_a=_t/2,ha=qt/2,wa=(e)=>e.output.reduce((a,l)=>a+l.text.length,0);async function Jo(e,a,l){if(Object.keys(a).some((A)=>!["jobId","action","input","waitForExitMs"].includes(A)))throw new r("invalid_payload","Unexpected job control field.");let{waitForExitMs:u,...f}=a;if(u!==void 0&&(f.action!=="start"||typeof f.input!=="object"||f.input===null||!("script"in f.input)||typeof u!=="number"||!Number.isSafeInteger(u)||u<1||u>fa))throw new r("invalid_payload","Only a script start may wait for its job, within its bound.");let g=(A)=>{let N=Ur(e);return oi(N,Ri(JSON.stringify({...A,type:"job",version:2,generation:N.generation,id:Sn()})),l)},k=await g(f);if(u===void 0)return k;let R=Date.now()+u,w=k;while(w.ok&&["starting","running"].includes(w.job.state)&&w.job.output.length<_a&&wa(w.job)<ha&&!l.aborted&&Date.now()<R){if(await new Promise((A)=>setTimeout(A,Math.min(pa,R-Date.now()))),l.aborted)break;try{let A=await g({jobId:f.jobId,action:"inspect",input:{after:0}});if(!A.ok)break;w=A}catch{break}}return w}function Ur(e){if(e.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","Hands authority expired.");let a=e.readIdentity?e.readIdentity():e;if(!a||!Ee(a.generation)||!ce(a.fenceId)||a.generation<e.generation||a.generation===e.generation&&a.fenceId!==e.fenceId)throw new r("hands_jobs_unavailable","The live Hands fencing identity could not be verified.");return e.generation=a.generation,e.fenceId=a.fenceId,{...e}}function oi(e,a,l){if(l.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((u,f)=>{let g=ta(e.socketPath),k="",R=!1,w,A=(D,S)=>{if(R)return;if(R=!0,clearTimeout(w),l.removeEventListener("abort",N),g.destroy(),D)f(D);else u(S)},N=()=>A(new r("cancelled","Job control waiter cancelled; inspect before retrying mutations."));l.addEventListener("abort",N,{once:!0}),g.setEncoding("utf8"),w=setTimeout(()=>A(new r("hands_job_result_unknown","Job control timed out; inspect before retrying mutations.")),Math.min(1e4,Math.max(1,e.expiresAtMs-Date.now()))),g.on("error",()=>A(new r("hands_job_result_unknown","Hands job control connection failed."))),g.once("connect",()=>g.write(JSON.stringify({version:1,scopeId:e.scopeId,fenceId:e.fenceId,executorLaunchId:e.executorLaunchId,request:a})+`
|
|
2
|
+
import{gt,gr,Se}from"./vm-hands-entry-lite-1as6h9ed.js";import{at,kt,Oe,xt,Ke,Dr,Zt,Ne,X,te,Vi}from"./vm-hands-entry-lite-hpw27zfb.js";import{Pn,Cr}from"./vm-hands-entry-lite-0xfme8gg.js";import{pc,F,qt,_t,Wt,He,Vt,qo,yt,bn,nt,Ee,ce,it,Ri,Ti,Vo}from"./vm-hands-entry-lite-bc9zq8gx.js";import{Ct,Je,ct,Le,Pt,xe,pe}from"./vm-hands-entry-lite-vvhfaxpd.js";import{cn,mi,dr,Re,U,H,T,To}from"./vm-hands-entry-lite-bbjsnjct.js";import{Ft,_i,Do,lc,je,Oo}from"./vm-hands-entry-lite-732hnx41.js";import{ue}from"./vm-hands-entry-lite-t2rhwchw.js";import{ba}from"./vm-hands-entry-lite-t3k90kdn.js";import{v,Bt,ln,pr,oc,ht,ft}from"./vm-hands-entry-lite-sxnvhzy5.js";import{b,m,y}from"./vm-hands-entry-lite-2927z566.js";import{L}from"./vm-hands-entry-lite-hpe54h0b.js";import{Mn}from"./vm-hands-entry-lite-fp3gaa2c.js";import{s,Uc,zc,Ge,Wc}from"./vm-hands-entry-lite-tzv8s0e7.js";import{he,ma,ga,Xc,I,t,V,zr,o,_,d,n,h,P,$e,c,i}from"./vm-hands-entry-lite-bt6skt4h.js";import{ya}from"./vm-hands-entry-lite-1sy80ca9.js";import{Zc,Ye,Ea,B,It,Be,G}from"./vm-hands-entry-lite-04nx5y4f.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{readFileSync as ho,realpathSync as mo,statSync as Ni}from"fs";import{homedir as Li}from"os";import{dirname as Bi,isAbsolute as ji,join as dt,sep as Mi}from"path";var Hi=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function a(f){return e[f]??null}let l={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},u={nan:"NaN"};return(f)=>{switch(f.code){case"invalid_type":{let g=u[f.expected]??f.expected,k=Xc(f.input),R=u[k]??k;return`Invalid input: expected ${g}, received ${R}`}case"invalid_value":if(f.values.length===1)return`Invalid input: expected ${ga(f.values[0])}`;return`Invalid option: expected one of ${ma(f.values,"|")}`;case"too_big":{let g=f.inclusive?"<=":"<",k=a(f.origin);if(k)return`Too big: expected ${f.origin??"value"} to have ${g}${f.maximum.toString()} ${k.unit??"elements"}`;return`Too big: expected ${f.origin??"value"} to be ${g}${f.maximum.toString()}`}case"too_small":{let g=f.inclusive?">=":">",k=a(f.origin);if(k)return`Too small: expected ${f.origin} to have ${g}${f.minimum.toString()} ${k.unit}`;return`Too small: expected ${f.origin} to be ${g}${f.minimum.toString()}`}case"invalid_format":{let g=f;if(g.format==="starts_with")return`Invalid string: must start with "${g.prefix}"`;if(g.format==="ends_with")return`Invalid string: must end with "${g.suffix}"`;if(g.format==="includes")return`Invalid string: must include "${g.includes}"`;if(g.format==="regex")return`Invalid string: must match pattern ${g.pattern}`;return`Invalid ${l[g.format]??f.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${f.divisor}`;case"unrecognized_keys":return`Unrecognized key${f.keys.length>1?"s":""}: ${ma(f.keys,", ")}`;case"invalid_key":return`Invalid key in ${f.origin}`;case"invalid_union":if(f.options&&Array.isArray(f.options)&&f.options.length>0)return`Invalid discriminator value. Expected ${f.options.map((k)=>`'${k}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${f.origin}`;default:return"Invalid input"}}};function mn(){return{localeError:Hi()}}he(mn());var ri="--proxy",ni="--proxy-ca-file",Wi=262144;class K extends Error{}function gn(e){let a;try{a=new URL(e)}catch{throw new K("The proxy must be a URL like https://proxy.example.com:3128.")}if(a.protocol!=="https:"&&a.protocol!=="http:")throw new K("The proxy URL must use the https or http scheme.");if(!a.hostname)throw new K("The proxy URL must name a host.");if(a.port!==""&&Number(a.port)<1)throw new K("The proxy URL must use a port between 1 and 65535.");if(a.pathname!==""&&a.pathname!=="/"||a.search||a.hash)throw new K("The proxy URL must not carry a path, query, or fragment.");return a.toString()}function qa(e){let a=new URL(e.url),l=a.port||(a.protocol==="https:"?"443":"80");return`${a.hostname}:${l}`}function Fi(e={}){let a=e.home??Li(),l=e.statePath??gt();return[Bi(l),dt(a,".ssh"),dt(a,".aws"),dt(a,".gnupg"),dt(a,".kube"),dt(a,"Library","Keychains")]}function Ui(e,a){return a===e||a.startsWith(e+Mi)}function zi(e,a={}){if(!ji(e))throw new K("The proxy CA file must be an absolute path.");let l,u,f;try{l=mo(e);let R=Ni(l);u=R.size,f=R.isFile()}catch{throw new K("The proxy CA file does not exist or is not readable.")}if(!f)throw new K("The proxy CA file must be a regular file.");if(u>Wi)throw new K("The proxy CA file must be 256 KB or smaller.");let g=Fi(a).flatMap((R)=>{try{let w=mo(R);return w===R?[R]:[R,w]}catch{return[R]}});for(let R of[e,l])if(g.some((w)=>Ui(w,R)))throw new K("The proxy CA file must not live inside a credential directory.");let k;try{k=ho(l,"utf8")}catch{throw new K("The proxy CA file is not readable.")}if(!k.includes("-----BEGIN CERTIFICATE-----"))throw new K("The proxy CA file must be a PEM certificate bundle.");return l}function Wa(e,a={}){if(!e.proxyUrl)throw new K("A proxy URL is required.");let l=gn(e.proxyUrl),u=e.caFile===void 0?void 0:zi(e.caFile,a);return{version:gr,url:l,...u===void 0?{}:{caFile:u}}}function oe(e,a=fetch){if(!e)return a;let l,u=!1;return(g,k)=>{if(!u){if(e.caFile)try{l=ho(e.caFile,"utf8")}catch{throw new K(`The configured proxy CA file is not readable: ${e.caFile}`)}u=!0}let R={...k,proxy:e.url,...l===void 0?{}:{tls:{ca:l}}};return a(g,R)}}import{createHash as $i}from"crypto";import{isAbsolute as bo,join as wo,relative as yo,resolve as Tt,sep as Io}from"path";var At=t().min(1).refine(bo,"absolute path required"),go=h({version:i(1),apiOrigin:zr(),channel:c(["staging","production"]),stateDirectory:At,workspaceRoot:At,lifetime:c(["persistent","ephemeral"]),executionMode:c(["confined","host"]).default("confined"),name:t().min(1).max(160).default("Reason headless worker"),slots:o().int().min(1).max(4).default(1),shutdownGraceMs:o().int().min(0).max(300000).default(30000),proxy:h({version:i(gr),url:t().refine((e)=>{try{return gn(e)===e}catch{return!1}},"invalid proxy URL"),caFile:At.optional()}).optional(),userChrome:_().optional(),cloudSessions:i(!0).optional(),localLogins:_().optional(),folders:d(At).min(1).max(31).optional()}),Ki=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,x=P("channel",[go,go.extend({channel:i("local-qa"),apiOrigin:t()})]).superRefine((e,a)=>{if(e.channel==="local-qa"){if(!Ki.test(e.apiOrigin))a.addIssue({code:"custom",message:"local QA worker requires an exact HTTPS trycloudflare.com quick-tunnel origin"})}else{let u=new URL(e.apiOrigin);if(u.origin!==e.apiOrigin||u.username||u.password||u.protocol!=="https:"&&!(u.protocol==="http:"&&Cr(u.origin))||!Cr(u.origin)&&!Pn(e.channel,u.origin))a.addIssue({code:"custom",message:"API origin must match channel (or loopback)"})}if(!ge(e.workspaceRoot,e.stateDirectory))a.addIssue({code:"custom",message:"state and workspace must be disjoint"});let l=e.folders??[];if(new Set([e.workspaceRoot,...l]).size!==l.length+1||l.some((u)=>!ge(u,e.stateDirectory)))a.addIssue({code:"custom",message:"folders must be distinct and disjoint from state"})});function p(e){return wo(e.stateDirectory,`headless-${e.channel}`)}function vo(e,a={},l={}){let u=e.executionMode==="host"?"unsandboxed":"sandboxed";return{worker:Object.freeze({executionMode:u,runtimeDirectory:p(e),handsSlots:e.slots,...l.ownComputer?{ownComputer:!0}:{},readiness:Object.freeze({...a}),...l.persistentTerminals?{persistentTerminals:!0}:{},...l.probing?.length?{probing:Object.freeze([...l.probing])}:{},...l.displayVideo?{displayVideo:!0}:{},...l.handsBrowser&&a["hands.connect"]===!0?{handsBrowser:!0}:{},...l.githubSignedIn===void 0?{}:{githubSignedIn:l.githubSignedIn},...e.userChrome!==!1&&l.userChrome?{userChrome:l.userChrome}:{},...e.cloudSessions&&a["automation.call.v1"]===!0?{cloudSessions:!0}:{}}),proxy:e.proxy??null}}function ge(e,a){if(se(a,e))return!1;return!se(e,a)||L(wo(Io,yo(Tt(e),Tt(a))))}function se(e,a){let l=yo(Tt(e),Tt(a));return l===""||l!==".."&&!l.startsWith(`..${Io}`)&&!bo(l)}function O(e){let{proxy:a,userChrome:l,cloudSessions:u,localLogins:f,folders:g,...k}=e;return $i("sha256").update(JSON.stringify(k)).digest("hex")}var Gi=4,Ji=[2375,2376,9222,9229];function ii(e){let a=new Set(Ji);for(let l of e){let u=new URL(l);a.add(Number(u.port||(["https:","wss:"].includes(u.protocol)?443:80)))}return a}function yr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var qi=60000;function Ho(e){let a=new AbortController,l=new Map,u=(w)=>JSON.stringify([w.jobId,w.port]);function f(w){let A=e.authority.owner;if(a.signal.aborted||!e.isCurrent()||e.expiresAtMs<=Date.now()||w.organization_id!==A.organization_id||w.user_id!==A.user_id||w.device_id!==A.device_id)yr()}function g(w){let A;try{A=e.environment.current()}catch{return null}return A.binding.target_generation===w.generation&&A.binding.target_fence_id===w.fenceId&&A.run_id===e.runId&&A.device_id===e.authority.owner.device_id&&A.root_id===e.authority.rootId?A:null}async function k(w,A,N){let D=await R(w,A,N);if(D!=="moved")return D;let S=await R(w,A,N);return S==="moved"?null:S}async function R(w,A,N){try{f(e.authority.owner);let D=e.identity();if(!D||N.aborted||w.expiresAtMs<=Date.now()||w.expiresAtMs>e.expiresAtMs)return null;let S=A.opened,M=S!==void 0&&D.generation>S.generation,j=g(D);if(M){if(j){if(j.revision<=S.revision||w.expiresAtMs>Date.parse(j.expires_at)||j.binding.target_revision!==S.attachmentRevision||j.binding.root_grant_revision!==S.grantRevision)return null;A.recoveringSinceMs=void 0}else if(Date.now()-(A.recoveringSinceMs??=Date.now())>qi)return null}else if(!j||w.expiresAtMs>Date.parse(j.expires_at)||S&&(D.generation!==S.generation||D.fenceId!==S.fenceId))return null;let C=await e.inspect(w.jobId,N),z=e.identity(),Q=z&&g(z);f(e.authority.owner);let Y=j&&{generation:D.generation,fenceId:D.fenceId,snapshotId:j.snapshot_id,revision:j.revision,attachmentRevision:j.binding.target_revision,grantRevision:j.binding.root_grant_revision},re=M?S:Y;if(N.aborted||!z)return null;if(z.generation!==D.generation||z.fenceId!==D.fenceId||Q?.snapshot_id!==j?.snapshot_id||Q?.revision!==j?.revision)return"moved";let we=C.ok&&C.job.environmentSnapshotId!==void 0&&C.job.environmentRevision!==void 0?{snapshotId:C.job.environmentSnapshotId,revision:C.job.environmentRevision}:null;if(!C.ok||C.generation!==D.generation||!re||!we)return null;if((we.snapshotId!==re.snapshotId||we.revision!==re.revision)&&(M||!e.environment.carried(we.snapshotId,we.revision)))return null;if(!S&&D.generation===w.generation&&D.fenceId===w.fenceId)A.opened={...re,...we};return{executorLaunchId:e.executorLaunchId,job:C.job,binding:{organizationId:e.authority.owner.organization_id,userId:e.authority.owner.user_id,deviceId:e.authority.owner.device_id,rootId:e.authority.rootId,runId:e.runId,attachmentRevision:re.attachmentRevision,grantRevision:re.grantRevision,generation:re.generation,fenceId:re.fenceId,jobId:C.job.jobId,port:w.port,expiresAtMs:w.expiresAtMs}}}catch{return null}}return{async open(w,A,N){f(A);let{binding:D,deviceRelayUrl:S}=pr(w);if(N.aborted||D.expiresAtMs<=Date.now()||D.expiresAtMs>Date.now()+v.lifetimeMs||new URL(S).origin!==e.authority.relayOrigin)yr();let M=u(D),j=l.get(M);if(j){if(!Bt(j.binding,D)||j.relay!==S)yr();if(await j.opened,!await ln(()=>j.port.check())||N.aborted||j.abort.signal.aborted)yr();return{opened:!0,binding:D}}if(l.size>=Gi)yr();let C=new AbortController,z={},Q=ft({binding:D,deniedPorts:e.authority.deniedPorts,readCurrentJob:()=>k(D,z,C.signal)}),Y=()=>C.abort();if(N.addEventListener("abort",Y,{once:!0}),a.signal.addEventListener("abort",Y,{once:!0}),N.aborted||a.signal.aborted)Y();let re=ht({binding:D,deviceRelayUrl:S,port:Q,signal:C.signal}),we={binding:D,relay:S,abort:C,port:Q,opened:re};l.set(M,we);let Ie=()=>{if(N.removeEventListener("abort",Y),a.signal.removeEventListener("abort",Y),l.get(M)===we)l.delete(M)};try{if((await re).closed.then(Ie),N.removeEventListener("abort",Y),f(A),C.signal.aborted||!await ln(()=>Q.check()))yr();return{opened:!0,binding:D}}catch{C.abort(),Ie(),yr()}},async close(w,A){f(A);let{binding:N}=oc(w),D=l.get(u(N));if(!D||!Bt(D.binding,N))yr();return D.abort.abort(),await D.opened.then((S)=>S.closed,()=>{return}),{closed:!0,binding:N}},dispose(){a.abort();for(let w of l.values())w.abort.abort();l.clear()}}}import{WebSocket as wn}from"ws";var No=(e)=>("data"in e)?e.data.length:e.bytes,Lo=2*Vt;function Fe(e){throw new r(e,"The bound Hands terminal is unavailable or its outcome is unconfirmed.")}var Wr=(e)=>!["starting","running"].includes(e.state);function Va(e,a,l=Date.now()){let u=["relay_url","session_id","expires_at","cols","rows","pty","workspace"];if(Object.keys(e).length!==u.length||Object.keys(e).some((A)=>!u.includes(A))||!nt(a)||!nt(e.session_id)||typeof e.expires_at!=="string"||typeof e.relay_url!=="string"||e.relay_url.length>4096||![e.cols,e.rows].every((A)=>Number.isSafeInteger(A)&&Number(A)>=1&&Number(A)<=yt))Fe("invalid_pty_request");let f=e.pty;if(!f||typeof f!=="object"||Array.isArray(f))Fe("invalid_pty_request");let g=f;if(Object.keys(g).length!==2||g.version!==1||!it(g.jobId))Fe("invalid_pty_request");let k;try{k=new URL(e.relay_url)}catch{return Fe("invalid_pty_request")}if(!["ws:","wss:"].includes(k.protocol)||k.username||k.password||k.hash||k.protocol==="ws:"&&!["127.0.0.1","[::1]","localhost"].includes(k.hostname))Fe("invalid_pty_request");let R=Date.parse(e.expires_at);if(!Number.isSafeInteger(R)||R<=l)Fe("invalid_pty_request");return{workspace:te(e.workspace)??Fe("invalid_pty_request"),session:{jobId:g.jobId,sessionId:e.session_id,operationId:a,relayUrl:k.href,cols:Number(e.cols),rows:Number(e.rows),leaseExpiresAtMs:Math.min(R,l+43200000)}}}async function Bo(e){let{session:a,binding:l}=e;if(l.assertCurrent(),e.signal.aborted||Date.now()>=a.leaseExpiresAtMs)Fe("cancelled");let u=new wn(a.relayUrl,{followRedirects:!1,perMessageDeflate:!1,maxPayload:He}),f=new AbortController,g=()=>{},k=()=>{f.abort(),g()};e.signal.addEventListener("abort",k,{once:!0});let R=setTimeout(k,Math.max(1,a.leaseExpiresAtMs-Date.now())),w=[],A=0,N=0,D=0,S=!1,M=!1,j=!1,C,z,Q,Y=(W)=>{Q=new r(W,"Bound terminal input was refused."),k()};u.on("error",()=>Y("pty_relay_unavailable")),u.on("close",k),u.on("message",(W,q)=>{if(f.signal.aborted)return;if(!M){Y("pty_not_ready");return}let ne=Array.isArray(W)?Buffer.concat(W):W instanceof ArrayBuffer?Buffer.from(W):W;if(ne.length===0)return;let ye=w.at(-1),le=q&&ye!==void 0&&"data"in ye&&ye.data.length+ne.length<=He;if(ne.length>He||A+ne.length>qo){Y("pty_input_backpressure");return}if(le)ye.data=Buffer.concat([ye.data,ne]);else if(q)w.push({data:Buffer.from(ne)});else try{let fe=JSON.parse(ne.toString("utf8"));if(fe&&fe.t==="close"&&Object.keys(fe).length===1){j=!0,k();return}if(!fe||fe.t!=="resize"||Object.keys(fe).length!==3||![fe.cols,fe.rows].every((ee)=>Number.isSafeInteger(ee)&&ee>=1&&ee<=yt))throw Error("invalid_control");w.push({cols:fe.cols,rows:fe.rows,bytes:ne.length})}catch{Y("invalid_pty_control");return}A+=ne.length,g()});function re(W){return Vo(JSON.stringify({...l.scope,version:1,sessionId:a.sessionId,operationId:a.operationId,job:{...W,output:[],pty:W.pty?{...W.pty,output:[]}:void 0}}))}function we(W){if(!W.ok)Fe(W.error);let q=W.job;if(W.generation!==l.scope.generation||q.jobId!==a.jobId||!q.pty||q.leaseExpiresAtMs>a.leaseExpiresAtMs||q.process&&q.process.executorLaunchId!==l.scope.executorLaunchId||q.process&&z&&(q.process.pid!==z.pid||q.process.processGroupId!==z.processGroupId)||q.state!=="starting"&&(q.environmentRevision!==l.environment.revision||q.environmentSnapshotId!==l.environment.snapshotId))Fe("pty_binding_changed");if(re(q),q.process)z??={...q.process};return q}async function Ie(W){l.assertCurrent();let q=await l.request(W,f.signal);if(l.assertCurrent(),f.signal.aborted)Fe("cancelled");let ne=we(q);if(ne.inputSequence!==N)Fe("job_input_sequence");if(!Wr(ne)&&ne.leaseExpiresAtMs<=Date.now())Fe("pty_binding_changed");return ne}function Z(W){if(l.assertCurrent(),f.signal.aborted||u.readyState!==wn.OPEN||u.bufferedAmount+Buffer.byteLength(W)>Lo)Fe("pty_output_backpressure");u.send(W)}function be(W){if(W.firstCursor>D+1)D=W.firstCursor-1;for(let q of W.pty.output){if(q.cursor<=D)continue;if(q.cursor!==D+1)Fe("pty_output_gap");let ne=Buffer.from(q.dataBase64,"base64");if(u.bufferedAmount+ne.length>Lo)return!1;Z(ne),D=q.cursor}if(D!==W.nextCursor)Fe("pty_output_gap");return!0}async function ke(W,q){let ne;try{await Promise.race([e.emit(W,q),new Promise((ye,le)=>{ne=setTimeout(()=>le(new r("pty_event_unavailable","Terminal metadata delivery timed out.")),2000)})])}finally{clearTimeout(ne)}}async function ae(){let W=AbortSignal.timeout(bn),q=l.request({jobId:a.jobId,action:"cancel",input:{}},W),ne,ye=new Promise((le,fe)=>{if(ne=()=>fe(new r("pty_cleanup_unconfirmed","Terminal cleanup acknowledgement was not observed within authority.")),W.addEventListener("abort",ne,{once:!0}),W.aborted)ne()});try{let le=await Promise.race([q,ye]);if(W.aborted)Fe("pty_cleanup_unconfirmed");return we(le)}finally{W.removeEventListener("abort",ne)}}try{await new Promise((le,fe)=>{let ee=setTimeout(()=>{k(),fe(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),me=()=>{clearTimeout(ee),fe(new r("cancelled","Terminal pairing was cancelled."))};if(f.signal.addEventListener("abort",me,{once:!0}),u.once("open",()=>{clearTimeout(ee),f.signal.removeEventListener("abort",me),le()}),f.signal.aborted)me()}),l.assertCurrent(),S=!0,C=await Ie({jobId:a.jobId,action:"start",input:{mode:"pty",cols:a.cols,rows:a.rows,leaseExpiresAtMs:a.leaseExpiresAtMs}});let W=Date.now()+5000;while(C.state==="starting"){if(Date.now()>=W)Fe("pty_not_ready");await new Promise((le)=>setTimeout(le,25)),C=await Ie({jobId:a.jobId,action:"inspect",input:{after:D}})}if(C.state!=="running"||C.inputSequence!==0||C.leaseExpiresAtMs<=Date.now())Fe("pty_not_ready");await ke("pty.ready",re(C)),M=!0,Z(JSON.stringify({t:"open",cols:C.pty.cols,rows:C.pty.rows,receipt:re(C)}));let q=!1,ne=0,ye=!1;while(!f.signal.aborted){let le=C.firstCursor>D+1,fe=be(C);if(Wr(C)){if(fe)break}else if(le)q=!0;else if(q&&fe&&Date.now()>=ne){q=!1,ne=Date.now()+1000;let{cols:me,rows:De}=C.pty;for(let Me of[{cols:me,rows:De>1?De-1:2},{cols:me,rows:De}]){if(Wr(C))break;let rr=++N;if(C=await Ie({jobId:a.jobId,action:"resize",input:{sequence:rr,...Me}}),C.inputSequence!==rr)Fe("job_input_sequence")}continue}let ee=Wr(C)||ye?void 0:w.shift();if(ee){A-=No(ee);let me=++N;try{C=await Ie("data"in ee?{jobId:a.jobId,action:"input",input:{sequence:me,dataBase64:ee.data.toString("base64")}}:{jobId:a.jobId,action:"resize",input:{sequence:me,cols:ee.cols,rows:ee.rows}})}catch(De){if(!(De instanceof r)||De.code!=="job_input_backpressure")throw De;N-=1,w.unshift(ee),A+=No(ee),ye=!0;continue}if(C.inputSequence!==me)Fe("job_input_sequence")}else if(await new Promise((me)=>{let De=setTimeout(me,ye||!fe?10:50);if(g=()=>{clearTimeout(De),me()},f.signal.aborted||!ye&&w.length)g()}),ye=!1,g=()=>{},!f.signal.aborted&&fe)try{C=await Ie({jobId:a.jobId,action:"inspect",input:{after:D}})}catch(me){if(!j||!(me instanceof r)||me.code!=="cancelled")throw me}}}catch(W){Q??=W}finally{if(M=!1,w.length=0,clearTimeout(R),e.signal.removeEventListener("abort",k),k(),S&&(!C||!Wr(C)))try{C=await ae()}catch{C=void 0}try{if(!C||!Wr(C)||C.pty?.cleanup!=="confirmed")Fe("pty_cleanup_unconfirmed");let W=re(C);if(u.readyState===wn.OPEN)await new Promise((q)=>{let ne=setTimeout(q,500);u.send(JSON.stringify({t:"exit",code:C.exitCode,receipt:W}),()=>{clearTimeout(ne),q()})});await ke("pty.stopped",W)}catch(W){Q??=W}u.terminate()}if(Q)throw Q;if(e.signal.aborted)Fe("cancelled");if(!C)Fe("pty_cleanup_unconfirmed");return{receipt:re(C)}}import{createHash as Yi,randomUUID as Sn}from"crypto";import{spawnSync as Fo}from"child_process";import{closeSync as jo,constants as yn,fstatSync as Xi,fsyncSync as Zi,lstatSync as lt,mkdirSync as Qi,mkdtempSync as Uo,openSync as Mo,readFileSync as ea,readdirSync as zo,realpathSync as kr,rmSync as vn,unlinkSync as ra}from"fs";import{createConnection as ta}from"net";import{dirname as na,join as Ar,sep as kn}from"path";import{tmpdir as $o}from"os";var er=new Map,vr=new Map;function mr(e,a){return Yi("sha256").update(JSON.stringify([e,a])).digest("hex")}function Fr(e){try{Qi(e,{mode:448})}catch(l){if(!(l instanceof Error&&("code"in l)&&l.code==="EEXIST"))throw l}let a=lt(e);if(!a.isDirectory()||a.isSymbolicLink()||!G(a)||kr(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function oa(e){let a;try{a=lt(e)}catch(l){if(l instanceof Error&&"code"in l&&l.code==="ENOENT")return!1;throw l}return!a.isDirectory()||a.isSymbolicLink()||zo(e).length>0}function sa(e){if(process.platform==="win32")return Ea();let a=e.map((l)=>{try{return kr(l)}catch{return l}});for(let l of[()=>Ea(),()=>kr("/dev/shm"),()=>kr($o())]){let u;try{u=l()}catch{continue}if(!a.some((f)=>u===f||u.startsWith(f.endsWith(kn)?f:f+kn)))return u}throw new r("invalid_hands_workspace","A Session can't work in this computer's temporary folder itself; start it in a project folder inside it.")}function $t(e){let a=mr(e.root,e.runId),l=e.previousRuntimeDirectories?.find((k)=>oa(Ar(k,"jobs",a.slice(0,16))))??e.runtimeDirectory;Fr(l);let u=Ar(l,"jobs");Fr(u);let f=Ar(u,a.slice(0,16));if(e.maxScopes!==void 0){let k=zo(u);if(!Number.isSafeInteger(e.maxScopes)||e.maxScopes<1||k.length>e.maxScopes||!k.includes(a.slice(0,16))&&k.length>=e.maxScopes)throw new r("process_journal_capacity","Managed process receipt capacity is full; preserve uncertain jobs and reconcile their existing receipts before starting more work.")}Fr(f);let g=Uo(Ar(sa(e.folders??[]),"reason-j-"));try{return Fr(g),{journalDirectory:f,scopeId:a,launchDirectory:g,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${Sn()}`:Ar(g,"control.sock"),disposeSocket:()=>vn(g,{recursive:!0,force:!0})}}catch(k){throw vn(g,{recursive:!0,force:!0}),k}}var ia=60000,aa=5000;function ca(e){if(process.platform==="win32")return da(e);let a=Fo("ps",["-o","lstart=","-p",String(e)],{encoding:"utf8",timeout:2000,env:{...process.env,LC_ALL:"C",LANG:"C"}}),l=a.status===0?/^\w{3} (\w{3}) +(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/.exec(a.stdout.trim()):null,u=l?"JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(l[1]):-1;if(!l||u<0||u%3!==0)return null;let f=new Date(Number(l[6]),u/3,Number(l[2]),Number(l[3]),Number(l[4]),Number(l[5])).getTime();return Number.isFinite(f)?f:null}function da(e){let a=Fo(B("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().ToString('o')`],{encoding:"utf8",timeout:5000,windowsHide:!0,env:It()}),l=a.status===0?Date.parse(a.stdout.trim()):Number.NaN;return Number.isFinite(l)?l:null}function Ko(e,a={}){let l=Ar(e.journalDirectory,"owner.lock"),u;try{u=Mo(l,yn.O_RDONLY|yn.O_NOFOLLOW)}catch{return null}try{let f=Xi(u);if(!f.isFile()||f.nlink!==1||!G(f)||f.size>4096)return null;let g=null;try{g=JSON.parse(ea(u,"utf8"))}catch{}let k;if(g===null){if((a.now??Date.now)()-f.mtimeMs<ia)return null;k={reason:"never_written",executorLaunchId:null}}else{let{version:A,scopeId:N,pid:D,createdAtMs:S,executorLaunchId:M}=g;if(A!==1||N!==e.scopeId||typeof M!=="string"||typeof D!=="number"||!Number.isSafeInteger(D)||D<1||D===process.pid||typeof S!=="number"||!Number.isSafeInteger(S))return null;if(!(a.exists??((C)=>{try{return process.kill(C,0),!0}catch(z){return!(z instanceof Error&&("code"in z)&&z.code==="ESRCH")}}))(D))k={reason:"owner_exited",executorLaunchId:M};else{let C=(a.startedAtMs??ca)(D);if(C===null||C<=S+aa)return null;k={reason:"pid_reused",executorLaunchId:M}}}let R=lt(l);if(R.dev!==f.dev||R.ino!==f.ino)return null;ra(l);let w=Mo(e.journalDirectory,yn.O_RDONLY);try{Zi(w)}finally{jo(w)}return k}catch{return null}finally{jo(u)}}function Go(e){let a={...e,workspace:e.workspace&&Object.freeze({...e.workspace}),previewAuthority:e.previewAuthority&&Object.freeze({...e.previewAuthority,owner:Object.freeze({...e.previewAuthority.owner}),deniedPorts:new Set(e.previewAuthority.deniedPorts)})},l=mr(a.root,a.runId);if(er.has(l)||a.operationId!==void 0&&vr.has(a.operationId))throw new r("hands_jobs_busy","The Session already has a live Hands job supervisor.");let u={binding:a,key:l,terminals:new Map};if(a.previewAuthority&&a.environment)u.previews=Ho({authority:a.previewAuthority,runId:a.runId,expiresAtMs:a.expiresAtMs,executorLaunchId:a.executorLaunchId,environment:a.environment,isCurrent:()=>er.get(u.key)===u,identity:()=>{try{return Ur(a)}catch{return null}},inspect:(f,g)=>{if(er.get(u.key)!==u)throw new r("preview_unavailable","The Hands supervisor is no longer current.");return Jo(a,{jobId:f,action:"inspect",input:{after:0}},g)}});if(er.set(l,u),a.operationId!==void 0)vr.set(a.operationId,u);return()=>{if(er.get(u.key)===u)er.delete(u.key);if(a.operationId!==void 0&&vr.get(a.operationId)===u)vr.delete(a.operationId);u.previews?.dispose();for(let f of u.terminals.values())f.abort()}}var la=5000,ua=20;async function Ga(e){let a=(f)=>{throw new r("hands_rebind_unavailable",f)};if(!ce(e.operationId)||!ce(e.runId)||!ce(e.fenceId)||!Ee(e.targetGeneration))a("Reason sent an invalid Hands rebind.");let l=vr.get(e.operationId);if(!l||l.binding.root!==e.root)return a("No live Hands supervisor owns this operation.");for(let f=Date.now()+la;;){if(e.signal?.aborted)a("The Hands rebind was cancelled.");if(vr.get(e.operationId)!==l)a("The Hands supervisor is no longer current.");let g=null;try{g=Ur(l.binding)}catch{}if(g&&g.generation===e.targetGeneration&&g.fenceId===e.fenceId)break;if(g&&g.generation>e.targetGeneration||Date.now()>=f)a("The executor did not adopt this take.");await new Promise((k)=>setTimeout(k,ua))}if(vr.get(e.operationId)!==l||er.get(l.key)!==l)a("The Hands supervisor is no longer current.");let u=mr(e.root,e.runId);if(l.key===u)return;if(er.has(u))a("The taking run already has a live Hands job supervisor.");er.delete(l.key);for(let f of l.terminals.values())f.abort();l.key=u,er.set(u,l)}function Qe(e){let a="operationId"in e?vr.get(e.operationId):er.get(mr(e.root,e.runId)),l=a&&a.binding.root===e.root?a.binding:void 0;if(!l?.environment||l.expiresAtMs<=Date.now())throw new r("environment_unavailable","No live Hands supervisor owns this environment.");return l.environment.install(e.payload)}async function Ka(e){let a=er.get(mr(e.root,e.runId));if(!a?.previews||!e.owner)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return a.previews.open(e.payload,e.owner,e.signal)}async function Ja(e){let a=er.get(mr(e.root,e.runId));if(!a?.previews||!e.owner||e.signal.aborted)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return a.previews.close(e.payload,e.owner)}async function rn(e){let a=mr(e.root,e.runId),l=er.get(a),u=l?.binding,f=u?.runId,g=u?.previewAuthority,k=u?.environment,R=e.owner&&{...e.owner},w=e.authority&&{...e.authority},A=()=>{throw new r("pty_binding_unavailable","No current authenticated Hands scope owns this terminal.")};if(!l||!u||!g||!k||!R||!w||!u.workspace)return A();let N=Object.freeze({...u.workspace}),D=Ur(u),S=k.current(),M=()=>{if(er.get(a)!==l||R.organization_id!==g.owner.organization_id||R.user_id!==g.owner.user_id||R.device_id!==g.owner.device_id||e.deviceId!==g.owner.device_id||e.rootId!==g.rootId||X(e.workspace)!==X(N))A();let C=Ur(u),z=k.current();if(C.generation!==D.generation||C.fenceId!==D.fenceId||z.run_id!==f||z.device_id!==e.deviceId||z.root_id!==e.rootId||z.snapshot_id!==S.snapshot_id||z.revision!==S.revision||z.binding.target_generation!==D.generation||z.binding.target_fence_id!==D.fenceId||w.device_id!==e.deviceId||w.binding!==z.binding.kind||w.target_revision!==z.binding.target_revision||w.root_grant_revision!==z.binding.root_grant_revision||w.target_generation!==D.generation||w.target_fence_id!==D.fenceId)A()};if(M(),new URL(e.session.relayUrl).origin!==g.relayOrigin||l.terminals.has(e.session.jobId)||l.terminals.size>=4)return A();let j=new AbortController;l.terminals.set(e.session.jobId,j);try{return await Bo({session:{...e.session,leaseExpiresAtMs:Math.min(e.session.leaseExpiresAtMs,D.expiresAtMs,Date.parse(S.expires_at))},signal:AbortSignal.any([e.signal,j.signal]),emit:e.emit,binding:{assertCurrent:M,environment:{revision:S.revision,snapshotId:S.snapshot_id},scope:{runId:e.runId,deviceId:e.deviceId,rootId:e.rootId,workspace:N,binding:S.binding.kind,targetRevision:S.binding.target_revision,rootGrantRevision:S.binding.root_grant_revision,generation:D.generation,fenceId:D.fenceId,executorLaunchId:D.executorLaunchId},request:(C,z)=>oi(D,Ri(JSON.stringify({...C,type:"job",version:2,generation:D.generation,id:Sn()})),z)}})}finally{if(l.terminals.get(e.session.jobId)===j)l.terminals.delete(e.session.jobId)}}async function Xa(e){if(it(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let a=er.get(mr(e.root,e.runId))?.binding;if(!a||a.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","No live Hands supervisor owns this Session and root.");return Jo(a,e.payload,e.signal)}var fa=1e4,pa=20,_a=_t/2,ha=qt/2,wa=(e)=>e.output.reduce((a,l)=>a+l.text.length,0);async function Jo(e,a,l){if(Object.keys(a).some((A)=>!["jobId","action","input","waitForExitMs"].includes(A)))throw new r("invalid_payload","Unexpected job control field.");let{waitForExitMs:u,...f}=a;if(u!==void 0&&(f.action!=="start"||typeof f.input!=="object"||f.input===null||!("script"in f.input)||typeof u!=="number"||!Number.isSafeInteger(u)||u<1||u>fa))throw new r("invalid_payload","Only a script start may wait for its job, within its bound.");let g=(A)=>{let N=Ur(e);return oi(N,Ri(JSON.stringify({...A,type:"job",version:2,generation:N.generation,id:Sn()})),l)},k=await g(f);if(u===void 0)return k;let R=Date.now()+u,w=k;while(w.ok&&["starting","running"].includes(w.job.state)&&w.job.output.length<_a&&wa(w.job)<ha&&!l.aborted&&Date.now()<R){if(await new Promise((A)=>setTimeout(A,Math.min(pa,R-Date.now()))),l.aborted)break;try{let A=await g({jobId:f.jobId,action:"inspect",input:{after:0}});if(!A.ok)break;w=A}catch{break}}return w}function Ur(e){if(e.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","Hands authority expired.");let a=e.readIdentity?e.readIdentity():e;if(!a||!Ee(a.generation)||!ce(a.fenceId)||a.generation<e.generation||a.generation===e.generation&&a.fenceId!==e.fenceId)throw new r("hands_jobs_unavailable","The live Hands fencing identity could not be verified.");return e.generation=a.generation,e.fenceId=a.fenceId,{...e}}function oi(e,a,l){if(l.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((u,f)=>{let g=ta(e.socketPath),k="",R=!1,w,A=(D,S)=>{if(R)return;if(R=!0,clearTimeout(w),l.removeEventListener("abort",N),g.destroy(),D)f(D);else u(S)},N=()=>A(new r("cancelled","Job control waiter cancelled; inspect before retrying mutations."));l.addEventListener("abort",N,{once:!0}),g.setEncoding("utf8"),w=setTimeout(()=>A(new r("hands_job_result_unknown","Job control timed out; inspect before retrying mutations.")),Math.min(1e4,Math.max(1,e.expiresAtMs-Date.now()))),g.on("error",()=>A(new r("hands_job_result_unknown","Hands job control connection failed."))),g.once("connect",()=>g.write(JSON.stringify({version:1,scopeId:e.scopeId,fenceId:e.fenceId,executorLaunchId:e.executorLaunchId,request:a})+`
|
|
3
3
|
`)),g.on("data",(D)=>{if(k+=D,Buffer.byteLength(k)>Wt)A(new r("hands_job_result_unknown","Hands job result exceeded its bound."))}),g.once("end",()=>{if(Date.now()>=e.expiresAtMs){A(new r("hands_job_result_unknown","Hands authority expired before the result was acknowledged."));return}try{let D=Ti(k.trim());if(D.id!==a.id||D.generation!==e.generation||D.ok&&D.job.jobId!==a.jobId)throw Error("identity");A(void 0,D)}catch{A(new r("hands_job_result_unknown","Hands job response identity or shape was invalid."))}}),g.once("close",()=>{if(!R)A(new r("hands_job_result_unknown","Hands job control closed before an acknowledged result."))})})}function Wo(e){let a=kr(e.root),l=e.authority,u=Date.parse(e.leaseUntil),f=()=>{if(e.signal.throwIfAborted(),!Number.isFinite(u)||u<=Date.now())throw Error("local_device_gh_lease_expired")};if(f(),l.readOnly&&l.generation===null)return{root:a,readOnly:!0,signal:e.signal,deadlineMs:u,assertCurrent:f};let g=mr(a,e.runId),k=er.get(g),R=k?.binding;if(!R?.environment||!R.workspace||R.localGithubConfinement!==!0)throw Error("local_device_gh_confinement_unavailable");let w=R.environment.current(),A=()=>{f();let D=R.environment.current(),S=Ur(R);if(er.get(g)!==k||D.github_auth!=="local_gh"||D.run_id!==R.runId||l.runId!==e.runId||D.device_id!==l.deviceId||D.root_id!==l.rootId||String(D.binding.root_grant_revision)!==l.rootRevision||D.binding.target_generation!==l.generation||D.binding.target_fence_id!==l.fenceId||S.generation!==l.generation||S.fenceId!==l.fenceId||D.snapshot_id!==w.snapshot_id||D.revision!==w.revision)throw Error("local_device_gh_authority_changed")};A();let N=Ge(a,R.workspace);return{root:N.boundary,signal:e.signal,deadlineMs:u,privateDirectory:na(R.environment.path),repoPath:N.path,readOnly:l.readOnly,forbiddenSecretValues:Object.values(w.variables),secretNames:(D)=>Object.entries(w.variables).filter(([,S])=>S.trim()===D.trim()).map(([S])=>`variable ${S}`),assertCurrent:A}}async function Ya(e,a){let l=Ct.parse(e.request),u=Je.parse(e.authority);if(u.contributorRefresh&&l.kind==="read"&&u.readOnly)return a(Wo(e));let f=Boolean(u.contributorRefresh);if(f&&(u.merge||l.kind!=="pr_mutation"||l.mutation.action!=="edit"||typeof l.mutation.body!=="string"||l.mutation.title!==void 0||l.mutation.base!==void 0||u.readOnly||u.runId!==e.runId||u.repoFullName!==l.repoFullName))throw Error("local_device_gh_contributor_refresh_authority_invalid");if(l.kind!=="pr_merge"&&!f){if(u.merge)throw Error("local_device_gh_merge_authority_invalid");return a(Wo(e))}if(!f&&(!u.merge||u.readOnly||u.runId!==e.runId||u.repoFullName!==l.repoFullName||u.merge.source==="agent"&&(u.generation===null||u.fenceId===null)))throw Error("local_device_gh_merge_authority_invalid");let g=kr(e.root),k=lt(g),R=Date.parse(e.leaseUntil);if(!Number.isFinite(R)||R<=Date.now())throw Error("local_device_gh_lease_expired");let w=kr($o());if(w===g||w.startsWith(g+kn))throw Error("local_device_gh_private_scope_unavailable");let A=Uo(Ar(w,"reason-gh-merge-"));try{Fr(A);let N=()=>{if(e.signal.throwIfAborted(),Date.now()>=R)throw Error("local_device_gh_lease_expired");let D=lt(e.root);if(D.isSymbolicLink()||D.dev!==k.dev||D.ino!==k.ino||kr(e.root)!==g)throw Error("local_device_gh_authority_changed");Fr(A)};return N(),await a({root:g,readOnly:!1,privateDirectory:A,forbiddenSecretValues:[],signal:e.signal,deadlineMs:R,assertCurrent:N})}finally{vn(A,{recursive:!0,force:!0})}}var Zo=43200000;function $r(e){return Number.isSafeInteger(e)&&Math.abs(e)<=8640000000000000?e:null}function Yo(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Xo(e,a){return Object.keys(e).length===a.length&&a.every((l)=>Object.hasOwn(e,l))}function Za(e){if(!Yo(e)||!Xo(e,["version","outcome","clock_source","validation_now_ms","expiry_ms","remaining_ms","maximum_lifetime_ms","cli_artifact"])||e.version!==1||e.maximum_lifetime_ms!==43200000||typeof e.outcome!=="string"||!["accepted","parse","noncanonical","expired","over_cap"].includes(e.outcome)||typeof e.clock_source!=="string"||!["date_now","injected"].includes(e.clock_source))return null;for(let u of["validation_now_ms","expiry_ms"]){let f=e[u];if(f!==null&&(typeof f!=="number"||$r(f)===null))return null}if(e.remaining_ms!==null&&(typeof e.remaining_ms!=="number"||!Number.isSafeInteger(e.remaining_ms)))return null;let a=typeof e.expiry_ms==="number"&&typeof e.validation_now_ms==="number"?e.expiry_ms-e.validation_now_ms:null;if(e.remaining_ms!==(a!==null&&Number.isSafeInteger(a)?a:null))return null;if(e.outcome==="parse"&&e.expiry_ms!==null)return null;if(e.outcome!=="parse"&&e.expiry_ms===null)return null;if(e.outcome==="expired"&&!(typeof a==="number"&&a<=0))return null;if(e.outcome==="over_cap"&&!(typeof a==="number"&&a>43200000))return null;if(e.outcome==="accepted"&&!(typeof a==="number"&&a>0&&a<=43200000))return null;let l=e.cli_artifact;if(!Yo(l)||!Xo(l,["kind","status","sha256","observed_at_ms"])||l.observed_at_ms!==null&&(typeof l.observed_at_ms!=="number"||$r(l.observed_at_ms)===null))return null;if(l.kind==="entrypoint_file"){if(l.status!=="observed"||typeof l.sha256!=="string"||!/^[a-f0-9]{64}$/.test(l.sha256)||l.observed_at_ms===null)return null}else if(l.kind!=="unavailable"||l.sha256!==null||typeof l.status!=="string"||!["unsupported_entrypoint","read_failed","file_changed","size_limit","time_limit"].includes(l.status))return null;return e}var En=h({kind:c(["workspace_source","mcp_control"]),target_revision:o().int().nonnegative(),root_grant_revision:o().int().positive()}),Qo=new RegExp(dr.tokenPattern),va=h({token_url:zr().max(2048),request_token:t().min(1).max(8192).regex(Qo),aws_credentials_url:zr().max(2048).nullable()});function es(e,a){let l=(u,f)=>{try{let g=new URL(u);return g.origin===new URL(a).origin&&g.pathname===f&&!g.username&&!g.password&&!g.search&&!g.hash}catch{return!1}};if(!Qo.test(e.request_token)||!l(e.token_url,dr.tokenPath)||e.aws_credentials_url!==null&&!l(e.aws_credentials_url,dr.awsPath))return null;return{REASON_OIDC_TOKEN_URL:e.token_url,REASON_OIDC_REQUEST_TOKEN:e.request_token,...e.aws_credentials_url!==null?{AWS_CONTAINER_CREDENTIALS_FULL_URI:e.aws_credentials_url,AWS_CONTAINER_AUTHORIZATION_TOKEN:e.request_token}:{}}}function rs(e){return new TextEncoder().encode(e).byteLength}function ka(e){return rs(JSON.stringify(e)+`
|
|
4
4
|
`)}var si=h({version:i(1),snapshot_id:V(),revision:o().int().positive(),run_id:t().min(1).max(160),device_id:V(),root_id:V(),binding:En.extend({target_generation:o().int().positive(),target_fence_id:V()}),expires_at:I.datetime({offset:!0}),variables:$e(t().max(128).regex(cn),t().refine((e)=>!e.includes("\x00")&&rs(e)<=Re.valueBytes)).refine((e)=>Object.keys(e).length<=Re.variables),github_auth:i("local_gh").optional(),git:h({base_url:zr().max(2048),token:t().min(1).max(4096).regex(/^[A-Za-z0-9._~-]+$/),expires_at:I.datetime({offset:!0})}).nullable(),cloud_access:va.optional()}).refine((e)=>e.github_auth!=="local_gh"||e.git===null,"conflicting git authority").refine((e)=>ka(e)<=Re.snapshotBytes,"snapshot too large");import{spawn as Sa}from"child_process";import{basename as Ra,isAbsolute as Ef}from"path";var Oa=0,ts=120000,ns=15000,xa=65536;function Rn(e=process.execPath,a=process.argv[1]){let l=Ra(e),u=(l.startsWith("bun")||l.startsWith("node"))&&typeof a==="string"&&a.length>0;return{command:e,prefix:u?[a]:[]}}function nn(e={}){let{command:a,prefix:l}=Rn(e.executablePath,e.sourceEntrypoint),u=e.spawnProcess??Sa,f=e.now??Date.now,g=null,k=0,R=!1,w=(N)=>{try{N.kill("SIGKILL")}catch{}},A=()=>{if(R)return;if(g&&f()-k<ts-ns)return;if(g){let D=g;g=null,w(D)}let N;try{N=u(a,[...l,"__device","__hands-worker","--handoff-fd",String(Oa)],{cwd:"/",env:{PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin"},shell:!1,stdio:["pipe","ignore","pipe"]})}catch{return}g=N,k=f(),N.on("error",()=>{if(g===N)g=null}),N.once("exit",(D,S)=>{if(g!==N)return;g=null,e.log?.("hands.worker_prespawn_exited",{exit_code:D,exit_signal:S})}),e.log?.("hands.worker_prespawned",{pid:N.pid??null})};return{arm:A,take(N){let D=g;if(!D||R)return null;let S=N.args.at(-1),M=N.options.env,j=N.options.cwd,C=[...l,"__device","__hands-worker","--config"];if(N.command!==a||N.args.length!==C.length+1||C.some((re,we)=>N.args[we]!==re)||typeof S!=="string"||!M||typeof j!=="string"||N.options.shell||JSON.stringify(N.options.stdio)!==JSON.stringify(["ignore","ignore","pipe"]))return null;g=null;let z=D.stdin,Q={configPath:S,cwd:j,env:Object.fromEntries(Object.entries(M).filter((re)=>typeof re[1]==="string"))},Y=JSON.stringify(Q);if(D.exitCode!==null||D.signalCode!==null||!z||z.destroyed||f()-k>=ts-ns||Buffer.byteLength(Y,"utf8")>xa)return w(D),null;return z.on("error",()=>{return}),z.end(Y),D.once("exit",()=>{A()}),e.log?.("hands.worker_prespawn_taken",{pid:D.pid??null}),D},adopt(N){N.once("exit",()=>{A()})},close(){if(R=!0,g)w(g);g=null}}}import{accessSync as Ca,constants as Ha,statSync as Na}from"fs";import{homedir as La,tmpdir as Ba,userInfo as ja}from"os";import{delimiter as Ma,win32 as Fa}from"path";var Pa=new Set(["ALL_PROXY","BUN_BE_BUN","BUN_OPTIONS","CURL_CA_BUNDLE","GIT_SSL_CAINFO","GRPC_DEFAULT_SSL_ROOTS_FILE_PATH","HTTPS_PROXY","HTTP_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED","REQUESTS_CA_BUNDLE","SSLKEYLOGFILE","SSL_CERT_DIR","SSL_CERT_FILE","all_proxy","http_proxy","https_proxy","no_proxy"]);var Ia=["BUN_CONFIG_","BUN_INSPECT","DYLD_","NODE_DEBUG"],Aa=new Set(["BUN_INSTALL"]);var Ta=/^--(?:max-old-space-size|max-semi-space-size|stack-size)=\d{1,9}$/;function Da(e){return(e??"").split(/\s+/).filter(Boolean).every((a)=>Ta.test(a.replaceAll("_","-")))}function pt(e){return Object.keys(e).filter((a)=>Pa.has(a)&&!(a==="NODE_OPTIONS"&&Da(e[a]))||Ia.some((l)=>a.startsWith(l))||a.startsWith("BUN_")&&!Aa.has(a)).sort()}var Ua=new Set(["HOME","PATH","PWD","OLDPWD","SHLVL","_","TMPDIR","TMP","TEMP","SHELL","BASH_ENV","ENV","ZDOTDIR","PROMPT_COMMAND","IFS","CDPATH","GLOBIGNORE","SHELLOPTS","BASHOPTS","NODE_PATH"]),za=/^(?:ARA_|REASON_|PI_|GIT_|GH_|GITHUB_|LD_|DYLD_|BUN_|BASH_FUNC_|SSH_)/,$a=/TOKEN|SECRET|PASSW|PASSPHRASE|CREDENTIAL|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|AUTH/i,sc=/^[A-Za-z_][A-Za-z0-9_]*$/;function ci(e=process.env){let a=(f)=>{if(!(process.platform==="win32"?Fa.isAbsolute(f):f.startsWith("/"))||/[\0\r\n]/.test(f)||f.length>32768)throw Error("invalid_host_execution_environment");return f};if(e.PATH!==void 0&&(/[\0\r\n]/.test(e.PATH)||e.PATH.length>32768))throw Error("invalid_host_execution_environment");let l=new Set(pt(e)),u=Object.fromEntries(Object.entries(e).filter((f)=>{let[g,k]=f;return typeof k==="string"&&k.length<=32768&&!k.includes("\x00")&&g.length<=128&&sc.test(g)&&!l.has(g)&&!Ua.has(g)&&!za.test(g)&&!$a.test(g)}).sort(([f],[g])=>f.localeCompare(g)).slice(0,512));return{home:a(e.HOME||(process.platform==="win32"?e.USERPROFILE:void 0)||La()),path:((f)=>process.platform==="win32"?Oo(f):f)(_i(e.PATH??"").join(Ma)||Ft),temporaryDirectory:a(e.TMPDIR||e.TMP||e.TEMP||Ba()),variables:u}}function li(e=process.env,a=()=>ja().shell){if(process.platform==="win32")return Ye();let l=(f)=>{if(!f||!/^\/[A-Za-z0-9._/-]*\/(?:bash|zsh)$/.test(f))return!1;try{return Ca(f,Ha.X_OK),Na(f).isFile()}catch{return!1}};if(l(e.SHELL))return e.SHELL;let u;try{u=a()}catch{u=void 0}return l(u)?u:"/bin/zsh"}import{readdir as ac}from"fs/promises";var cc=15000;function Eo(e){let a=e instanceof Error&&"code"in e?e.code:null;return a==="EPERM"||a==="EACCES"}function ko(e){return new r("folder_access_denied",`macOS blocked Reason from opening ${e}. Allow Reason in System Settings \u203A Privacy & Security \u203A Files and Folders `+"(or Full Disk Access), then restart the Reason app or worker on this Mac and try again: until it restarts it keeps the earlier refusal.")}async function os(e,{timeoutMs:a=cc,open:l=(u)=>ac(u)}={}){let u,f=new Promise((g)=>{u=setTimeout(()=>g("pending"),a)});try{if(await Promise.race([l(e).then(()=>"open"),f])==="pending")throw new r("folder_access_pending",`macOS is asking whether Reason may open ${e}. Answer the prompt on this Mac, then try again.`)}catch(g){if(Eo(g))throw ko(e);if(g instanceof r)throw g}finally{clearTimeout(u)}}import{chmodSync as Kc,closeSync as Gc,constants as Ln,fstatSync as Jc,lstatSync as Rs,openSync as Vc,readSync as qc,realpathSync as Bn,unlinkSync as Yc}from"fs";import{lookup as Qc}from"dns/promises";import{createRequire as ed}from"module";import{request as rd}from"http";import{request as td}from"https";import Nr from"net";import{platform as As}from"os";import{basename as nd,extname as od,isAbsolute as Os,relative as jn,resolve as Vr,sep as Wn}from"path";var ss=String.raw`
|
|
5
5
|
async (roots) => {
|