@reason-machines/cli-linux-x64 0.2.563 → 0.2.565
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-3stvmqsj.js → agent-network-mnv1fm1c.js} +1 -1
- package/bin/vm-hands/{api-credentials-3wwkpts2.js → api-credentials-082cnpn9.js} +1 -1
- package/bin/vm-hands/{api-9xm5e4g9.js → api-sq672f51.js} +1 -1
- package/bin/vm-hands/{ask-relay-5f92e4c5.js → ask-relay-v5btnjvb.js} +2 -2
- package/bin/vm-hands/connect-cli-rxb3qtra.js +2 -0
- package/bin/vm-hands/{desktop-components-p0zx6qxg.js → desktop-components-099xyxmz.js} +1 -1
- package/bin/vm-hands/{local-automation-0a7enct8.js → local-automation-7pjd5nc1.js} +1 -1
- package/bin/vm-hands/{local-capabilities-d3ycjdyg.js → local-capabilities-ha0ey4zh.js} +1 -1
- package/bin/vm-hands/{local-display-session-pc85z6mg.js → local-display-session-0mkswxgk.js} +1 -1
- package/bin/vm-hands/local-display-video-c3fk87c5.js +2 -0
- package/bin/vm-hands/{local-managed-process-ka331rcr.js → local-managed-process-ahr2jync.js} +1 -1
- package/bin/vm-hands/{managed-runtime-nwj7cn7c.js → managed-runtime-shzb3tr3.js} +1 -1
- package/bin/vm-hands/{network-auto-update-tk104maa.js → network-auto-update-3m94436w.js} +2 -2
- package/bin/vm-hands/{network-sign-in-t9ng36rs.js → network-sign-in-xm79s170.js} +2 -2
- package/bin/vm-hands/{permissions-ywh8x4dq.js → permissions-scffy1px.js} +1 -1
- package/bin/vm-hands/{serve-service-43kmwskj.js → serve-service-grp91ybk.js} +1 -1
- package/bin/vm-hands/{status-ec366bs8.js → status-89999mdn.js} +3 -3
- package/bin/vm-hands/{version-6ys9zwbj.js → version-wyshazh7.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-srtqjjqb.js → vm-hands-entry-lite-1eyg750p.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-jgwjt10t.js → vm-hands-entry-lite-1xhpn3hw.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-d12hx1dk.js → vm-hands-entry-lite-34b4tws6.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-41nn0vbf.js → vm-hands-entry-lite-432khjd5.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-pe374cn6.js → vm-hands-entry-lite-6vnjgy77.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-0jy8mv4a.js → vm-hands-entry-lite-7r27208j.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-mn8rjpxq.js → vm-hands-entry-lite-af45ma9p.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-43bv9hf0.js → vm-hands-entry-lite-bsk184m7.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-1wxwsb3f.js → vm-hands-entry-lite-dy204qh4.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-61p78r72.js → vm-hands-entry-lite-gcqqnnze.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-vbqfmsd3.js → vm-hands-entry-lite-ncyrz48z.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-frg1b1rg.js → vm-hands-entry-lite-ngn4tafr.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-j8s2vqpf.js → vm-hands-entry-lite-pt19vacn.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-1w39j6vz.js → vm-hands-entry-lite-rqfhfp09.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-k4d5rhpw.js → vm-hands-entry-lite-sz7z1qby.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-zj9esd2g.js → vm-hands-entry-lite-t43bz0ey.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-thstg177.js → vm-hands-entry-lite-t86kt9jz.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-d431ffz0.js → vm-hands-entry-lite-tnj3483k.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-2ngwj96m.js → vm-hands-executor-kyb5t371.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-te2ze1e7.js → vm-hands-op-runner-gkt79hcp.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-09ehkm3c.js → vm-hands-runtime-tdr6j55n.js} +3 -3
- package/package.json +1 -1
- package/bin/vm-hands/connect-cli-d3dp0r1t.js +0 -2
- package/bin/vm-hands/local-display-video-40avbg94.js +0 -2
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Pa}from"./vm-hands-entry-lite-cmmb9k3g.js";import{R}from"./vm-hands-entry-lite-z65xva21.js";import{W}from"./vm-hands-entry-lite-33at6g06.js";import{Q,oo,ve,so}from"./vm-hands-entry-lite-2qfmabqn.js";import{Ir}from"./vm-hands-entry-lite-1w39j6vz.js";import{t,o,_,d,n,ll,we,c,i}from"./vm-hands-entry-lite-zpvr7wc6.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 Ca(){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 oo(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 so(s),null}).finally(()=>{if(w.get(u)===h)w.delete(u)}),w.set(u,h),I(h,e.signal)}function Aa(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 no(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(Pa,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{Pa}from"./vm-hands-entry-lite-cmmb9k3g.js";import{R}from"./vm-hands-entry-lite-z65xva21.js";import{W}from"./vm-hands-entry-lite-33at6g06.js";import{Q,oo,ve,so}from"./vm-hands-entry-lite-2qfmabqn.js";import{Ir}from"./vm-hands-entry-lite-rqfhfp09.js";import{t,o,_,d,n,ll,we,c,i}from"./vm-hands-entry-lite-zpvr7wc6.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 Ca(){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 oo(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 so(s),null}).finally(()=>{if(w.get(u)===h)w.delete(u)}),w.set(u,h),I(h,e.signal)}function Aa(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 no(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(Pa,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{Ca,be,Aa,C,no,me};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{R}from"./vm-hands-entry-lite-z65xva21.js";import{w}from"./vm-hands-entry-lite-33at6g06.js";import{ot,as,$i,We}from"./vm-hands-entry-lite-y0jtj8zz.js";import{fs,Ln,jc}from"./vm-hands-entry-lite-
|
|
2
|
+
import{R}from"./vm-hands-entry-lite-z65xva21.js";import{w}from"./vm-hands-entry-lite-33at6g06.js";import{ot,as,$i,We}from"./vm-hands-entry-lite-y0jtj8zz.js";import{fs,Ln,jc}from"./vm-hands-entry-lite-t86kt9jz.js";import{B}from"./vm-hands-entry-lite-pg7nnyc6.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 Oi(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,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{te}from"./vm-hands-entry-lite-kbnxk71q.js";import{U,H,T}from"./vm-hands-entry-lite-qjrgvdbj.js";import{ge,$t,ii,Ao,Po,ur}from"./vm-hands-entry-lite-
|
|
2
|
+
import{te}from"./vm-hands-entry-lite-kbnxk71q.js";import{U,H,T}from"./vm-hands-entry-lite-qjrgvdbj.js";import{ge,$t,ii,Ao,Po,ur}from"./vm-hands-entry-lite-gcqqnnze.js";import{gt}from"./vm-hands-entry-lite-xfak34av.js";import{v,pr,To,ht,ft}from"./vm-hands-entry-lite-b1vanmtv.js";import{b,m}from"./vm-hands-entry-lite-yg4dk99m.js";import{s,Et,qc}from"./vm-hands-entry-lite-12ck5swp.js";import{Ji,I,t,V,o,_,cl,Rt,ga,d,n,we,P,$e,c,i,Xi}from"./vm-hands-entry-lite-zpvr7wc6.js";import{Ye,G}from"./vm-hands-entry-lite-pg7nnyc6.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{randomUUID as X}from"crypto";import{spawn as ke}from"child_process";import{existsSync as Y,lstatSync as de,mkdirSync as Oe,readFileSync as Me,realpathSync as q,rmSync as Te,writeFileSync as je}from"fs";import{dirname as Le,join as A,relative as We,sep as Ne}from"path";var he=["process.run.v1","process.full.v1"],be=600000,ve=1800000,ye=20000,re="process.cancel.v1",oe=n({action:i("start"),request_id:t().uuid(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),cwd:t().min(1).max(4096).refine((e)=>!e.includes("\x00")&&!e.startsWith("/")&&!e.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:c(["host","confined"]).default("host"),timeout_ms:o().int().min(1000).max(ve).default(be).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),B={device_id:t().uuid(),root_id:t().uuid()},Se=P("action",[oe.extend(B),n({...B,action:i("inspect"),process_id:t().uuid(),after:o().int().min(0).default(0),wait_ms:o().int().min(0).max(ye).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),n({...B,action:i("cancel"),process_id:t().uuid()}).strict()]),qe=Ji(Se,{io:"input"}),Je=oe.extend({process_brain_fence:t().uuid(),process_expires_at:I.datetime()}).strict(),W=n({version:i(1),process_id:t().uuid(),state:c(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:o().int().nullable(),first_cursor:o().int().min(0),next_cursor:o().int().min(0),truncated:_(),observed_at:I.datetime(),output:d(n({cursor:o().int().min(1),stream:c(["stdout","stderr"]),text:t().max(32768)}).strict()).max(128)}).strict().refine((e)=>{if(Buffer.byteLength(JSON.stringify(e))>1e5||e.next_cursor<e.first_cursor-1)return!1;if((e.state==="starting"||e.state==="running"||e.state==="uncertain")&&e.exit_code!==null)return!1;if(e.state==="exited"&&(e.exit_code===null||e.exit_code<0||e.exit_code>255))return!1;if(e.state==="cancelled"&&e.exit_code!==130||e.state==="expired"&&e.exit_code!==124)return!1;let p=e.first_cursor-1;for(let l of e.output){if(l.cursor<=p||l.cursor>e.next_cursor)return!1;p=l.cursor}return!0});function Zn(e){return he.includes(e)}var ze=n({operation_constraints:$e(t(),Rt())}),Ge=n({ready:i(!0),version:i(1),execution_mode:c(["host","confined"]),max_timeout_ms:o().int().min(1000).optional()});var xe=n({version:i(1),process_id:t().uuid(),state:c(["queued","cancelled_before_start","not_started"]),exit_code:cl(),output:d(ga()).length(0),first_cursor:i(0),next_cursor:i(0),truncated:i(!1),cancellation_requested:i(!1),reason_code:c(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:I.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),Pe=n({...W.shape,state:c(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:I.datetime().optional(),expires_at:I.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:_(),reason_code:t().nullable().optional(),execution_authority:i("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:n({cause:i("brain_generation_changed"),terminal_confirmed:_(),next_step:c(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:W.shape.state.or(i("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),Be=Ji(Pe),Fe=we([W,xe.refine((e)=>e.state==="cancelled_before_start")]),F=n({version:i(1),process_id:t().uuid(),state:c(["exited","cancelled","expired"]),exit_code:o().int().min(0).max(255),observed_at:I.datetime()}).strict().refine((e)=>(e.state!=="cancelled"||e.exit_code===130)&&(e.state!=="expired"||e.exit_code===124)),Ee=n({process_terminal_observation:F}).strict();function Ma(e,a){let p=Ee.safeParse(e);return p.success&&p.data.process_terminal_observation.process_id===a?p.data:null}var Ba="preview.serve.v1",Fa=43200000;var ja=3,ne="preview.open.v1",se=1,_o="gid_proxy_v1",Ha="egress",yo=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,Re=n({version:i(_o),allowed_domains:d(t().max(260).regex(yo)).max(1024)}).strict(),Ie=Xi((e)=>te(e)!==null,"invalid workspace"),De=n({version:i(1),request_id:V(),session_id:V(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),port:o().int().min(1024).max(65535),workspace:Ie,egress:Re.optional()}).strict(),Ua=De.extend({expires_at:I.datetime()}).strict();var Ce=4,Ae=5000;function K(e,a,p){let l=null;try{l=pr(e)}catch{}To({deviceRelayUrl:l?.deviceRelayUrl??"",binding:l?.binding??null,jobId:a,port:l?.binding.port??0,reason:l?p:"binding_invalid"})}function ie(e){let a=new Map;return{open(p){let l=(w)=>K(p,e.claim.operation_id,w),E;try{E=pr(p)}catch{return l("binding_invalid")}let{binding:h,deviceRelayUrl:N}=E,S=e.claim.owner;if(!S||h.organizationId!==S.organization_id||h.userId!==S.user_id||h.deviceId!==S.device_id||h.rootId!==e.claim.root_id||h.jobId!==e.claim.operation_id||h.fenceId!==e.claim.operation_id||h.generation!==se||h.expiresAtMs>Math.min(Date.now()+v.lifetimeMs+Ae,e.expiresAtMs))return l("binding_mismatch");if(h.expiresAtMs<=Date.now())return l("binding_expired");if(a.get(h.port)?.abort(),a.delete(h.port),a.size>=Ce)return l("preview_capacity");let k=new AbortController;a.set(h.port,k);let y=ft({binding:h,deniedPorts:e.deniedPorts,readCurrentJob:async()=>{if(k.signal.aborted)return null;let w=await e.inspect();return w?{binding:h,executorLaunchId:e.executorLaunchId,job:w}:null}});ht({binding:h,deviceRelayUrl:N,port:y,signal:k.signal}).then((w)=>w.closed,(w)=>{let x=w instanceof Error?w.message:"preview_failed";if(x!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:h.jobId,port:h.port,reason_code:x})}
|
|
3
3
|
`)}).finally(()=>{if(a.get(h.port)===k)a.delete(h.port)})},dispose(){for(let p of a.values())p.abort();a.clear()}}}class lr extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var le=256,J=new Map,pe="preview.serve.v1",M=new Map;function ue(e){let a=M.get(e.operation_id);if(a){if(a.claim!==e)throw D("process_authority_lost");return a}if(M.size>=le)throw D("process_journal_capacity");let p={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return M.set(e.operation_id,p),p}function ae(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ce=(e)=>new Promise((a)=>setTimeout(a,e)),D=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function Ve(e=s(),a=He()){let p=Le(gt({},e)),l=We(Et(e),p),[E,...h]=l.split(Ne);return{directory:A(a,l,"processes"),previous:[A(p,"processes"),...E==="reason"?[A(a,"ara",...h,"processes")]:[]]}}function He(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=qc();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function Qn(e){if(!e.claim.owner||e.signal.aborted||e.expiresAtMs<=Date.now())throw D("process_authority_lost");let a=ue(e.claim);if(a.executing)throw D("process_busy");if(a.executing=!0,a.cancelRequested)return a.phase="settling",ae(e.claim.operation_id);a.phase="starting";let p=e.journals??Ve();Oe(p.directory,{recursive:!0,mode:448});let l=$t({runtimeDirectory:q(p.directory),previousRuntimeDirectories:(p.previous??[]).filter((u)=>Y(u)).map((u)=>q(u)),root:e.root,runId:JSON.stringify([e.claim.owner,e.claim.run_id,e.claim.root_id,e.claim.operation_id]),maxScopes:le,folders:[e.root,e.cwd]});try{for(let u of[e.root,e.cwd])if(!ge(q(u),l.journalDirectory))throw new r("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(u){throw l.disposeSocket(),u}let E=de(l.journalDirectory),h=e.claim.capability===pe,N=()=>J.set(e.claim.operation_id,{path:l.journalDirectory,ino:E.ino,dev:E.dev,anyCompletion:h}),S=l.launchDirectory,k=A(S,"config.json"),y={url:"",transport:"local_job_ipc",directShell:{mode:e.mode,executable:e.shell,jobId:e.claim.operation_id},workerVersion:U,protocolVersion:2,workerArtifactSha256:T,workerEntrypoint:H,targetGeneration:1,fenceId:X(),...process.platform==="win32"?{bashExecutable:Ye()}:{},workRoot:e.root,workspaceAliasPath:e.root,repoPath:e.cwd,jobEnvPath:A(S,"unused.env"),replSocketPath:A(S,"unused.sock"),readyPath:A(S,"ready.json"),directTerminalReceiptPath:A(S,"terminal.json"),launchId:X(),expiresAtMs:e.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:l.journalDirectory,scopeId:l.scopeId},jobControlSocketPath:l.socketPath,...e.prefix?{bashCommandPrefix:e.prefix}:{},...e.jobsUser?{jobsUser:e.jobsUser}:{}},w;try{je(k,JSON.stringify(y),{mode:384});let u=Ao({configPath:k,root:e.cwd,grantedRoot:e.root,workRoot:e.root,temporaryDirectory:S});w=e.spawnWorker?.(k,y)??ke(u.command,u.args,{...u.options,env:e.environment,stdio:[Po,"ignore","ignore"]})}catch(u){throw l.disposeSocket(),u}let x=!1,z=new Promise((u,g)=>{w.once("exit",(f)=>{x=!0,u(f)}),w.once("error",(f)=>{x=!0,g(f)})});z.catch(()=>{});let me={root:e.root,runId:e.claim.run_id,scopeId:l.scopeId,socketPath:l.socketPath,generation:1,fenceId:y.fenceId,executorLaunchId:y.launchId,expiresAtMs:y.expiresAtMs},O=async(u)=>{let g=await ii(me,{type:"job",version:2,generation:1,id:X(),jobId:e.claim.operation_id,...u==="start"?{action:u,input:{script:e.command,leaseExpiresAtMs:e.expiresAtMs}}:u==="inspect"?{action:u,input:{after:0}}:u==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:u,input:{}}},new AbortController().signal);if(!g.ok)throw D(g.error);return g.job},j=!1,L=!1,Q,Z=()=>{j=!0,ur(w,"SIGTERM")};e.signal.addEventListener("abort",Z,{once:!0});let C,ee=0,_e=async(u)=>{let g=[...u.output],f={version:1,process_id:e.claim.operation_id,state:u.state,exit_code:u.exitCode,first_cursor:u.firstCursor,next_cursor:u.nextCursor,truncated:u.truncated,output:g,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(f))>90000&&g.length)g.shift(),f.truncated=!0,f.first_cursor=g[0]?.cursor??f.next_cursor+1;C=W.parse(f),await e.emit(C),ee=Date.now()};try{let u=Math.min(Date.now()+1e4,e.expiresAtMs);while(!Y(y.readyPath)){if(x)throw new r("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if(e.signal.aborted||Date.now()>=u)throw D("process_start_unconfirmed");await ce(25)}let g=JSON.parse(Me(y.readyPath,"utf8"));if(g.launchId!==y.launchId||g.fenceId!==y.fenceId||g.workerArtifactSha256!==T)throw D();if(e.signal.throwIfAborted(),a.cancelRequested)return ae(e.claim.operation_id);let f;try{L=!0,f=await O("start")}catch(R){if(!(R instanceof r)||R.code!=="hands_job_result_unknown")throw R;f=await O("inspect")}if(a.phase="running",a.cancel=async()=>{await O("cancel")},h&&e.preview)a.tunnels=ie({claim:e.claim,executorLaunchId:y.launchId,expiresAtMs:e.expiresAtMs,deniedPorts:e.preview.deniedPorts,inspect:async()=>a.phase==="running"&&!x?await O("probe"):null});if(a.cancelRequested)await a.cancel(),f=await O("inspect");for(;;){if(!["starting","running"].includes(f.state))a.phase="settling",a.cancel=void 0;if(!C||C.state!==f.state||C.next_cursor!==f.nextCursor&&Date.now()-ee>=5000)await _e(f);if(!["starting","running"].includes(f.state))break;if(e.signal.aborted||x)throw D();await ce(1000);try{f=await O("inspect"),Q=void 0}catch(R){if(!(R instanceof r)||R.code!=="hands_job_result_unknown"||e.signal.aborted||x||Date.now()-(Q??=Date.now())>120000)throw R}}if(!C||C.state==="uncertain")throw D();return C}finally{if(a.phase="settling",a.cancel=void 0,a.tunnels?.dispose(),a.tunnels=void 0,await a.cancelInFlight?.catch(()=>{}),e.signal.removeEventListener("abort",Z),!x&&!j)ur(w,"SIGTERM");let u,g=await Promise.race([z.then((f)=>({code:f})),new Promise((f)=>{u=setTimeout(()=>f(null),6000)})]).finally(()=>{clearTimeout(u)});if(!g){try{ur(w,"SIGKILL")}catch{}try{await z}finally{if(x)l.disposeSocket()}throw D("process_cleanup_unconfirmed")}try{if((j||e.signal.aborted)&&g.code===0&&L){b(S);let f=JSON.parse(m(y.directTerminalReceiptPath)),R=F.safeParse(f.observation);if(Object.keys(f).length===4&&f.launch_id===y.launchId&&f.fence_id===y.fenceId&&f.scope_id===l.scopeId&&R.success&&R.data.process_id===e.claim.operation_id){if(h)N();throw new lr(R.data)}}}catch(f){if(f instanceof lr)throw f}finally{if(x)l.disposeSocket()}if(g.code!==0&&!j&&L)throw D("process_cleanup_unconfirmed");if(!j&&g.code===0&&(C&&["exited","cancelled","expired"].includes(C.state)||!L&&a.cancelRequested)||h&&g.code===0&&!L)N()}}async function wo(e,a){if(a.kind===ne&&e.capability===pe){let E=M.get(e.operation_id);if(E?.claim===e&&E.tunnels)E.tunnels.open(a.payload);else K(a.payload,e.operation_id,"server_not_running");return!0}if(a.kind!==re||!Zn(e.capability)||!e.owner||a.payload.process_id!==e.operation_id)return!1;let p=M.get(e.operation_id);if(p&&p.claim!==e)return!1;let l=ue(e);if(l.cancelRequested=!0,l.phase==="running"&&l.cancel)l.cancelInFlight??=l.cancel(),await l.cancelInFlight;return!0}function ei(e,a){M.delete(e);let p=J.get(e);if(!p||a!=="succeeded"&&!p.anyCompletion)return J.delete(e),!1;try{let l=de(p.path);if(!l.isDirectory()||l.isSymbolicLink()||l.ino!==p.ino||l.dev!==p.dev||!G(l)||q(p.path)!==p.path||Y(A(p.path,"owner.lock")))return!1;return Te(p.path,{recursive:!0}),J.delete(e),!0}catch{return!1}}
|
|
4
4
|
export{Zn,Ma,Ba,Fa,ja,_o,Ha,yo,Ua,lr,Qn,wo,ei};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{R}from"./vm-hands-entry-lite-z65xva21.js";import{Fi,ji,St,Yt,ms,gs}from"./vm-hands-entry-lite-
|
|
2
|
+
import{R}from"./vm-hands-entry-lite-z65xva21.js";import{Fi,ji,St,Yt,ms,gs}from"./vm-hands-entry-lite-t86kt9jz.js";import{uc,dc}from"./vm-hands-entry-lite-q62g6sx0.js";import{Ti,Ii,bn,yr,l,mc,Di,gc,vn,Gt,Sn}from"./vm-hands-entry-lite-1b21avcs.js";import{s}from"./vm-hands-entry-lite-12ck5swp.js";import{G}from"./vm-hands-entry-lite-pg7nnyc6.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=ji(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"?Ii:Ti)}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=${Fi}`,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(!ms(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:bn,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 gs({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{gt,gr,Se}from"./vm-hands-entry-lite-xfak34av.js";import{at,kt,Oe,xt,Ke,Dr,Zt,Ne,X,te,Wi}from"./vm-hands-entry-lite-kbnxk71q.js";import{An,Cr}from"./vm-hands-entry-lite-33at6g06.js";import{pc,F,qt,_t,Wt,He,Vt,zo,yt,wn,nt,Ee,ce,it,Pi,Ri,Wo}from"./vm-hands-entry-lite-zp7chzcc.js";import{Ct,Je,ct,Le,Pt,xe,pe}from"./vm-hands-entry-lite-fxptf351.js";import{an,fi,dr,Re,U,H,T,Ro}from"./vm-hands-entry-lite-qjrgvdbj.js";import{Ft,gi,Io,lc,je,Do}from"./vm-hands-entry-lite-s93f3pbv.js";import{ue}from"./vm-hands-entry-lite-cc8hwgxc.js";import{wa}from"./vm-hands-entry-lite-sh4mqy93.js";import{v,Bt,cn,pr,oc,ht,ft}from"./vm-hands-entry-lite-b1vanmtv.js";import{b,m,y}from"./vm-hands-entry-lite-yg4dk99m.js";import{L}from"./vm-hands-entry-lite-fccn6s4j.js";import{$n}from"./vm-hands-entry-lite-k4d5rhpw.js";import{s,Uc,zc,Ge,Wc}from"./vm-hands-entry-lite-12ck5swp.js";import{he,fa,ma,Xc,I,t,V,zr,o,_,d,n,h,P,$e,c,i}from"./vm-hands-entry-lite-zpvr7wc6.js";import{_a}from"./vm-hands-entry-lite-fn2805g8.js";import{Zc,Ye,Sa,B,It,Be,G}from"./vm-hands-entry-lite-pg7nnyc6.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{readFileSync as mo,realpathSync as _o,statSync as Hi}from"fs";import{homedir as Ni}from"os";import{dirname as Li,isAbsolute as Bi,join as dt,sep as ji}from"path";var Ci=()=>{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 ${ma(f.values[0])}`;return`Invalid option: expected one of ${fa(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":""}: ${fa(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 _n(){return{localeError:Ci()}}he(_n());var ti="--proxy",ri="--proxy-ca-file",Mi=262144;class K extends Error{}function hn(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 za(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??Ni(),l=e.statePath??gt();return[Li(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+ji)}function zi(e,a={}){if(!Bi(e))throw new K("The proxy CA file must be an absolute path.");let l,u,f;try{l=_o(e);let R=Hi(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>Mi)throw new K("The proxy CA file must be 256 KB or smaller.");let g=Fi(a).flatMap((R)=>{try{let w=_o(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=mo(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 qa(e,a={}){if(!e.proxyUrl)throw new K("A proxy URL is required.");let l=hn(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=mo(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 go,join as wo,relative as yo,resolve as Tt,sep as Oo}from"path";var At=t().min(1).refine(go,"absolute path required"),ho=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 hn(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",[ho,ho.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)&&!An(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 bo(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(Oo,yo(Tt(e),Tt(a))))}function se(e,a){let l=yo(Tt(e),Tt(a));return l===""||l!==".."&&!l.startsWith(`..${Oo}`)&&!go(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 ni(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 Vi=60000;function To(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())>Vi)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 cn(()=>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 cn(()=>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 gn}from"ws";var Ho=(e)=>("data"in e)?e.data.length:e.bytes,No=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 Wa(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 Lo(e){let{session:a,binding:l}=e;if(l.assertCurrent(),e.signal.aborted||Date.now()>=a.leaseExpiresAtMs)Fe("cancelled");let u=new gn(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>zo){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 Wo(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!==gn.OPEN||u.bufferedAmount+Buffer.byteLength(W)>No)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>No)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(wn),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-=Ho(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+=Ho(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===gn.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 qi,randomUUID as kn}from"crypto";import{spawnSync as Fo}from"child_process";import{closeSync as Bo,constants as bn,fstatSync as Yi,fsyncSync as Xi,lstatSync as lt,mkdirSync as Zi,mkdtempSync as Uo,openSync as jo,readFileSync as Qi,readdirSync as $o,realpathSync as kr,rmSync as yn,unlinkSync as ea}from"fs";import{createConnection as ra}from"net";import{dirname as ta,join as Ar,sep as vn}from"path";import{tmpdir as Ko}from"os";var er=new Map,vr=new Map;function mr(e,a){return qi("sha256").update(JSON.stringify([e,a])).digest("hex")}function Fr(e){try{Zi(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 na(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()||$o(e).length>0}function oa(e){if(process.platform==="win32")return Sa();let a=e.map((l)=>{try{return kr(l)}catch{return l}});for(let l of[()=>Sa(),()=>kr("/dev/shm"),()=>kr(Ko())]){let u;try{u=l()}catch{continue}if(!a.some((f)=>u===f||u.startsWith(f.endsWith(vn)?f:f+vn)))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)=>na(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=$o(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(oa(e.folders??[]),"reason-j-"));try{return Fr(g),{journalDirectory:f,scopeId:a,launchDirectory:g,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${kn()}`:Ar(g,"control.sock"),disposeSocket:()=>yn(g,{recursive:!0,force:!0})}}catch(k){throw yn(g,{recursive:!0,force:!0}),k}}var sa=60000,ia=5000;function aa(e){if(process.platform==="win32")return ca(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 ca(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 Go(e,a={}){let l=Ar(e.journalDirectory,"owner.lock"),u;try{u=jo(l,bn.O_RDONLY|bn.O_NOFOLLOW)}catch{return null}try{let f=Yi(u);if(!f.isFile()||f.nlink!==1||!G(f)||f.size>4096)return null;let g=null;try{g=JSON.parse(Qi(u,"utf8"))}catch{}let k;if(g===null){if((a.now??Date.now)()-f.mtimeMs<sa)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??aa)(D);if(C===null||C<=S+ia)return null;k={reason:"pid_reused",executorLaunchId:M}}}let R=lt(l);if(R.dev!==f.dev||R.ino!==f.ino)return null;ea(l);let w=jo(e.journalDirectory,bn.O_RDONLY);try{Xi(w)}finally{Bo(w)}return k}catch{return null}finally{Bo(u)}}function Jo(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=To({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 Vo(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 da=5000,la=20;async function Va(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()+da;;){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,la))}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 Ga(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 Ka(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 Lo({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)=>ii(D,Pi(JSON.stringify({...C,type:"job",version:2,generation:D.generation,id:kn()})),z)}})}finally{if(l.terminals.get(e.session.jobId)===j)l.terminals.delete(e.session.jobId)}}async function Ja(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 Vo(a,e.payload,e.signal)}var ua=1e4,pa=20,ha=_t/2,ga=qt/2,ba=(e)=>e.output.reduce((a,l)=>a+l.text.length,0);async function Vo(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>ua))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 ii(N,Pi(JSON.stringify({...A,type:"job",version:2,generation:N.generation,id:kn()})),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<ha&&ba(w.job)<ga&&!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 ii(e,a,l){if(l.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((u,f)=>{let g=ra(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-xfak34av.js";import{at,kt,Oe,xt,Ke,Dr,Zt,Ne,X,te,Wi}from"./vm-hands-entry-lite-kbnxk71q.js";import{An,Cr}from"./vm-hands-entry-lite-33at6g06.js";import{pc,F,qt,_t,Wt,He,Vt,zo,yt,wn,nt,Ee,ce,it,Pi,Ri,Wo}from"./vm-hands-entry-lite-zp7chzcc.js";import{Ct,Je,ct,Le,Pt,xe,pe}from"./vm-hands-entry-lite-fxptf351.js";import{an,fi,dr,Re,U,H,T,Ro}from"./vm-hands-entry-lite-qjrgvdbj.js";import{Ft,gi,Io,lc,je,Do}from"./vm-hands-entry-lite-s93f3pbv.js";import{ue}from"./vm-hands-entry-lite-cc8hwgxc.js";import{wa}from"./vm-hands-entry-lite-sh4mqy93.js";import{v,Bt,cn,pr,oc,ht,ft}from"./vm-hands-entry-lite-b1vanmtv.js";import{b,m,y}from"./vm-hands-entry-lite-yg4dk99m.js";import{L}from"./vm-hands-entry-lite-fccn6s4j.js";import{$n}from"./vm-hands-entry-lite-sz7z1qby.js";import{s,Uc,zc,Ge,Wc}from"./vm-hands-entry-lite-12ck5swp.js";import{he,fa,ma,Xc,I,t,V,zr,o,_,d,n,h,P,$e,c,i}from"./vm-hands-entry-lite-zpvr7wc6.js";import{_a}from"./vm-hands-entry-lite-fn2805g8.js";import{Zc,Ye,Sa,B,It,Be,G}from"./vm-hands-entry-lite-pg7nnyc6.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{readFileSync as mo,realpathSync as _o,statSync as Hi}from"fs";import{homedir as Ni}from"os";import{dirname as Li,isAbsolute as Bi,join as dt,sep as ji}from"path";var Ci=()=>{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 ${ma(f.values[0])}`;return`Invalid option: expected one of ${fa(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":""}: ${fa(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 _n(){return{localeError:Ci()}}he(_n());var ti="--proxy",ri="--proxy-ca-file",Mi=262144;class K extends Error{}function hn(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 za(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??Ni(),l=e.statePath??gt();return[Li(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+ji)}function zi(e,a={}){if(!Bi(e))throw new K("The proxy CA file must be an absolute path.");let l,u,f;try{l=_o(e);let R=Hi(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>Mi)throw new K("The proxy CA file must be 256 KB or smaller.");let g=Fi(a).flatMap((R)=>{try{let w=_o(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=mo(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 qa(e,a={}){if(!e.proxyUrl)throw new K("A proxy URL is required.");let l=hn(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=mo(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 go,join as wo,relative as yo,resolve as Tt,sep as Oo}from"path";var At=t().min(1).refine(go,"absolute path required"),ho=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 hn(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",[ho,ho.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)&&!An(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 bo(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(Oo,yo(Tt(e),Tt(a))))}function se(e,a){let l=yo(Tt(e),Tt(a));return l===""||l!==".."&&!l.startsWith(`..${Oo}`)&&!go(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 ni(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 Vi=60000;function To(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())>Vi)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 cn(()=>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 cn(()=>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 gn}from"ws";var Ho=(e)=>("data"in e)?e.data.length:e.bytes,No=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 Wa(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 Lo(e){let{session:a,binding:l}=e;if(l.assertCurrent(),e.signal.aborted||Date.now()>=a.leaseExpiresAtMs)Fe("cancelled");let u=new gn(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>zo){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 Wo(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!==gn.OPEN||u.bufferedAmount+Buffer.byteLength(W)>No)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>No)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(wn),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-=Ho(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+=Ho(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===gn.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 qi,randomUUID as kn}from"crypto";import{spawnSync as Fo}from"child_process";import{closeSync as Bo,constants as bn,fstatSync as Yi,fsyncSync as Xi,lstatSync as lt,mkdirSync as Zi,mkdtempSync as Uo,openSync as jo,readFileSync as Qi,readdirSync as $o,realpathSync as kr,rmSync as yn,unlinkSync as ea}from"fs";import{createConnection as ra}from"net";import{dirname as ta,join as Ar,sep as vn}from"path";import{tmpdir as Ko}from"os";var er=new Map,vr=new Map;function mr(e,a){return qi("sha256").update(JSON.stringify([e,a])).digest("hex")}function Fr(e){try{Zi(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 na(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()||$o(e).length>0}function oa(e){if(process.platform==="win32")return Sa();let a=e.map((l)=>{try{return kr(l)}catch{return l}});for(let l of[()=>Sa(),()=>kr("/dev/shm"),()=>kr(Ko())]){let u;try{u=l()}catch{continue}if(!a.some((f)=>u===f||u.startsWith(f.endsWith(vn)?f:f+vn)))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)=>na(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=$o(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(oa(e.folders??[]),"reason-j-"));try{return Fr(g),{journalDirectory:f,scopeId:a,launchDirectory:g,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${kn()}`:Ar(g,"control.sock"),disposeSocket:()=>yn(g,{recursive:!0,force:!0})}}catch(k){throw yn(g,{recursive:!0,force:!0}),k}}var sa=60000,ia=5000;function aa(e){if(process.platform==="win32")return ca(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 ca(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 Go(e,a={}){let l=Ar(e.journalDirectory,"owner.lock"),u;try{u=jo(l,bn.O_RDONLY|bn.O_NOFOLLOW)}catch{return null}try{let f=Yi(u);if(!f.isFile()||f.nlink!==1||!G(f)||f.size>4096)return null;let g=null;try{g=JSON.parse(Qi(u,"utf8"))}catch{}let k;if(g===null){if((a.now??Date.now)()-f.mtimeMs<sa)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??aa)(D);if(C===null||C<=S+ia)return null;k={reason:"pid_reused",executorLaunchId:M}}}let R=lt(l);if(R.dev!==f.dev||R.ino!==f.ino)return null;ea(l);let w=jo(e.journalDirectory,bn.O_RDONLY);try{Xi(w)}finally{Bo(w)}return k}catch{return null}finally{Bo(u)}}function Jo(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=To({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 Vo(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 da=5000,la=20;async function Va(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()+da;;){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,la))}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 Ga(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 Ka(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 Lo({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)=>ii(D,Pi(JSON.stringify({...C,type:"job",version:2,generation:D.generation,id:kn()})),z)}})}finally{if(l.terminals.get(e.session.jobId)===j)l.terminals.delete(e.session.jobId)}}async function Ja(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 Vo(a,e.payload,e.signal)}var ua=1e4,pa=20,ha=_t/2,ga=qt/2,ba=(e)=>e.output.reduce((a,l)=>a+l.text.length,0);async function Vo(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>ua))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 ii(N,Pi(JSON.stringify({...A,type:"job",version:2,generation:N.generation,id:kn()})),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<ha&&ba(w.job)<ga&&!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 ii(e,a,l){if(l.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((u,f)=>{let g=ra(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=Ri(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 Mo(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:ta(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 Xa(e,a){let l=Ct.parse(e.request),u=Je.parse(e.authority);if(u.contributorRefresh&&l.kind==="read"&&u.readOnly)return a(Mo(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(Mo(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(Ko());if(w===g||w.startsWith(g+vn))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{yn(A,{recursive:!0,force:!0})}}var Xo=43200000;function $r(e){return Number.isSafeInteger(e)&&Math.abs(e)<=8640000000000000?e:null}function qo(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Yo(e,a){return Object.keys(e).length===a.length&&a.every((l)=>Object.hasOwn(e,l))}function Ya(e){if(!qo(e)||!Yo(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(!qo(l)||!Yo(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 Sn=h({kind:c(["workspace_source","mcp_control"]),target_revision:o().int().nonnegative(),root_grant_revision:o().int().positive()}),Zo=new RegExp(dr.tokenPattern),ya=h({token_url:zr().max(2048),request_token:t().min(1).max(8192).regex(Zo),aws_credentials_url:zr().max(2048).nullable()});function Qo(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(!Zo.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 es(e){return new TextEncoder().encode(e).byteLength}function va(e){return es(JSON.stringify(e)+`
|
|
4
4
|
`)}var oi=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:Sn.extend({target_generation:o().int().positive(),target_fence_id:V()}),expires_at:I.datetime({offset:!0}),variables:$e(t().max(128).regex(an),t().refine((e)=>!e.includes("\x00")&&es(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:ya.optional()}).refine((e)=>e.github_auth!=="local_gh"||e.git===null,"conflicting git authority").refine((e)=>va(e)<=Re.snapshotBytes,"snapshot too large");import{spawn as ka}from"child_process";import{basename as Ea,isAbsolute as Ef}from"path";var Ra=0,rs=120000,ts=15000,Oa=65536;function En(e=process.execPath,a=process.argv[1]){let l=Ea(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}=En(e.executablePath,e.sourceEntrypoint),u=e.spawnProcess??ka,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<rs-ts)return;if(g){let D=g;g=null,w(D)}let N;try{N=u(a,[...l,"__device","__hands-worker","--handoff-fd",String(Ra)],{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>=rs-ts||Buffer.byteLength(Y,"utf8")>Oa)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 Da,constants as Ca,statSync as Ha}from"fs";import{homedir as Na,tmpdir as La,userInfo as Ba}from"os";import{delimiter as ja,win32 as Ma}from"path";var xa=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 Pa=["BUN_CONFIG_","BUN_INSPECT","DYLD_","NODE_DEBUG"],Ia=new Set(["BUN_INSTALL"]);var Aa=/^--(?:max-old-space-size|max-semi-space-size|stack-size)=\d{1,9}$/;function Ta(e){return(e??"").split(/\s+/).filter(Boolean).every((a)=>Aa.test(a.replaceAll("_","-")))}function pt(e){return Object.keys(e).filter((a)=>xa.has(a)&&!(a==="NODE_OPTIONS"&&Ta(e[a]))||Pa.some((l)=>a.startsWith(l))||a.startsWith("BUN_")&&!Ia.has(a)).sort()}var Fa=new Set(["HOME","PATH","PWD","OLDPWD","SHLVL","_","TMPDIR","TMP","TEMP","SHELL","BASH_ENV","ENV","ZDOTDIR","PROMPT_COMMAND","IFS","CDPATH","GLOBIGNORE","SHELLOPTS","BASHOPTS","NODE_PATH"]),Ua=/^(?: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 ai(e=process.env){let a=(f)=>{if(!(process.platform==="win32"?Ma.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)&&!Fa.has(g)&&!Ua.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)||Na()),path:((f)=>process.platform==="win32"?Do(f):f)(gi(e.PATH??"").join(ja)||Ft),temporaryDirectory:a(e.TMPDIR||e.TMP||e.TEMP||La()),variables:u}}function ci(e=process.env,a=()=>Ba().shell){if(process.platform==="win32")return Ye();let l=(f)=>{if(!f||!/^\/[A-Za-z0-9._/-]*\/(?:bash|zsh)$/.test(f))return!1;try{return Da(f,Ca.X_OK),Ha(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 So(e){let a=e instanceof Error&&"code"in e?e.code:null;return a==="EPERM"||a==="EACCES"}function Eo(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 ns(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(So(g))throw Eo(e);if(g instanceof r)throw g}finally{clearTimeout(u)}}import{chmodSync as Kc,closeSync as Gc,constants as Nn,fstatSync as Jc,lstatSync as Es,openSync as Vc,readSync as qc,realpathSync as Ln,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 Is}from"os";import{basename as nd,extname as od,isAbsolute as Rs,relative as Bn,resolve as Vr,sep as jn}from"path";var os=String.raw`
|
|
5
5
|
async (roots) => {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{mkdirSync as R,readdirSync as A,readFileSync as k,realpathSync as x}from"fs";import{userInfo as E}from"os";var zn="--vm-hands-op-runner-kind=person",qn="--vm-hands-op-runner-kind=surface",Wr="--vm-hands-surface-uid=",Vr="--vm-hands-surface-dir=",C="/sys/fs/cgroup/reason-person/desktop",Gr=new Set(["automation.call.v1","display.stream.v1","preview.serve.v1"]);function D(t){let a=new Set([t]),l=[];try{l=A("/proc")}catch{}for(let n of l){if(!/^\d+$/.test(n))continue;try{let o=k(`/proc/${n}/stat`,"utf8");if(Number(o.slice(o.lastIndexOf(")")+2).split(" ")[3])===t)a.add(Number(n))}catch{}}for(let n of a)try{process.kill(n,"SIGKILL")}catch{}}var H=(t)=>{let a=globalThis.Bun;if(!a)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");let l=a.spawn({cmd:[t.shell,...t.args],cwd:t.cwd,env:{...t.environment,TERM:"xterm-256color"},terminal:{cols:t.cols,rows:t.rows,data:(c,d)=>t.onData(d)}}),n=l.terminal,o=()=>{D(l.pid);try{n?.close()}catch{}};if(!n)throw o(),new r("pty_unavailable","Reason could not allocate a pseudo-terminal.");return{write:(c)=>n.write(c),resize:(c,d)=>n.resize(c,d),kill:o,exited:l.exited.then((c)=>typeof c==="number"?c:null,()=>null)}};function O(){let t=(()=>{try{return E().username}catch{return}})();return{PATH:process.env.PATH,HOME:process.env.HOME,SHELL:process.env.SHELL,LANG:"C.UTF-8",...t?{USER:t,LOGNAME:t}:{}}}async function L(t){let[{localAutomationAvailable:a},{localDisplayReady:l},{localDisplayVideoAvailable:n},{probeWorkerPreview:o},m]=await Promise.all([import("./local-automation-
|
|
3
|
-
`).find((o)=>o.startsWith("0::"))?.slice(3)??""}catch{return null}if(!/^\/reason-person\/vm-hands\/[A-Za-z0-9._-]+$/.test(a))return null;if(!t)return null;let l=[t.xvnc,t.xvfb,t.openbox,t.x11vnc,t.pulseaudio,t.browser,"/usr/bin/dbus-daemon","/bin/dbus-daemon"].flatMap((o)=>{try{return o?[x(o)]:[]}catch{return[]}}),n={join:`/sys/fs/cgroup${a}/desktop`,keep:C,programs:[...new Set(l)]};for(let o of[n.join,n.keep])try{R(o,{mode:493})}catch(m){if(m.code!=="EEXIST")return null}return n}async function hl(){let[{executeLocalOperation:t,spawnCaptured:a},{runLocalPtySession:l},{configureDesktopAccount:n,desktopAccount:o},{configureWorkerSandbox:m},{configureDesktopPlacement:c},{readDesktopComponents:d}]=await Promise.all([import("./local-capabilities-
|
|
2
|
+
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{mkdirSync as R,readdirSync as A,readFileSync as k,realpathSync as x}from"fs";import{userInfo as E}from"os";var zn="--vm-hands-op-runner-kind=person",qn="--vm-hands-op-runner-kind=surface",Wr="--vm-hands-surface-uid=",Vr="--vm-hands-surface-dir=",C="/sys/fs/cgroup/reason-person/desktop",Gr=new Set(["automation.call.v1","display.stream.v1","preview.serve.v1"]);function D(t){let a=new Set([t]),l=[];try{l=A("/proc")}catch{}for(let n of l){if(!/^\d+$/.test(n))continue;try{let o=k(`/proc/${n}/stat`,"utf8");if(Number(o.slice(o.lastIndexOf(")")+2).split(" ")[3])===t)a.add(Number(n))}catch{}}for(let n of a)try{process.kill(n,"SIGKILL")}catch{}}var H=(t)=>{let a=globalThis.Bun;if(!a)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");let l=a.spawn({cmd:[t.shell,...t.args],cwd:t.cwd,env:{...t.environment,TERM:"xterm-256color"},terminal:{cols:t.cols,rows:t.rows,data:(c,d)=>t.onData(d)}}),n=l.terminal,o=()=>{D(l.pid);try{n?.close()}catch{}};if(!n)throw o(),new r("pty_unavailable","Reason could not allocate a pseudo-terminal.");return{write:(c)=>n.write(c),resize:(c,d)=>n.resize(c,d),kill:o,exited:l.exited.then((c)=>typeof c==="number"?c:null,()=>null)}};function O(){let t=(()=>{try{return E().username}catch{return}})();return{PATH:process.env.PATH,HOME:process.env.HOME,SHELL:process.env.SHELL,LANG:"C.UTF-8",...t?{USER:t,LOGNAME:t}:{}}}async function L(t){let[{localAutomationAvailable:a},{localDisplayReady:l},{localDisplayVideoAvailable:n},{probeWorkerPreview:o},m]=await Promise.all([import("./local-automation-7pjd5nc1.js"),import("./local-display-session-0mkswxgk.js"),import("./local-display-video-c3fk87c5.js"),import("./worker-preview-readiness-h96yr4wf.js"),import("fs")]),c=AbortSignal.timeout(15000),d=null;try{m.mkdirSync(t,{recursive:!0,mode:448}),d=m.mkdtempSync(`${t}/probe-`);let[w,u,v]=await Promise.all([Promise.resolve().then(()=>a()).catch(()=>!1),l().catch(()=>!1),o(d,c).catch(()=>!1)]);return{t:"readiness",display_video:u&&await n().catch(()=>!1),lanes:{"automation.call.v1":w,"display.stream.v1":u,"preview.serve.v1":v,"tunnel.open":v,"tunnel.close":v}}}finally{if(d)m.rmSync(d,{recursive:!0,force:!0})}}function N(t){let a="";try{a=k("/proc/self/cgroup","utf8").split(`
|
|
3
|
+
`).find((o)=>o.startsWith("0::"))?.slice(3)??""}catch{return null}if(!/^\/reason-person\/vm-hands\/[A-Za-z0-9._-]+$/.test(a))return null;if(!t)return null;let l=[t.xvnc,t.xvfb,t.openbox,t.x11vnc,t.pulseaudio,t.browser,"/usr/bin/dbus-daemon","/bin/dbus-daemon"].flatMap((o)=>{try{return o?[x(o)]:[]}catch{return[]}}),n={join:`/sys/fs/cgroup${a}/desktop`,keep:C,programs:[...new Set(l)]};for(let o of[n.join,n.keep])try{R(o,{mode:493})}catch(m){if(m.code!=="EEXIST")return null}return n}async function hl(){let[{executeLocalOperation:t,spawnCaptured:a},{runLocalPtySession:l},{configureDesktopAccount:n,desktopAccount:o},{configureWorkerSandbox:m},{configureDesktopPlacement:c},{readDesktopComponents:d}]=await Promise.all([import("./local-capabilities-ha0ey4zh.js"),import("./local-pty-session-tqn2xmph.js"),import("./desktop-account-xma0330a.js"),import("./worker-sandbox-6kkhvryn.js"),import("./desktop-delegate-tch2qzx0.js"),import("./desktop-components-099xyxmz.js")]);m();let w=process.argv.includes(zn),u=process.argv.includes(qn),v=(i,e,p)=>a(i,e[0]==="-lic"?["-lc",...e.slice(1)]:e,p),y=(process.geteuid?.()??0)!==0;if(u){y=!1;let i=process.argv.find((e)=>e.startsWith(Wr))?.slice(Wr.length);if((process.geteuid?.()??-1)===0&&i)try{y=n({value:i})!==null&&o()!==null}catch{y=!1}}let S=new Map,_=new Map,f=(i)=>{try{process.send?.(i)}catch{}};if(u&&y){let i=o()?.home,e=i?N(d({home:i})):null;c(e&&{...e,log:(p,g)=>f({t:"log",event:p,fields:g})})}if(process.on("message",(i)=>{let e=i;if(e?.t==="cancel"){S.get(e.id)?.abort();return}if(e?.t==="control"){let s=_.get(e.id);if(u&&s&&e.control&&typeof e.control.kind==="string")import("./local-managed-process-ahr2jync.js").then(({controlManagedDeviceProcess:h})=>h(s,{kind:e.control.kind,payload:e.control.payload??{}})).catch(()=>!1);return}if(e?.t==="retire"){if(u&&typeof e.operation_id==="string"&&typeof e.status==="string")import("./local-managed-process-ahr2jync.js").then(({retireManagedDeviceProcess:s})=>s(e.operation_id,e.status)).catch(()=>!1);return}if(e?.t!=="op")return;if(!y){f({t:"done",id:e.id,completion:{status:"failed",error_code:"vm_hands_payload_account_unavailable"}});return}let p=e.claim.capability;if(p==="pty.start"&&!w){f({t:"done",id:e.id,completion:{status:"failed",error_code:"capability_not_granted"}});return}if(Gr.has(p)!==u){f({t:"done",id:e.id,completion:{status:"failed",error_code:"capability_not_granted"}});return}let g=new AbortController;S.set(e.id,g),_.set(e.id,e.claim);let b=p==="pty.start"?{runPtySession:(s)=>l(s,{spawnPty:H,environment:O(),loadProxy:()=>null})}:{worker:e.worker,...p==="exec.full"?{spawnFullControl:v}:{}};t(e.state,e.claim,{...b,signal:g.signal,emit:(s)=>{let{deliverySignal:h,...P}=s;f({t:"event",id:e.id,event:P})}}).then((s)=>f({t:"done",id:e.id,completion:s}),(s)=>f({t:"done",id:e.id,completion:{status:"failed",error_code:s&&typeof s==="object"&&"code"in s&&typeof s.code==="string"?s.code:"vm_hands_op_failed"}})).finally(()=>{S.delete(e.id),_.delete(e.id)})}),process.on("disconnect",()=>process.exit(0)),u){let i=process.argv.find((p)=>p.startsWith(Vr))?.slice(Vr.length),e={t:"readiness",display_video:!1,lanes:{}};f(y&&i?await L(i).catch(()=>e):e)}await new Promise(()=>{})}
|
|
4
4
|
export{zn,qn,Wr,Vr,Gr,hl};
|