@reason-machines/cli-linux-arm64 0.2.419 → 0.2.422
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/{connect-cli-k7px2rdj.js → connect-cli-qtbe4v66.js} +1 -1
- package/bin/vm-hands/{local-automation-y36wa5fz.js → local-automation-0gmnztwx.js} +1 -1
- package/bin/vm-hands/{local-capabilities-t6fwch4h.js → local-capabilities-vfteeg61.js} +1 -1
- package/bin/vm-hands/{local-display-session-5cgt72jx.js → local-display-session-bnc6whgt.js} +1 -1
- package/bin/vm-hands/local-display-video-mtd0gnyg.js +2 -0
- package/bin/vm-hands/{local-managed-process-bnqnzd8d.js → local-managed-process-khhmd6pe.js} +1 -1
- package/bin/vm-hands/{managed-runtime-wbsp37xw.js → managed-runtime-hv0hwf1j.js} +1 -1
- package/bin/vm-hands/{permissions-vys6xvz7.js → permissions-rr3e1yd5.js} +1 -1
- package/bin/vm-hands/{serve-service-rcvza2vj.js → serve-service-pb0ch11d.js} +1 -1
- package/bin/vm-hands/{status-5q2w623r.js → status-4pmpra54.js} +1 -1
- package/bin/vm-hands/version-8z9rdrb0.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-1pabvq5q.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-ehthgxsx.js → vm-hands-entry-lite-1qpwpdcc.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-pcvgqrse.js → vm-hands-entry-lite-2e15739v.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-706c7f7x.js → vm-hands-entry-lite-3tx0tkeq.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-03gh7msy.js → vm-hands-entry-lite-6gv0d400.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-8h2p4crd.js → vm-hands-entry-lite-7m9dr2mg.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-tfra9vjt.js → vm-hands-entry-lite-94bm9vgk.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-34z9890s.js → vm-hands-entry-lite-aapdds5x.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-2nvhegyc.js → vm-hands-entry-lite-bknthqy2.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-dht2p1vj.js +128 -0
- package/bin/vm-hands/{vm-hands-entry-lite-09sq8090.js → vm-hands-entry-lite-dzv12jpj.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-p9v963ks.js → vm-hands-entry-lite-jjwcsywg.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-w8ykfw5h.js → vm-hands-entry-lite-kz0b5h2f.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-wmynasc4.js → vm-hands-entry-lite-xvmeb9e8.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
- package/bin/vm-hands/vm-hands-executor-z222kmvg.js +11 -0
- package/bin/vm-hands/{vm-hands-op-runner-7tcv4e0v.js → vm-hands-op-runner-34d38g9f.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-mc2e6wsv.js → vm-hands-runtime-h0trw0xr.js} +3 -3
- package/package.json +1 -1
- package/bin/vm-hands/local-display-video-3xk3kg9p.js +0 -2
- package/bin/vm-hands/version-qgew2890.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-ewxc9m4d.js +0 -128
- package/bin/vm-hands/vm-hands-entry-lite-f1by8av5.js +0 -2
- package/bin/vm-hands/vm-hands-executor-6357p4cd.js +0 -11
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{zt,j}from"./vm-hands-entry-lite-pf5qtbj5.js";import{ue,Ce,Z,Ae,de,rr,Qe,X,O,H,tn}from"./vm-hands-entry-lite-3krzmhkk.js";import{_o,Vn}from"./vm-hands-entry-lite-aj139v8j.js";import{lo,P,Ke,ve,Je,ne,Ze,Bn,Se,Gt,ae,U,N,ce,Ur,Hr,jn}from"./vm-hands-entry-lite-tdgtpx8e.js";import{Pe,oe,pe,Y,Oe,q,Q}from"./vm-hands-entry-lite-4vks5phw.js";import{It,Sr,st,V,D,R,b}from"./vm-hands-entry-lite-beyyy1gz.js";import{xr,kr,bn,io,ze,vn}from"./vm-hands-entry-lite-s5qkb1fk.js";import{K}from"./vm-hands-entry-lite-hk6trmwa.js";import{Ii}from"./vm-hands-entry-lite-fbhqfzbq.js";import{p,He,Dt,at,Yi,_e,we}from"./vm-hands-entry-lite-s4bharcb.js";import{v,h,oo}from"./vm-hands-entry-lite-wx4ax7wg.js";import{E}from"./vm-hands-entry-lite-dk79tnax.js";import{er}from"./vm-hands-entry-lite-706c7f7x.js";import{a,ie,Do}from"./vm-hands-entry-lite-jev771b3.js";import{L,Pi,Ti,Bo,y,t,k,xt,o,d,u,i,c,_,ee,s,n}from"./vm-hands-entry-lite-avc65bd7.js";import{Oi}from"./vm-hands-entry-lite-hbs3tpdg.js";import{jo,se,Uo,C,Ne,$e,A}from"./vm-hands-entry-lite-6c67a3jc.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";var li=()=>{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 l(w){return e[w]??null}let f={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"},g={nan:"NaN"};return(w)=>{switch(w.code){case"invalid_type":{let S=g[w.expected]??w.expected,I=Bo(w.input),W=g[I]??I;return`Invalid input: expected ${S}, received ${W}`}case"invalid_value":if(w.values.length===1)return`Invalid input: expected ${Ti(w.values[0])}`;return`Invalid option: expected one of ${Pi(w.values,"|")}`;case"too_big":{let S=w.inclusive?"<=":"<",I=l(w.origin);if(I)return`Too big: expected ${w.origin??"value"} to have ${S}${w.maximum.toString()} ${I.unit??"elements"}`;return`Too big: expected ${w.origin??"value"} to be ${S}${w.maximum.toString()}`}case"too_small":{let S=w.inclusive?">=":">",I=l(w.origin);if(I)return`Too small: expected ${w.origin} to have ${S}${w.minimum.toString()} ${I.unit}`;return`Too small: expected ${w.origin} to be ${S}${w.minimum.toString()}`}case"invalid_format":{let S=w;if(S.format==="starts_with")return`Invalid string: must start with "${S.prefix}"`;if(S.format==="ends_with")return`Invalid string: must end with "${S.suffix}"`;if(S.format==="includes")return`Invalid string: must include "${S.includes}"`;if(S.format==="regex")return`Invalid string: must match pattern ${S.pattern}`;return`Invalid ${f[S.format]??w.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${w.divisor}`;case"unrecognized_keys":return`Unrecognized key${w.keys.length>1?"s":""}: ${Pi(w.keys,", ")}`;case"invalid_key":return`Invalid key in ${w.origin}`;case"invalid_union":if(w.options&&Array.isArray(w.options)&&w.options.length>0)return`Invalid discriminator value. Expected ${w.options.map((I)=>`'${I}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${w.origin}`;default:return"Invalid input"}}};function En(){return{localeError:li()}}L(En());class _t extends Error{}function Ro(e){let l;try{l=new URL(e)}catch{throw new _t("The proxy must be a URL like https://proxy.example.com:3128.")}if(l.protocol!=="https:"&&l.protocol!=="http:")throw new _t("The proxy URL must use the https or http scheme.");if(!l.hostname)throw new _t("The proxy URL must name a host.");if(l.port!==""&&Number(l.port)<1)throw new _t("The proxy URL must use a port between 1 and 65535.");if(l.pathname!==""&&l.pathname!=="/"||l.search||l.hash)throw new _t("The proxy URL must not carry a path, query, or fragment.");return l.toString()}import{createHash as ui}from"crypto";import{isAbsolute as Oo,join as xo,relative as Po,resolve as Yt,sep as Io}from"path";var qt=t().min(1).refine(Oo,"absolute path required"),On=c({version:n(1),apiOrigin:xt(),channel:s(["staging","production"]),stateDirectory:qt,workspaceRoot:qt,lifetime:s(["persistent","ephemeral"]),executionMode:s(["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:c({version:n(zt),url:t().refine((e)=>{try{return Ro(e)===e}catch{return!1}},"invalid proxy URL"),caFile:qt.optional()}).optional(),userChrome:d().optional(),cloudSessions:n(!0).optional(),localLogins:d().optional(),folders:u(qt).min(1).max(31).optional()}),fi=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,B=_("channel",[On,On.extend({channel:n("pr"),apiOrigin:t(),prEnvironment:t()}),On.extend({channel:n("local-qa"),apiOrigin:t()})]).superRefine((e,l)=>{if(e.channel==="local-qa"){if(!fi.test(e.apiOrigin))l.addIssue({code:"custom",message:"local QA worker requires an exact HTTPS trycloudflare.com quick-tunnel origin"})}else if(e.channel==="pr"){let g=e.prEnvironment,w=/^https:\/\/([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)\.up\.railway\.app$/.exec(e.apiOrigin),S=w?.[1]?.match(/(?:^|-)pr-[0-9]+(?=-|$)/g)?.map((I)=>I.replace(/^-/,""));if(!g||/^pr-[1-9][0-9]*$/.exec(g)?.[0]!==g||w?.[0]!==e.apiOrigin||S?.length!==1||S[0]!==g)l.addIssue({code:"custom",message:"PR worker requires explicit prEnvironment and an exact same-PR HTTPS Railway origin"})}else{let g=new URL(e.apiOrigin);if(g.origin!==e.apiOrigin||g.username||g.password||g.protocol!=="https:"&&!(g.protocol==="http:"&&Vn(g.origin))||!Vn(g.origin)&&!_o(e.channel,g.origin))l.addIssue({code:"custom",message:"API origin must match channel (or loopback)"})}if(!je(e.workspaceRoot,e.stateDirectory))l.addIssue({code:"custom",message:"state and workspace must be disjoint"});let f=e.folders??[];if(new Set([e.workspaceRoot,...f]).size!==f.length+1||f.some((g)=>!je(g,e.stateDirectory)))l.addIssue({code:"custom",message:"folders must be distinct and disjoint from state"})});function m(e){return xo(e.stateDirectory,`headless-${e.channel==="pr"?e.prEnvironment:e.channel}`)}function je(e,l){if($r(l,e))return!1;return!$r(e,l)||E(xo(Io,Po(Yt(e),Yt(l))))}function $r(e,l){let f=Po(Yt(e),Yt(l));return f===""||f!==".."&&!f.startsWith(`..${Io}`)&&!Oo(f)}function te(e){let{proxy:l,userChrome:f,cloudSessions:g,localLogins:w,folders:S,...I}=e;return ui("sha256").update(JSON.stringify(I)).digest("hex")}var pi=4,_i=[2375,2376,9222,9229];function dr(e){let l=new Set(_i);for(let f of e){let g=new URL(f);l.add(Number(g.port||(["https:","wss:"].includes(g.protocol)?443:80)))}return l}function Vr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var mi=60000;function Ao(e){let l=new AbortController,f=new Map,g=(x)=>JSON.stringify([x.jobId,x.port]);function w(x){let M=e.authority.owner;if(l.signal.aborted||!e.isCurrent()||e.expiresAtMs<=Date.now()||x.organization_id!==M.organization_id||x.user_id!==M.user_id||x.device_id!==M.device_id)Vr()}function S(x){let M;try{M=e.environment.current()}catch{return null}return M.binding.target_generation===x.generation&&M.binding.target_fence_id===x.fenceId&&M.run_id===e.runId&&M.device_id===e.authority.owner.device_id&&M.root_id===e.authority.rootId?M:null}async function I(x,M,G){let F=await W(x,M,G);if(F!=="moved")return F;let T=await W(x,M,G);return T==="moved"?null:T}async function W(x,M,G){try{w(e.authority.owner);let F=e.identity();if(!F||G.aborted||x.expiresAtMs<=Date.now()||x.expiresAtMs>e.expiresAtMs)return null;let T=M.opened,re=T!==void 0&&F.generation>T.generation,J=S(F);if(re){if(J){if(J.revision<=T.revision||x.expiresAtMs>Date.parse(J.expires_at)||J.binding.target_revision!==T.attachmentRevision||J.binding.root_grant_revision!==T.grantRevision)return null;M.recoveringSinceMs=void 0}else if(Date.now()-(M.recoveringSinceMs??=Date.now())>mi)return null}else if(!J||x.expiresAtMs>Date.parse(J.expires_at)||T&&(F.generation!==T.generation||F.fenceId!==T.fenceId))return null;let z=await e.inspect(x.jobId,G),fe=e.identity(),ke=fe&&S(fe);w(e.authority.owner);let be=J&&{generation:F.generation,fenceId:F.fenceId,snapshotId:J.snapshot_id,revision:J.revision,attachmentRevision:J.binding.target_revision,grantRevision:J.binding.root_grant_revision},Re=re?T:be;if(G.aborted||!fe)return null;if(fe.generation!==F.generation||fe.fenceId!==F.fenceId||ke?.snapshot_id!==J?.snapshot_id||ke?.revision!==J?.revision)return"moved";let Fe=z.ok&&z.job.environmentSnapshotId!==void 0&&z.job.environmentRevision!==void 0?{snapshotId:z.job.environmentSnapshotId,revision:z.job.environmentRevision}:null;if(!z.ok||z.generation!==F.generation||!Re||!Fe)return null;if((Fe.snapshotId!==Re.snapshotId||Fe.revision!==Re.revision)&&(re||!e.environment.carried(Fe.snapshotId,Fe.revision)))return null;if(!T&&F.generation===x.generation&&F.fenceId===x.fenceId)M.opened={...Re,...Fe};return{executorLaunchId:e.executorLaunchId,job:z.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:z.job.jobId,port:x.port,expiresAtMs:x.expiresAtMs}}}catch{return null}}return{async open(x,M,G){w(M);let{binding:F,deviceRelayUrl:T}=at(x);if(G.aborted||F.expiresAtMs<=Date.now()||F.expiresAtMs>Date.now()+p.lifetimeMs||new URL(T).origin!==e.authority.relayOrigin)Vr();let re=g(F),J=f.get(re);if(J){if(!He(J.binding,F)||J.relay!==T)Vr();if(await J.opened,!await Dt(()=>J.port.check())||G.aborted||J.abort.signal.aborted)Vr();return{opened:!0,binding:F}}if(f.size>=pi)Vr();let z=new AbortController,fe={},ke=we({binding:F,deniedPorts:e.authority.deniedPorts,readCurrentJob:()=>I(F,fe,z.signal)}),be=()=>z.abort();if(G.addEventListener("abort",be,{once:!0}),l.signal.addEventListener("abort",be,{once:!0}),G.aborted||l.signal.aborted)be();let Re=_e({binding:F,deviceRelayUrl:T,port:ke,signal:z.signal}),Fe={binding:F,relay:T,abort:z,port:ke,opened:Re};f.set(re,Fe);let Ye=()=>{if(G.removeEventListener("abort",be),l.signal.removeEventListener("abort",be),f.get(re)===Fe)f.delete(re)};try{if((await Re).closed.then(Ye),G.removeEventListener("abort",be),w(M),z.signal.aborted||!await Dt(()=>ke.check()))Vr();return{opened:!0,binding:F}}catch{z.abort(),Ye(),Vr()}},async close(x,M){w(M);let{binding:G}=Yi(x),F=f.get(g(G));if(!F||!He(F.binding,G))Vr();return F.abort.abort(),await F.opened.then((T)=>T.closed,()=>{return}),{closed:!0,binding:G}},dispose(){l.abort();for(let x of f.values())x.abort.abort();f.clear()}}}import{WebSocket as xn}from"ws";var To=(e)=>("data"in e)?e.data.length:e.bytes,Co=2*Ze;function cr(e){throw new r(e,"The bound Hands terminal is unavailable or its outcome is unconfirmed.")}var mt=(e)=>!["starting","running"].includes(e.state);function Hi(e,l,f=Date.now()){let g=["relay_url","session_id","expires_at","cols","rows","pty","workspace"];if(Object.keys(e).length!==g.length||Object.keys(e).some((M)=>!g.includes(M))||!ae(l)||!ae(e.session_id)||typeof e.expires_at!=="string"||typeof e.relay_url!=="string"||e.relay_url.length>4096||![e.cols,e.rows].every((M)=>Number.isSafeInteger(M)&&Number(M)>=1&&Number(M)<=Se))cr("invalid_pty_request");let w=e.pty;if(!w||typeof w!=="object"||Array.isArray(w))cr("invalid_pty_request");let S=w;if(Object.keys(S).length!==2||S.version!==1||!ce(S.jobId))cr("invalid_pty_request");let I;try{I=new URL(e.relay_url)}catch{return cr("invalid_pty_request")}if(!["ws:","wss:"].includes(I.protocol)||I.username||I.password||I.hash||I.protocol==="ws:"&&!["127.0.0.1","[::1]","localhost"].includes(I.hostname))cr("invalid_pty_request");let W=Date.parse(e.expires_at);if(!Number.isSafeInteger(W)||W<=f)cr("invalid_pty_request");return{workspace:H(e.workspace)??cr("invalid_pty_request"),session:{jobId:S.jobId,sessionId:e.session_id,operationId:l,relayUrl:I.href,cols:Number(e.cols),rows:Number(e.rows),leaseExpiresAtMs:Math.min(W,f+43200000)}}}async function Ho(e){let{session:l,binding:f}=e;if(f.assertCurrent(),e.signal.aborted||Date.now()>=l.leaseExpiresAtMs)cr("cancelled");let g=new xn(l.relayUrl,{followRedirects:!1,perMessageDeflate:!1,maxPayload:ne}),w=new AbortController,S=()=>{},I=()=>{w.abort(),S()};e.signal.addEventListener("abort",I,{once:!0});let W=setTimeout(I,Math.max(1,l.leaseExpiresAtMs-Date.now())),x=[],M=0,G=0,F=0,T=!1,re=!1,J=!1,z,fe,ke,be=(le)=>{ke=new r(le,"Bound terminal input was refused."),I()};g.on("error",()=>be("pty_relay_unavailable")),g.on("close",I),g.on("message",(le,he)=>{if(w.signal.aborted)return;if(!re){be("pty_not_ready");return}let xe=Array.isArray(le)?Buffer.concat(le):le instanceof ArrayBuffer?Buffer.from(le):le;if(xe.length===0)return;let Ge=x.at(-1),Le=he&&Ge!==void 0&&"data"in Ge&&Ge.data.length+xe.length<=ne;if(xe.length>ne||M+xe.length>Bn){be("pty_input_backpressure");return}if(Le)Ge.data=Buffer.concat([Ge.data,xe]);else if(he)x.push({data:Buffer.from(xe)});else try{let Be=JSON.parse(xe.toString("utf8"));if(Be&&Be.t==="close"&&Object.keys(Be).length===1){J=!0,I();return}if(!Be||Be.t!=="resize"||Object.keys(Be).length!==3||![Be.cols,Be.rows].every((Ee)=>Number.isSafeInteger(Ee)&&Ee>=1&&Ee<=Se))throw Error("invalid_control");x.push({cols:Be.cols,rows:Be.rows,bytes:xe.length})}catch{be("invalid_pty_control");return}M+=xe.length,S()});function Re(le){return jn(JSON.stringify({...f.scope,version:1,sessionId:l.sessionId,operationId:l.operationId,job:{...le,output:[],pty:le.pty?{...le.pty,output:[]}:void 0}}))}function Fe(le){if(!le.ok)cr(le.error);let he=le.job;if(le.generation!==f.scope.generation||he.jobId!==l.jobId||!he.pty||he.leaseExpiresAtMs>l.leaseExpiresAtMs||he.process&&he.process.executorLaunchId!==f.scope.executorLaunchId||he.process&&fe&&(he.process.pid!==fe.pid||he.process.processGroupId!==fe.processGroupId)||he.state!=="starting"&&(he.environmentRevision!==f.environment.revision||he.environmentSnapshotId!==f.environment.snapshotId))cr("pty_binding_changed");if(Re(he),he.process)fe??={...he.process};return he}async function Ye(le){f.assertCurrent();let he=await f.request(le,w.signal);if(f.assertCurrent(),w.signal.aborted)cr("cancelled");let xe=Fe(he);if(xe.inputSequence!==G)cr("job_input_sequence");if(!mt(xe)&&xe.leaseExpiresAtMs<=Date.now())cr("pty_binding_changed");return xe}function ye(le){if(f.assertCurrent(),w.signal.aborted||g.readyState!==xn.OPEN||g.bufferedAmount+Buffer.byteLength(le)>Co)cr("pty_output_backpressure");g.send(le)}function We(le){if(le.firstCursor>F+1)F=le.firstCursor-1;for(let he of le.pty.output){if(he.cursor<=F)continue;if(he.cursor!==F+1)cr("pty_output_gap");let xe=Buffer.from(he.dataBase64,"base64");if(g.bufferedAmount+xe.length>Co)return!1;ye(xe),F=he.cursor}if(F!==le.nextCursor)cr("pty_output_gap");return!0}async function qe(le,he){let xe;try{await Promise.race([e.emit(le,he),new Promise((Ge,Le)=>{xe=setTimeout(()=>Le(new r("pty_event_unavailable","Terminal metadata delivery timed out.")),2000)})])}finally{clearTimeout(xe)}}async function Te(){let le=AbortSignal.timeout(Gt),he=f.request({jobId:l.jobId,action:"cancel",input:{}},le),xe,Ge=new Promise((Le,Be)=>{if(xe=()=>Be(new r("pty_cleanup_unconfirmed","Terminal cleanup acknowledgement was not observed within authority.")),le.addEventListener("abort",xe,{once:!0}),le.aborted)xe()});try{let Le=await Promise.race([he,Ge]);if(le.aborted)cr("pty_cleanup_unconfirmed");return Fe(Le)}finally{le.removeEventListener("abort",xe)}}try{await new Promise((Le,Be)=>{let Ee=setTimeout(()=>{I(),Be(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),Me=()=>{clearTimeout(Ee),Be(new r("cancelled","Terminal pairing was cancelled."))};if(w.signal.addEventListener("abort",Me,{once:!0}),g.once("open",()=>{clearTimeout(Ee),w.signal.removeEventListener("abort",Me),Le()}),w.signal.aborted)Me()}),f.assertCurrent(),T=!0,z=await Ye({jobId:l.jobId,action:"start",input:{mode:"pty",cols:l.cols,rows:l.rows,leaseExpiresAtMs:l.leaseExpiresAtMs}});let le=Date.now()+5000;while(z.state==="starting"){if(Date.now()>=le)cr("pty_not_ready");await new Promise((Le)=>setTimeout(Le,25)),z=await Ye({jobId:l.jobId,action:"inspect",input:{after:F}})}if(z.state!=="running"||z.inputSequence!==0||z.leaseExpiresAtMs<=Date.now())cr("pty_not_ready");await qe("pty.ready",Re(z)),re=!0,ye(JSON.stringify({t:"open",cols:z.pty.cols,rows:z.pty.rows,receipt:Re(z)}));let he=!1,xe=0,Ge=!1;while(!w.signal.aborted){let Le=z.firstCursor>F+1,Be=We(z);if(mt(z)){if(Be)break}else if(Le)he=!0;else if(he&&Be&&Date.now()>=xe){he=!1,xe=Date.now()+1000;let{cols:Me,rows:or}=z.pty;for(let sr of[{cols:Me,rows:or>1?or-1:2},{cols:Me,rows:or}]){if(mt(z))break;let Ir=++G;if(z=await Ye({jobId:l.jobId,action:"resize",input:{sequence:Ir,...sr}}),z.inputSequence!==Ir)cr("job_input_sequence")}continue}let Ee=mt(z)||Ge?void 0:x.shift();if(Ee){M-=To(Ee);let Me=++G;try{z=await Ye("data"in Ee?{jobId:l.jobId,action:"input",input:{sequence:Me,dataBase64:Ee.data.toString("base64")}}:{jobId:l.jobId,action:"resize",input:{sequence:Me,cols:Ee.cols,rows:Ee.rows}})}catch(or){if(!(or instanceof r)||or.code!=="job_input_backpressure")throw or;G-=1,x.unshift(Ee),M+=To(Ee),Ge=!0;continue}if(z.inputSequence!==Me)cr("job_input_sequence")}else if(await new Promise((Me)=>{let or=setTimeout(Me,Ge||!Be?10:50);if(S=()=>{clearTimeout(or),Me()},w.signal.aborted||!Ge&&x.length)S()}),Ge=!1,S=()=>{},!w.signal.aborted&&Be)try{z=await Ye({jobId:l.jobId,action:"inspect",input:{after:F}})}catch(Me){if(!J||!(Me instanceof r)||Me.code!=="cancelled")throw Me}}}catch(le){ke??=le}finally{if(re=!1,x.length=0,clearTimeout(W),e.signal.removeEventListener("abort",I),I(),T&&(!z||!mt(z)))try{z=await Te()}catch{z=void 0}try{if(!z||!mt(z)||z.pty?.cleanup!=="confirmed")cr("pty_cleanup_unconfirmed");let le=Re(z);if(g.readyState===xn.OPEN)await new Promise((he)=>{let xe=setTimeout(he,500);g.send(JSON.stringify({t:"exit",code:z.exitCode,receipt:le}),()=>{clearTimeout(xe),he()})});await qe("pty.stopped",le)}catch(le){ke??=le}g.terminate()}if(ke)throw ke;if(e.signal.aborted)cr("cancelled");if(!z)cr("pty_cleanup_unconfirmed");return{receipt:Re(z)}}import{createHash as hi,randomUUID as An}from"crypto";import{spawnSync as Wo}from"child_process";import{closeSync as No,constants as Pn,fstatSync as gi,fsyncSync as bi,lstatSync as Bt,mkdirSync as wi,mkdtempSync as Fo,openSync as Lo,readFileSync as yi,readdirSync as zo,realpathSync as Lt,rmSync as In,unlinkSync as vi}from"fs";import{createConnection as ki}from"net";import{dirname as Si,join as nt,sep as Ei}from"path";import{tmpdir as Ri}from"os";var Pr=new Map,qr=new Map;function Kr(e,l){return hi("sha256").update(JSON.stringify([e,l])).digest("hex")}function ht(e){try{wi(e,{mode:448})}catch(f){if(!(f instanceof Error&&("code"in f)&&f.code==="EEXIST"))throw f}let l=Bt(e);if(!l.isDirectory()||l.isSymbolicLink()||!A(l)||Lt(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function xi(e){let l;try{l=Bt(e)}catch(f){if(f instanceof Error&&"code"in f&&f.code==="ENOENT")return!1;throw f}return!l.isDirectory()||l.isSymbolicLink()||zo(e).length>0}function pr(e){let l=Kr(e.root,e.runId),f=e.previousRuntimeDirectories?.find((I)=>xi(nt(I,"jobs",l.slice(0,16))))??e.runtimeDirectory;ht(f);let g=nt(f,"jobs");ht(g);let w=nt(g,l.slice(0,16));if(e.maxScopes!==void 0){let I=zo(g);if(!Number.isSafeInteger(e.maxScopes)||e.maxScopes<1||I.length>e.maxScopes||!I.includes(l.slice(0,16))&&I.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.")}ht(w);let S=Fo(nt(Uo(),"reason-j-"));try{return ht(S),{journalDirectory:w,scopeId:l,launchDirectory:S,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${An()}`:nt(S,"control.sock"),disposeSocket:()=>In(S,{recursive:!0,force:!0})}}catch(I){throw In(S,{recursive:!0,force:!0}),I}}var Ai=60000,Di=5000;function Ci(e){if(process.platform==="win32")return Ni(e);let l=Wo("ps",["-o","lstart=","-p",String(e)],{encoding:"utf8",timeout:2000,env:{...process.env,LC_ALL:"C",LANG:"C"}}),f=l.status===0?/^\w{3} (\w{3}) +(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/.exec(l.stdout.trim()):null,g=f?"JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(f[1]):-1;if(!f||g<0||g%3!==0)return null;let w=new Date(Number(f[6]),g/3,Number(f[2]),Number(f[3]),Number(f[4]),Number(f[5])).getTime();return Number.isFinite(w)?w:null}function Ni(e){let l=Wo(C("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().ToString('o')`],{encoding:"utf8",timeout:5000,windowsHide:!0,env:Ne()}),f=l.status===0?Date.parse(l.stdout.trim()):Number.NaN;return Number.isFinite(f)?f:null}function $o(e,l={}){let f=nt(e.journalDirectory,"owner.lock"),g;try{g=Lo(f,Pn.O_RDONLY|Pn.O_NOFOLLOW)}catch{return null}try{let w=gi(g);if(!w.isFile()||w.nlink!==1||!A(w)||w.size>4096)return null;let S=null;try{S=JSON.parse(yi(g,"utf8"))}catch{}let I;if(S===null){if((l.now??Date.now)()-w.mtimeMs<Ai)return null;I={reason:"never_written",executorLaunchId:null}}else{let{version:M,scopeId:G,pid:F,createdAtMs:T,executorLaunchId:re}=S;if(M!==1||G!==e.scopeId||typeof re!=="string"||typeof F!=="number"||!Number.isSafeInteger(F)||F<1||F===process.pid||typeof T!=="number"||!Number.isSafeInteger(T))return null;if(!(l.exists??((z)=>{try{return process.kill(z,0),!0}catch(fe){return!(fe instanceof Error&&("code"in fe)&&fe.code==="ESRCH")}}))(F))I={reason:"owner_exited",executorLaunchId:re};else{let z=(l.startedAtMs??Ci)(F);if(z===null||z<=T+Di)return null;I={reason:"pid_reused",executorLaunchId:re}}}let W=Bt(f);if(W.dev!==w.dev||W.ino!==w.ino)return null;vi(f);let x=Lo(e.journalDirectory,Pn.O_RDONLY);try{bi(x)}finally{No(x)}return I}catch{return null}finally{No(g)}}function Ko(e){let l={...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)})},f=Kr(l.root,l.runId);if(Pr.has(f)||l.operationId!==void 0&&qr.has(l.operationId))throw new r("hands_jobs_busy","The Session already has a live Hands job supervisor.");let g={binding:l,key:f,terminals:new Map};if(l.previewAuthority&&l.environment)g.previews=Ao({authority:l.previewAuthority,runId:l.runId,expiresAtMs:l.expiresAtMs,executorLaunchId:l.executorLaunchId,environment:l.environment,isCurrent:()=>Pr.get(g.key)===g,identity:()=>{try{return gt(l)}catch{return null}},inspect:(w,S)=>{if(Pr.get(g.key)!==g)throw new r("preview_unavailable","The Hands supervisor is no longer current.");return Go(l,{jobId:w,action:"inspect",input:{after:0}},S)}});if(Pr.set(f,g),l.operationId!==void 0)qr.set(l.operationId,g);return()=>{if(Pr.get(g.key)===g)Pr.delete(g.key);if(l.operationId!==void 0&&qr.get(l.operationId)===g)qr.delete(l.operationId);g.previews?.dispose();for(let w of g.terminals.values())w.abort()}}var Li=5000,Bi=20;async function zi(e){let l=(w)=>{throw new r("hands_rebind_unavailable",w)};if(!N(e.operationId)||!N(e.runId)||!N(e.fenceId)||!U(e.targetGeneration))l("Reason sent an invalid Hands rebind.");let f=qr.get(e.operationId);if(!f||f.binding.root!==e.root)return l("No live Hands supervisor owns this operation.");for(let w=Date.now()+Li;;){if(e.signal?.aborted)l("The Hands rebind was cancelled.");if(qr.get(e.operationId)!==f)l("The Hands supervisor is no longer current.");let S=null;try{S=gt(f.binding)}catch{}if(S&&S.generation===e.targetGeneration&&S.fenceId===e.fenceId)break;if(S&&S.generation>e.targetGeneration||Date.now()>=w)l("The executor did not adopt this take.");await new Promise((I)=>setTimeout(I,Bi))}if(qr.get(e.operationId)!==f||Pr.get(f.key)!==f)l("The Hands supervisor is no longer current.");let g=Kr(e.root,e.runId);if(f.key===g)return;if(Pr.has(g))l("The taking run already has a live Hands job supervisor.");Pr.delete(f.key);for(let w of f.terminals.values())w.abort();f.key=g,Pr.set(g,f)}function it(e){let l="operationId"in e?qr.get(e.operationId):Pr.get(Kr(e.root,e.runId)),f=l&&l.binding.root===e.root?l.binding:void 0;if(!f?.environment||f.expiresAtMs<=Date.now())throw new r("environment_unavailable","No live Hands supervisor owns this environment.");return f.environment.install(e.payload)}async function qi(e){let l=Pr.get(Kr(e.root,e.runId));if(!l?.previews||!e.owner)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return l.previews.open(e.payload,e.owner,e.signal)}async function Wi(e){let l=Pr.get(Kr(e.root,e.runId));if(!l?.previews||!e.owner||e.signal.aborted)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return l.previews.close(e.payload,e.owner)}async function Vi(e){let l=Kr(e.root,e.runId),f=Pr.get(l),g=f?.binding,w=g?.runId,S=g?.previewAuthority,I=g?.environment,W=e.owner&&{...e.owner},x=e.authority&&{...e.authority},M=()=>{throw new r("pty_binding_unavailable","No current authenticated Hands scope owns this terminal.")};if(!f||!g||!S||!I||!W||!x||!g.workspace)return M();let G=Object.freeze({...g.workspace}),F=gt(g),T=I.current(),re=()=>{if(Pr.get(l)!==f||W.organization_id!==S.owner.organization_id||W.user_id!==S.owner.user_id||W.device_id!==S.owner.device_id||e.deviceId!==S.owner.device_id||e.rootId!==S.rootId||O(e.workspace)!==O(G))M();let z=gt(g),fe=I.current();if(z.generation!==F.generation||z.fenceId!==F.fenceId||fe.run_id!==w||fe.device_id!==e.deviceId||fe.root_id!==e.rootId||fe.snapshot_id!==T.snapshot_id||fe.revision!==T.revision||fe.binding.target_generation!==F.generation||fe.binding.target_fence_id!==F.fenceId||x.device_id!==e.deviceId||x.binding!==fe.binding.kind||x.target_revision!==fe.binding.target_revision||x.root_grant_revision!==fe.binding.root_grant_revision||x.target_generation!==F.generation||x.target_fence_id!==F.fenceId)M()};if(re(),new URL(e.session.relayUrl).origin!==S.relayOrigin||f.terminals.has(e.session.jobId)||f.terminals.size>=4)return M();let J=new AbortController;f.terminals.set(e.session.jobId,J);try{return await Ho({session:{...e.session,leaseExpiresAtMs:Math.min(e.session.leaseExpiresAtMs,F.expiresAtMs,Date.parse(T.expires_at))},signal:AbortSignal.any([e.signal,J.signal]),emit:e.emit,binding:{assertCurrent:re,environment:{revision:T.revision,snapshotId:T.snapshot_id},scope:{runId:e.runId,deviceId:e.deviceId,rootId:e.rootId,workspace:G,binding:T.binding.kind,targetRevision:T.binding.target_revision,rootGrantRevision:T.binding.root_grant_revision,generation:F.generation,fenceId:F.fenceId,executorLaunchId:F.executorLaunchId},request:(z,fe)=>hr(F,Ur(JSON.stringify({...z,type:"job",version:2,generation:F.generation,id:An()})),fe)}})}finally{if(f.terminals.get(e.session.jobId)===J)f.terminals.delete(e.session.jobId)}}async function Gi(e){if(ce(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let l=Pr.get(Kr(e.root,e.runId))?.binding;if(!l||l.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","No live Hands supervisor owns this Session and root.");return Go(l,e.payload,e.signal)}var ji=1e4,Mi=20,Fi=ve/2,Ui=Ke/2,$i=(e)=>e.output.reduce((l,f)=>l+f.text.length,0);async function Go(e,l,f){if(Object.keys(l).some((M)=>!["jobId","action","input","waitForExitMs"].includes(M)))throw new r("invalid_payload","Unexpected job control field.");let{waitForExitMs:g,...w}=l;if(g!==void 0&&(w.action!=="start"||typeof w.input!=="object"||w.input===null||!("script"in w.input)||typeof g!=="number"||!Number.isSafeInteger(g)||g<1||g>ji))throw new r("invalid_payload","Only a script start may wait for its job, within its bound.");let S=(M)=>{let G=gt(e);return hr(G,Ur(JSON.stringify({...M,type:"job",version:2,generation:G.generation,id:An()})),f)},I=await S(w);if(g===void 0)return I;let W=Date.now()+g,x=I;while(x.ok&&["starting","running"].includes(x.job.state)&&x.job.output.length<Fi&&$i(x.job)<Ui&&!f.aborted&&Date.now()<W){if(await new Promise((M)=>setTimeout(M,Math.min(Mi,W-Date.now()))),f.aborted)break;try{let M=await S({jobId:w.jobId,action:"inspect",input:{after:0}});if(!M.ok)break;x=M}catch{break}}return x}function gt(e){if(e.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","Hands authority expired.");let l=e.readIdentity?e.readIdentity():e;if(!l||!U(l.generation)||!N(l.fenceId)||l.generation<e.generation||l.generation===e.generation&&l.fenceId!==e.fenceId)throw new r("hands_jobs_unavailable","The live Hands fencing identity could not be verified.");return e.generation=l.generation,e.fenceId=l.fenceId,{...e}}function hr(e,l,f){if(f.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((g,w)=>{let S=ki(e.socketPath),I="",W=!1,x,M=(F,T)=>{if(W)return;if(W=!0,clearTimeout(x),f.removeEventListener("abort",G),S.destroy(),F)w(F);else g(T)},G=()=>M(new r("cancelled","Job control waiter cancelled; inspect before retrying mutations."));f.addEventListener("abort",G,{once:!0}),S.setEncoding("utf8"),x=setTimeout(()=>M(new r("hands_job_result_unknown","Job control timed out; inspect before retrying mutations.")),Math.min(1e4,Math.max(1,e.expiresAtMs-Date.now()))),S.on("error",()=>M(new r("hands_job_result_unknown","Hands job control connection failed."))),S.once("connect",()=>S.write(JSON.stringify({version:1,scopeId:e.scopeId,fenceId:e.fenceId,executorLaunchId:e.executorLaunchId,request:l})+`
|
|
2
|
+
import{zt,j}from"./vm-hands-entry-lite-pf5qtbj5.js";import{ue,Ce,Z,Ae,de,rr,Qe,X,O,H,tn}from"./vm-hands-entry-lite-3krzmhkk.js";import{_o,Vn}from"./vm-hands-entry-lite-aj139v8j.js";import{lo,P,Ke,ve,Je,ne,Ze,Bn,Se,Gt,ae,U,N,ce,Ur,Hr,jn}from"./vm-hands-entry-lite-tdgtpx8e.js";import{Pe,oe,pe,Y,Oe,q,Q}from"./vm-hands-entry-lite-4vks5phw.js";import{It,Sr,st,V,D,R,b}from"./vm-hands-entry-lite-beyyy1gz.js";import{xr,kr,bn,io,ze,vn}from"./vm-hands-entry-lite-s5qkb1fk.js";import{K}from"./vm-hands-entry-lite-hk6trmwa.js";import{Ii}from"./vm-hands-entry-lite-fbhqfzbq.js";import{p,He,Dt,at,Yi,_e,we}from"./vm-hands-entry-lite-s4bharcb.js";import{v,h,oo}from"./vm-hands-entry-lite-wx4ax7wg.js";import{E}from"./vm-hands-entry-lite-dk79tnax.js";import{er}from"./vm-hands-entry-lite-3tx0tkeq.js";import{a,ie,Do}from"./vm-hands-entry-lite-jev771b3.js";import{L,Pi,Ti,Bo,y,t,k,xt,o,d,u,i,c,_,ee,s,n}from"./vm-hands-entry-lite-avc65bd7.js";import{Oi}from"./vm-hands-entry-lite-hbs3tpdg.js";import{jo,se,Uo,C,Ne,$e,A}from"./vm-hands-entry-lite-6c67a3jc.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";var li=()=>{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 l(w){return e[w]??null}let f={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"},g={nan:"NaN"};return(w)=>{switch(w.code){case"invalid_type":{let S=g[w.expected]??w.expected,I=Bo(w.input),W=g[I]??I;return`Invalid input: expected ${S}, received ${W}`}case"invalid_value":if(w.values.length===1)return`Invalid input: expected ${Ti(w.values[0])}`;return`Invalid option: expected one of ${Pi(w.values,"|")}`;case"too_big":{let S=w.inclusive?"<=":"<",I=l(w.origin);if(I)return`Too big: expected ${w.origin??"value"} to have ${S}${w.maximum.toString()} ${I.unit??"elements"}`;return`Too big: expected ${w.origin??"value"} to be ${S}${w.maximum.toString()}`}case"too_small":{let S=w.inclusive?">=":">",I=l(w.origin);if(I)return`Too small: expected ${w.origin} to have ${S}${w.minimum.toString()} ${I.unit}`;return`Too small: expected ${w.origin} to be ${S}${w.minimum.toString()}`}case"invalid_format":{let S=w;if(S.format==="starts_with")return`Invalid string: must start with "${S.prefix}"`;if(S.format==="ends_with")return`Invalid string: must end with "${S.suffix}"`;if(S.format==="includes")return`Invalid string: must include "${S.includes}"`;if(S.format==="regex")return`Invalid string: must match pattern ${S.pattern}`;return`Invalid ${f[S.format]??w.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${w.divisor}`;case"unrecognized_keys":return`Unrecognized key${w.keys.length>1?"s":""}: ${Pi(w.keys,", ")}`;case"invalid_key":return`Invalid key in ${w.origin}`;case"invalid_union":if(w.options&&Array.isArray(w.options)&&w.options.length>0)return`Invalid discriminator value. Expected ${w.options.map((I)=>`'${I}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${w.origin}`;default:return"Invalid input"}}};function En(){return{localeError:li()}}L(En());class _t extends Error{}function Ro(e){let l;try{l=new URL(e)}catch{throw new _t("The proxy must be a URL like https://proxy.example.com:3128.")}if(l.protocol!=="https:"&&l.protocol!=="http:")throw new _t("The proxy URL must use the https or http scheme.");if(!l.hostname)throw new _t("The proxy URL must name a host.");if(l.port!==""&&Number(l.port)<1)throw new _t("The proxy URL must use a port between 1 and 65535.");if(l.pathname!==""&&l.pathname!=="/"||l.search||l.hash)throw new _t("The proxy URL must not carry a path, query, or fragment.");return l.toString()}import{createHash as ui}from"crypto";import{isAbsolute as Oo,join as xo,relative as Po,resolve as Yt,sep as Io}from"path";var qt=t().min(1).refine(Oo,"absolute path required"),On=c({version:n(1),apiOrigin:xt(),channel:s(["staging","production"]),stateDirectory:qt,workspaceRoot:qt,lifetime:s(["persistent","ephemeral"]),executionMode:s(["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:c({version:n(zt),url:t().refine((e)=>{try{return Ro(e)===e}catch{return!1}},"invalid proxy URL"),caFile:qt.optional()}).optional(),userChrome:d().optional(),cloudSessions:n(!0).optional(),localLogins:d().optional(),folders:u(qt).min(1).max(31).optional()}),fi=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,B=_("channel",[On,On.extend({channel:n("pr"),apiOrigin:t(),prEnvironment:t()}),On.extend({channel:n("local-qa"),apiOrigin:t()})]).superRefine((e,l)=>{if(e.channel==="local-qa"){if(!fi.test(e.apiOrigin))l.addIssue({code:"custom",message:"local QA worker requires an exact HTTPS trycloudflare.com quick-tunnel origin"})}else if(e.channel==="pr"){let g=e.prEnvironment,w=/^https:\/\/([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)\.up\.railway\.app$/.exec(e.apiOrigin),S=w?.[1]?.match(/(?:^|-)pr-[0-9]+(?=-|$)/g)?.map((I)=>I.replace(/^-/,""));if(!g||/^pr-[1-9][0-9]*$/.exec(g)?.[0]!==g||w?.[0]!==e.apiOrigin||S?.length!==1||S[0]!==g)l.addIssue({code:"custom",message:"PR worker requires explicit prEnvironment and an exact same-PR HTTPS Railway origin"})}else{let g=new URL(e.apiOrigin);if(g.origin!==e.apiOrigin||g.username||g.password||g.protocol!=="https:"&&!(g.protocol==="http:"&&Vn(g.origin))||!Vn(g.origin)&&!_o(e.channel,g.origin))l.addIssue({code:"custom",message:"API origin must match channel (or loopback)"})}if(!je(e.workspaceRoot,e.stateDirectory))l.addIssue({code:"custom",message:"state and workspace must be disjoint"});let f=e.folders??[];if(new Set([e.workspaceRoot,...f]).size!==f.length+1||f.some((g)=>!je(g,e.stateDirectory)))l.addIssue({code:"custom",message:"folders must be distinct and disjoint from state"})});function m(e){return xo(e.stateDirectory,`headless-${e.channel==="pr"?e.prEnvironment:e.channel}`)}function je(e,l){if($r(l,e))return!1;return!$r(e,l)||E(xo(Io,Po(Yt(e),Yt(l))))}function $r(e,l){let f=Po(Yt(e),Yt(l));return f===""||f!==".."&&!f.startsWith(`..${Io}`)&&!Oo(f)}function te(e){let{proxy:l,userChrome:f,cloudSessions:g,localLogins:w,folders:S,...I}=e;return ui("sha256").update(JSON.stringify(I)).digest("hex")}var pi=4,_i=[2375,2376,9222,9229];function dr(e){let l=new Set(_i);for(let f of e){let g=new URL(f);l.add(Number(g.port||(["https:","wss:"].includes(g.protocol)?443:80)))}return l}function Vr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var mi=60000;function Ao(e){let l=new AbortController,f=new Map,g=(x)=>JSON.stringify([x.jobId,x.port]);function w(x){let M=e.authority.owner;if(l.signal.aborted||!e.isCurrent()||e.expiresAtMs<=Date.now()||x.organization_id!==M.organization_id||x.user_id!==M.user_id||x.device_id!==M.device_id)Vr()}function S(x){let M;try{M=e.environment.current()}catch{return null}return M.binding.target_generation===x.generation&&M.binding.target_fence_id===x.fenceId&&M.run_id===e.runId&&M.device_id===e.authority.owner.device_id&&M.root_id===e.authority.rootId?M:null}async function I(x,M,G){let F=await W(x,M,G);if(F!=="moved")return F;let T=await W(x,M,G);return T==="moved"?null:T}async function W(x,M,G){try{w(e.authority.owner);let F=e.identity();if(!F||G.aborted||x.expiresAtMs<=Date.now()||x.expiresAtMs>e.expiresAtMs)return null;let T=M.opened,re=T!==void 0&&F.generation>T.generation,J=S(F);if(re){if(J){if(J.revision<=T.revision||x.expiresAtMs>Date.parse(J.expires_at)||J.binding.target_revision!==T.attachmentRevision||J.binding.root_grant_revision!==T.grantRevision)return null;M.recoveringSinceMs=void 0}else if(Date.now()-(M.recoveringSinceMs??=Date.now())>mi)return null}else if(!J||x.expiresAtMs>Date.parse(J.expires_at)||T&&(F.generation!==T.generation||F.fenceId!==T.fenceId))return null;let z=await e.inspect(x.jobId,G),fe=e.identity(),ke=fe&&S(fe);w(e.authority.owner);let be=J&&{generation:F.generation,fenceId:F.fenceId,snapshotId:J.snapshot_id,revision:J.revision,attachmentRevision:J.binding.target_revision,grantRevision:J.binding.root_grant_revision},Re=re?T:be;if(G.aborted||!fe)return null;if(fe.generation!==F.generation||fe.fenceId!==F.fenceId||ke?.snapshot_id!==J?.snapshot_id||ke?.revision!==J?.revision)return"moved";let Fe=z.ok&&z.job.environmentSnapshotId!==void 0&&z.job.environmentRevision!==void 0?{snapshotId:z.job.environmentSnapshotId,revision:z.job.environmentRevision}:null;if(!z.ok||z.generation!==F.generation||!Re||!Fe)return null;if((Fe.snapshotId!==Re.snapshotId||Fe.revision!==Re.revision)&&(re||!e.environment.carried(Fe.snapshotId,Fe.revision)))return null;if(!T&&F.generation===x.generation&&F.fenceId===x.fenceId)M.opened={...Re,...Fe};return{executorLaunchId:e.executorLaunchId,job:z.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:z.job.jobId,port:x.port,expiresAtMs:x.expiresAtMs}}}catch{return null}}return{async open(x,M,G){w(M);let{binding:F,deviceRelayUrl:T}=at(x);if(G.aborted||F.expiresAtMs<=Date.now()||F.expiresAtMs>Date.now()+p.lifetimeMs||new URL(T).origin!==e.authority.relayOrigin)Vr();let re=g(F),J=f.get(re);if(J){if(!He(J.binding,F)||J.relay!==T)Vr();if(await J.opened,!await Dt(()=>J.port.check())||G.aborted||J.abort.signal.aborted)Vr();return{opened:!0,binding:F}}if(f.size>=pi)Vr();let z=new AbortController,fe={},ke=we({binding:F,deniedPorts:e.authority.deniedPorts,readCurrentJob:()=>I(F,fe,z.signal)}),be=()=>z.abort();if(G.addEventListener("abort",be,{once:!0}),l.signal.addEventListener("abort",be,{once:!0}),G.aborted||l.signal.aborted)be();let Re=_e({binding:F,deviceRelayUrl:T,port:ke,signal:z.signal}),Fe={binding:F,relay:T,abort:z,port:ke,opened:Re};f.set(re,Fe);let Ye=()=>{if(G.removeEventListener("abort",be),l.signal.removeEventListener("abort",be),f.get(re)===Fe)f.delete(re)};try{if((await Re).closed.then(Ye),G.removeEventListener("abort",be),w(M),z.signal.aborted||!await Dt(()=>ke.check()))Vr();return{opened:!0,binding:F}}catch{z.abort(),Ye(),Vr()}},async close(x,M){w(M);let{binding:G}=Yi(x),F=f.get(g(G));if(!F||!He(F.binding,G))Vr();return F.abort.abort(),await F.opened.then((T)=>T.closed,()=>{return}),{closed:!0,binding:G}},dispose(){l.abort();for(let x of f.values())x.abort.abort();f.clear()}}}import{WebSocket as xn}from"ws";var To=(e)=>("data"in e)?e.data.length:e.bytes,Co=2*Ze;function cr(e){throw new r(e,"The bound Hands terminal is unavailable or its outcome is unconfirmed.")}var mt=(e)=>!["starting","running"].includes(e.state);function Hi(e,l,f=Date.now()){let g=["relay_url","session_id","expires_at","cols","rows","pty","workspace"];if(Object.keys(e).length!==g.length||Object.keys(e).some((M)=>!g.includes(M))||!ae(l)||!ae(e.session_id)||typeof e.expires_at!=="string"||typeof e.relay_url!=="string"||e.relay_url.length>4096||![e.cols,e.rows].every((M)=>Number.isSafeInteger(M)&&Number(M)>=1&&Number(M)<=Se))cr("invalid_pty_request");let w=e.pty;if(!w||typeof w!=="object"||Array.isArray(w))cr("invalid_pty_request");let S=w;if(Object.keys(S).length!==2||S.version!==1||!ce(S.jobId))cr("invalid_pty_request");let I;try{I=new URL(e.relay_url)}catch{return cr("invalid_pty_request")}if(!["ws:","wss:"].includes(I.protocol)||I.username||I.password||I.hash||I.protocol==="ws:"&&!["127.0.0.1","[::1]","localhost"].includes(I.hostname))cr("invalid_pty_request");let W=Date.parse(e.expires_at);if(!Number.isSafeInteger(W)||W<=f)cr("invalid_pty_request");return{workspace:H(e.workspace)??cr("invalid_pty_request"),session:{jobId:S.jobId,sessionId:e.session_id,operationId:l,relayUrl:I.href,cols:Number(e.cols),rows:Number(e.rows),leaseExpiresAtMs:Math.min(W,f+43200000)}}}async function Ho(e){let{session:l,binding:f}=e;if(f.assertCurrent(),e.signal.aborted||Date.now()>=l.leaseExpiresAtMs)cr("cancelled");let g=new xn(l.relayUrl,{followRedirects:!1,perMessageDeflate:!1,maxPayload:ne}),w=new AbortController,S=()=>{},I=()=>{w.abort(),S()};e.signal.addEventListener("abort",I,{once:!0});let W=setTimeout(I,Math.max(1,l.leaseExpiresAtMs-Date.now())),x=[],M=0,G=0,F=0,T=!1,re=!1,J=!1,z,fe,ke,be=(le)=>{ke=new r(le,"Bound terminal input was refused."),I()};g.on("error",()=>be("pty_relay_unavailable")),g.on("close",I),g.on("message",(le,he)=>{if(w.signal.aborted)return;if(!re){be("pty_not_ready");return}let xe=Array.isArray(le)?Buffer.concat(le):le instanceof ArrayBuffer?Buffer.from(le):le;if(xe.length===0)return;let Ge=x.at(-1),Le=he&&Ge!==void 0&&"data"in Ge&&Ge.data.length+xe.length<=ne;if(xe.length>ne||M+xe.length>Bn){be("pty_input_backpressure");return}if(Le)Ge.data=Buffer.concat([Ge.data,xe]);else if(he)x.push({data:Buffer.from(xe)});else try{let Be=JSON.parse(xe.toString("utf8"));if(Be&&Be.t==="close"&&Object.keys(Be).length===1){J=!0,I();return}if(!Be||Be.t!=="resize"||Object.keys(Be).length!==3||![Be.cols,Be.rows].every((Ee)=>Number.isSafeInteger(Ee)&&Ee>=1&&Ee<=Se))throw Error("invalid_control");x.push({cols:Be.cols,rows:Be.rows,bytes:xe.length})}catch{be("invalid_pty_control");return}M+=xe.length,S()});function Re(le){return jn(JSON.stringify({...f.scope,version:1,sessionId:l.sessionId,operationId:l.operationId,job:{...le,output:[],pty:le.pty?{...le.pty,output:[]}:void 0}}))}function Fe(le){if(!le.ok)cr(le.error);let he=le.job;if(le.generation!==f.scope.generation||he.jobId!==l.jobId||!he.pty||he.leaseExpiresAtMs>l.leaseExpiresAtMs||he.process&&he.process.executorLaunchId!==f.scope.executorLaunchId||he.process&&fe&&(he.process.pid!==fe.pid||he.process.processGroupId!==fe.processGroupId)||he.state!=="starting"&&(he.environmentRevision!==f.environment.revision||he.environmentSnapshotId!==f.environment.snapshotId))cr("pty_binding_changed");if(Re(he),he.process)fe??={...he.process};return he}async function Ye(le){f.assertCurrent();let he=await f.request(le,w.signal);if(f.assertCurrent(),w.signal.aborted)cr("cancelled");let xe=Fe(he);if(xe.inputSequence!==G)cr("job_input_sequence");if(!mt(xe)&&xe.leaseExpiresAtMs<=Date.now())cr("pty_binding_changed");return xe}function ye(le){if(f.assertCurrent(),w.signal.aborted||g.readyState!==xn.OPEN||g.bufferedAmount+Buffer.byteLength(le)>Co)cr("pty_output_backpressure");g.send(le)}function We(le){if(le.firstCursor>F+1)F=le.firstCursor-1;for(let he of le.pty.output){if(he.cursor<=F)continue;if(he.cursor!==F+1)cr("pty_output_gap");let xe=Buffer.from(he.dataBase64,"base64");if(g.bufferedAmount+xe.length>Co)return!1;ye(xe),F=he.cursor}if(F!==le.nextCursor)cr("pty_output_gap");return!0}async function qe(le,he){let xe;try{await Promise.race([e.emit(le,he),new Promise((Ge,Le)=>{xe=setTimeout(()=>Le(new r("pty_event_unavailable","Terminal metadata delivery timed out.")),2000)})])}finally{clearTimeout(xe)}}async function Te(){let le=AbortSignal.timeout(Gt),he=f.request({jobId:l.jobId,action:"cancel",input:{}},le),xe,Ge=new Promise((Le,Be)=>{if(xe=()=>Be(new r("pty_cleanup_unconfirmed","Terminal cleanup acknowledgement was not observed within authority.")),le.addEventListener("abort",xe,{once:!0}),le.aborted)xe()});try{let Le=await Promise.race([he,Ge]);if(le.aborted)cr("pty_cleanup_unconfirmed");return Fe(Le)}finally{le.removeEventListener("abort",xe)}}try{await new Promise((Le,Be)=>{let Ee=setTimeout(()=>{I(),Be(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),Me=()=>{clearTimeout(Ee),Be(new r("cancelled","Terminal pairing was cancelled."))};if(w.signal.addEventListener("abort",Me,{once:!0}),g.once("open",()=>{clearTimeout(Ee),w.signal.removeEventListener("abort",Me),Le()}),w.signal.aborted)Me()}),f.assertCurrent(),T=!0,z=await Ye({jobId:l.jobId,action:"start",input:{mode:"pty",cols:l.cols,rows:l.rows,leaseExpiresAtMs:l.leaseExpiresAtMs}});let le=Date.now()+5000;while(z.state==="starting"){if(Date.now()>=le)cr("pty_not_ready");await new Promise((Le)=>setTimeout(Le,25)),z=await Ye({jobId:l.jobId,action:"inspect",input:{after:F}})}if(z.state!=="running"||z.inputSequence!==0||z.leaseExpiresAtMs<=Date.now())cr("pty_not_ready");await qe("pty.ready",Re(z)),re=!0,ye(JSON.stringify({t:"open",cols:z.pty.cols,rows:z.pty.rows,receipt:Re(z)}));let he=!1,xe=0,Ge=!1;while(!w.signal.aborted){let Le=z.firstCursor>F+1,Be=We(z);if(mt(z)){if(Be)break}else if(Le)he=!0;else if(he&&Be&&Date.now()>=xe){he=!1,xe=Date.now()+1000;let{cols:Me,rows:or}=z.pty;for(let sr of[{cols:Me,rows:or>1?or-1:2},{cols:Me,rows:or}]){if(mt(z))break;let Ir=++G;if(z=await Ye({jobId:l.jobId,action:"resize",input:{sequence:Ir,...sr}}),z.inputSequence!==Ir)cr("job_input_sequence")}continue}let Ee=mt(z)||Ge?void 0:x.shift();if(Ee){M-=To(Ee);let Me=++G;try{z=await Ye("data"in Ee?{jobId:l.jobId,action:"input",input:{sequence:Me,dataBase64:Ee.data.toString("base64")}}:{jobId:l.jobId,action:"resize",input:{sequence:Me,cols:Ee.cols,rows:Ee.rows}})}catch(or){if(!(or instanceof r)||or.code!=="job_input_backpressure")throw or;G-=1,x.unshift(Ee),M+=To(Ee),Ge=!0;continue}if(z.inputSequence!==Me)cr("job_input_sequence")}else if(await new Promise((Me)=>{let or=setTimeout(Me,Ge||!Be?10:50);if(S=()=>{clearTimeout(or),Me()},w.signal.aborted||!Ge&&x.length)S()}),Ge=!1,S=()=>{},!w.signal.aborted&&Be)try{z=await Ye({jobId:l.jobId,action:"inspect",input:{after:F}})}catch(Me){if(!J||!(Me instanceof r)||Me.code!=="cancelled")throw Me}}}catch(le){ke??=le}finally{if(re=!1,x.length=0,clearTimeout(W),e.signal.removeEventListener("abort",I),I(),T&&(!z||!mt(z)))try{z=await Te()}catch{z=void 0}try{if(!z||!mt(z)||z.pty?.cleanup!=="confirmed")cr("pty_cleanup_unconfirmed");let le=Re(z);if(g.readyState===xn.OPEN)await new Promise((he)=>{let xe=setTimeout(he,500);g.send(JSON.stringify({t:"exit",code:z.exitCode,receipt:le}),()=>{clearTimeout(xe),he()})});await qe("pty.stopped",le)}catch(le){ke??=le}g.terminate()}if(ke)throw ke;if(e.signal.aborted)cr("cancelled");if(!z)cr("pty_cleanup_unconfirmed");return{receipt:Re(z)}}import{createHash as hi,randomUUID as An}from"crypto";import{spawnSync as Wo}from"child_process";import{closeSync as No,constants as Pn,fstatSync as gi,fsyncSync as bi,lstatSync as Bt,mkdirSync as wi,mkdtempSync as Fo,openSync as Lo,readFileSync as yi,readdirSync as zo,realpathSync as Lt,rmSync as In,unlinkSync as vi}from"fs";import{createConnection as ki}from"net";import{dirname as Si,join as nt,sep as Ei}from"path";import{tmpdir as Ri}from"os";var Pr=new Map,qr=new Map;function Kr(e,l){return hi("sha256").update(JSON.stringify([e,l])).digest("hex")}function ht(e){try{wi(e,{mode:448})}catch(f){if(!(f instanceof Error&&("code"in f)&&f.code==="EEXIST"))throw f}let l=Bt(e);if(!l.isDirectory()||l.isSymbolicLink()||!A(l)||Lt(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function xi(e){let l;try{l=Bt(e)}catch(f){if(f instanceof Error&&"code"in f&&f.code==="ENOENT")return!1;throw f}return!l.isDirectory()||l.isSymbolicLink()||zo(e).length>0}function pr(e){let l=Kr(e.root,e.runId),f=e.previousRuntimeDirectories?.find((I)=>xi(nt(I,"jobs",l.slice(0,16))))??e.runtimeDirectory;ht(f);let g=nt(f,"jobs");ht(g);let w=nt(g,l.slice(0,16));if(e.maxScopes!==void 0){let I=zo(g);if(!Number.isSafeInteger(e.maxScopes)||e.maxScopes<1||I.length>e.maxScopes||!I.includes(l.slice(0,16))&&I.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.")}ht(w);let S=Fo(nt(Uo(),"reason-j-"));try{return ht(S),{journalDirectory:w,scopeId:l,launchDirectory:S,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${An()}`:nt(S,"control.sock"),disposeSocket:()=>In(S,{recursive:!0,force:!0})}}catch(I){throw In(S,{recursive:!0,force:!0}),I}}var Ai=60000,Di=5000;function Ci(e){if(process.platform==="win32")return Ni(e);let l=Wo("ps",["-o","lstart=","-p",String(e)],{encoding:"utf8",timeout:2000,env:{...process.env,LC_ALL:"C",LANG:"C"}}),f=l.status===0?/^\w{3} (\w{3}) +(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/.exec(l.stdout.trim()):null,g=f?"JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(f[1]):-1;if(!f||g<0||g%3!==0)return null;let w=new Date(Number(f[6]),g/3,Number(f[2]),Number(f[3]),Number(f[4]),Number(f[5])).getTime();return Number.isFinite(w)?w:null}function Ni(e){let l=Wo(C("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().ToString('o')`],{encoding:"utf8",timeout:5000,windowsHide:!0,env:Ne()}),f=l.status===0?Date.parse(l.stdout.trim()):Number.NaN;return Number.isFinite(f)?f:null}function $o(e,l={}){let f=nt(e.journalDirectory,"owner.lock"),g;try{g=Lo(f,Pn.O_RDONLY|Pn.O_NOFOLLOW)}catch{return null}try{let w=gi(g);if(!w.isFile()||w.nlink!==1||!A(w)||w.size>4096)return null;let S=null;try{S=JSON.parse(yi(g,"utf8"))}catch{}let I;if(S===null){if((l.now??Date.now)()-w.mtimeMs<Ai)return null;I={reason:"never_written",executorLaunchId:null}}else{let{version:M,scopeId:G,pid:F,createdAtMs:T,executorLaunchId:re}=S;if(M!==1||G!==e.scopeId||typeof re!=="string"||typeof F!=="number"||!Number.isSafeInteger(F)||F<1||F===process.pid||typeof T!=="number"||!Number.isSafeInteger(T))return null;if(!(l.exists??((z)=>{try{return process.kill(z,0),!0}catch(fe){return!(fe instanceof Error&&("code"in fe)&&fe.code==="ESRCH")}}))(F))I={reason:"owner_exited",executorLaunchId:re};else{let z=(l.startedAtMs??Ci)(F);if(z===null||z<=T+Di)return null;I={reason:"pid_reused",executorLaunchId:re}}}let W=Bt(f);if(W.dev!==w.dev||W.ino!==w.ino)return null;vi(f);let x=Lo(e.journalDirectory,Pn.O_RDONLY);try{bi(x)}finally{No(x)}return I}catch{return null}finally{No(g)}}function Ko(e){let l={...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)})},f=Kr(l.root,l.runId);if(Pr.has(f)||l.operationId!==void 0&&qr.has(l.operationId))throw new r("hands_jobs_busy","The Session already has a live Hands job supervisor.");let g={binding:l,key:f,terminals:new Map};if(l.previewAuthority&&l.environment)g.previews=Ao({authority:l.previewAuthority,runId:l.runId,expiresAtMs:l.expiresAtMs,executorLaunchId:l.executorLaunchId,environment:l.environment,isCurrent:()=>Pr.get(g.key)===g,identity:()=>{try{return gt(l)}catch{return null}},inspect:(w,S)=>{if(Pr.get(g.key)!==g)throw new r("preview_unavailable","The Hands supervisor is no longer current.");return Go(l,{jobId:w,action:"inspect",input:{after:0}},S)}});if(Pr.set(f,g),l.operationId!==void 0)qr.set(l.operationId,g);return()=>{if(Pr.get(g.key)===g)Pr.delete(g.key);if(l.operationId!==void 0&&qr.get(l.operationId)===g)qr.delete(l.operationId);g.previews?.dispose();for(let w of g.terminals.values())w.abort()}}var Li=5000,Bi=20;async function zi(e){let l=(w)=>{throw new r("hands_rebind_unavailable",w)};if(!N(e.operationId)||!N(e.runId)||!N(e.fenceId)||!U(e.targetGeneration))l("Reason sent an invalid Hands rebind.");let f=qr.get(e.operationId);if(!f||f.binding.root!==e.root)return l("No live Hands supervisor owns this operation.");for(let w=Date.now()+Li;;){if(e.signal?.aborted)l("The Hands rebind was cancelled.");if(qr.get(e.operationId)!==f)l("The Hands supervisor is no longer current.");let S=null;try{S=gt(f.binding)}catch{}if(S&&S.generation===e.targetGeneration&&S.fenceId===e.fenceId)break;if(S&&S.generation>e.targetGeneration||Date.now()>=w)l("The executor did not adopt this take.");await new Promise((I)=>setTimeout(I,Bi))}if(qr.get(e.operationId)!==f||Pr.get(f.key)!==f)l("The Hands supervisor is no longer current.");let g=Kr(e.root,e.runId);if(f.key===g)return;if(Pr.has(g))l("The taking run already has a live Hands job supervisor.");Pr.delete(f.key);for(let w of f.terminals.values())w.abort();f.key=g,Pr.set(g,f)}function it(e){let l="operationId"in e?qr.get(e.operationId):Pr.get(Kr(e.root,e.runId)),f=l&&l.binding.root===e.root?l.binding:void 0;if(!f?.environment||f.expiresAtMs<=Date.now())throw new r("environment_unavailable","No live Hands supervisor owns this environment.");return f.environment.install(e.payload)}async function qi(e){let l=Pr.get(Kr(e.root,e.runId));if(!l?.previews||!e.owner)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return l.previews.open(e.payload,e.owner,e.signal)}async function Wi(e){let l=Pr.get(Kr(e.root,e.runId));if(!l?.previews||!e.owner||e.signal.aborted)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return l.previews.close(e.payload,e.owner)}async function Vi(e){let l=Kr(e.root,e.runId),f=Pr.get(l),g=f?.binding,w=g?.runId,S=g?.previewAuthority,I=g?.environment,W=e.owner&&{...e.owner},x=e.authority&&{...e.authority},M=()=>{throw new r("pty_binding_unavailable","No current authenticated Hands scope owns this terminal.")};if(!f||!g||!S||!I||!W||!x||!g.workspace)return M();let G=Object.freeze({...g.workspace}),F=gt(g),T=I.current(),re=()=>{if(Pr.get(l)!==f||W.organization_id!==S.owner.organization_id||W.user_id!==S.owner.user_id||W.device_id!==S.owner.device_id||e.deviceId!==S.owner.device_id||e.rootId!==S.rootId||O(e.workspace)!==O(G))M();let z=gt(g),fe=I.current();if(z.generation!==F.generation||z.fenceId!==F.fenceId||fe.run_id!==w||fe.device_id!==e.deviceId||fe.root_id!==e.rootId||fe.snapshot_id!==T.snapshot_id||fe.revision!==T.revision||fe.binding.target_generation!==F.generation||fe.binding.target_fence_id!==F.fenceId||x.device_id!==e.deviceId||x.binding!==fe.binding.kind||x.target_revision!==fe.binding.target_revision||x.root_grant_revision!==fe.binding.root_grant_revision||x.target_generation!==F.generation||x.target_fence_id!==F.fenceId)M()};if(re(),new URL(e.session.relayUrl).origin!==S.relayOrigin||f.terminals.has(e.session.jobId)||f.terminals.size>=4)return M();let J=new AbortController;f.terminals.set(e.session.jobId,J);try{return await Ho({session:{...e.session,leaseExpiresAtMs:Math.min(e.session.leaseExpiresAtMs,F.expiresAtMs,Date.parse(T.expires_at))},signal:AbortSignal.any([e.signal,J.signal]),emit:e.emit,binding:{assertCurrent:re,environment:{revision:T.revision,snapshotId:T.snapshot_id},scope:{runId:e.runId,deviceId:e.deviceId,rootId:e.rootId,workspace:G,binding:T.binding.kind,targetRevision:T.binding.target_revision,rootGrantRevision:T.binding.root_grant_revision,generation:F.generation,fenceId:F.fenceId,executorLaunchId:F.executorLaunchId},request:(z,fe)=>hr(F,Ur(JSON.stringify({...z,type:"job",version:2,generation:F.generation,id:An()})),fe)}})}finally{if(f.terminals.get(e.session.jobId)===J)f.terminals.delete(e.session.jobId)}}async function Gi(e){if(ce(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let l=Pr.get(Kr(e.root,e.runId))?.binding;if(!l||l.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","No live Hands supervisor owns this Session and root.");return Go(l,e.payload,e.signal)}var ji=1e4,Mi=20,Fi=ve/2,Ui=Ke/2,$i=(e)=>e.output.reduce((l,f)=>l+f.text.length,0);async function Go(e,l,f){if(Object.keys(l).some((M)=>!["jobId","action","input","waitForExitMs"].includes(M)))throw new r("invalid_payload","Unexpected job control field.");let{waitForExitMs:g,...w}=l;if(g!==void 0&&(w.action!=="start"||typeof w.input!=="object"||w.input===null||!("script"in w.input)||typeof g!=="number"||!Number.isSafeInteger(g)||g<1||g>ji))throw new r("invalid_payload","Only a script start may wait for its job, within its bound.");let S=(M)=>{let G=gt(e);return hr(G,Ur(JSON.stringify({...M,type:"job",version:2,generation:G.generation,id:An()})),f)},I=await S(w);if(g===void 0)return I;let W=Date.now()+g,x=I;while(x.ok&&["starting","running"].includes(x.job.state)&&x.job.output.length<Fi&&$i(x.job)<Ui&&!f.aborted&&Date.now()<W){if(await new Promise((M)=>setTimeout(M,Math.min(Mi,W-Date.now()))),f.aborted)break;try{let M=await S({jobId:w.jobId,action:"inspect",input:{after:0}});if(!M.ok)break;x=M}catch{break}}return x}function gt(e){if(e.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","Hands authority expired.");let l=e.readIdentity?e.readIdentity():e;if(!l||!U(l.generation)||!N(l.fenceId)||l.generation<e.generation||l.generation===e.generation&&l.fenceId!==e.fenceId)throw new r("hands_jobs_unavailable","The live Hands fencing identity could not be verified.");return e.generation=l.generation,e.fenceId=l.fenceId,{...e}}function hr(e,l,f){if(f.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((g,w)=>{let S=ki(e.socketPath),I="",W=!1,x,M=(F,T)=>{if(W)return;if(W=!0,clearTimeout(x),f.removeEventListener("abort",G),S.destroy(),F)w(F);else g(T)},G=()=>M(new r("cancelled","Job control waiter cancelled; inspect before retrying mutations."));f.addEventListener("abort",G,{once:!0}),S.setEncoding("utf8"),x=setTimeout(()=>M(new r("hands_job_result_unknown","Job control timed out; inspect before retrying mutations.")),Math.min(1e4,Math.max(1,e.expiresAtMs-Date.now()))),S.on("error",()=>M(new r("hands_job_result_unknown","Hands job control connection failed."))),S.once("connect",()=>S.write(JSON.stringify({version:1,scopeId:e.scopeId,fenceId:e.fenceId,executorLaunchId:e.executorLaunchId,request:l})+`
|
|
3
3
|
`)),S.on("data",(F)=>{if(I+=F,Buffer.byteLength(I)>Je)M(new r("hands_job_result_unknown","Hands job result exceeded its bound."))}),S.once("end",()=>{if(Date.now()>=e.expiresAtMs){M(new r("hands_job_result_unknown","Hands authority expired before the result was acknowledged."));return}try{let F=Hr(I.trim());if(F.id!==l.id||F.generation!==e.generation||F.ok&&F.job.jobId!==l.jobId)throw Error("identity");M(void 0,F)}catch{M(new r("hands_job_result_unknown","Hands job response identity or shape was invalid."))}}),S.once("close",()=>{if(!W)M(new r("hands_job_result_unknown","Hands job control closed before an acknowledged result."))})})}function Mo(e){let l=Lt(e.root),f=e.authority,g=Date.parse(e.leaseUntil),w=()=>{if(e.signal.throwIfAborted(),!Number.isFinite(g)||g<=Date.now())throw Error("local_device_gh_lease_expired")};if(w(),f.readOnly&&f.generation===null)return{root:l,readOnly:!0,signal:e.signal,deadlineMs:g,assertCurrent:w};let S=Kr(l,e.runId),I=Pr.get(S),W=I?.binding;if(!W?.environment||!W.workspace||W.localGithubConfinement!==!0)throw Error("local_device_gh_confinement_unavailable");let x=W.environment.current(),M=()=>{w();let F=W.environment.current(),T=gt(W);if(Pr.get(S)!==I||F.github_auth!=="local_gh"||F.run_id!==W.runId||f.runId!==e.runId||F.device_id!==f.deviceId||F.root_id!==f.rootId||String(F.binding.root_grant_revision)!==f.rootRevision||F.binding.target_generation!==f.generation||F.binding.target_fence_id!==f.fenceId||T.generation!==f.generation||T.fenceId!==f.fenceId||F.snapshot_id!==x.snapshot_id||F.revision!==x.revision)throw Error("local_device_gh_authority_changed")};M();let G=ie(l,W.workspace);return{root:G.boundary,signal:e.signal,deadlineMs:g,privateDirectory:Si(W.environment.path),repoPath:G.path,readOnly:f.readOnly,forbiddenSecretValues:Object.values(x.variables),secretNames:(F)=>Object.entries(x.variables).filter(([,T])=>T.trim()===F.trim()).map(([T])=>`variable ${T}`),assertCurrent:M}}async function Ki(e,l){let f=Pe.parse(e.request),g=oe.parse(e.authority);if(g.contributorRefresh&&f.kind==="read"&&g.readOnly)return l(Mo(e));let w=Boolean(g.contributorRefresh);if(w&&(g.merge||f.kind!=="pr_mutation"||f.mutation.action!=="edit"||typeof f.mutation.body!=="string"||f.mutation.title!==void 0||f.mutation.base!==void 0||g.readOnly||g.runId!==e.runId||g.repoFullName!==f.repoFullName))throw Error("local_device_gh_contributor_refresh_authority_invalid");if(f.kind!=="pr_merge"&&!w){if(g.merge)throw Error("local_device_gh_merge_authority_invalid");return l(Mo(e))}if(!w&&(!g.merge||g.readOnly||g.runId!==e.runId||g.repoFullName!==f.repoFullName||g.merge.source==="agent"&&(g.generation===null||g.fenceId===null)))throw Error("local_device_gh_merge_authority_invalid");let S=Lt(e.root),I=Bt(S),W=Date.parse(e.leaseUntil);if(!Number.isFinite(W)||W<=Date.now())throw Error("local_device_gh_lease_expired");let x=Lt(Ri());if(x===S||x.startsWith(S+Ei))throw Error("local_device_gh_private_scope_unavailable");let M=Fo(nt(x,"reason-gh-merge-"));try{ht(M);let G=()=>{if(e.signal.throwIfAborted(),Date.now()>=W)throw Error("local_device_gh_lease_expired");let F=Bt(e.root);if(F.isSymbolicLink()||F.dev!==I.dev||F.ino!==I.ino||Lt(e.root)!==S)throw Error("local_device_gh_authority_changed");ht(M)};return G(),await l({root:S,readOnly:!1,privateDirectory:M,forbiddenSecretValues:[],signal:e.signal,deadlineMs:W,assertCurrent:G})}finally{In(M,{recursive:!0,force:!0})}}var qo=43200000;function bt(e){return Number.isSafeInteger(e)&&Math.abs(e)<=8640000000000000?e:null}function Jo(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Vo(e,l){return Object.keys(e).length===l.length&&l.every((f)=>Object.hasOwn(e,f))}function Ji(e){if(!Jo(e)||!Vo(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 g of["validation_now_ms","expiry_ms"]){let w=e[g];if(w!==null&&(typeof w!=="number"||bt(w)===null))return null}if(e.remaining_ms!==null&&(typeof e.remaining_ms!=="number"||!Number.isSafeInteger(e.remaining_ms)))return null;let l=typeof e.expiry_ms==="number"&&typeof e.validation_now_ms==="number"?e.expiry_ms-e.validation_now_ms:null;if(e.remaining_ms!==(l!==null&&Number.isSafeInteger(l)?l: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 l==="number"&&l<=0))return null;if(e.outcome==="over_cap"&&!(typeof l==="number"&&l>43200000))return null;if(e.outcome==="accepted"&&!(typeof l==="number"&&l>0&&l<=43200000))return null;let f=e.cli_artifact;if(!Jo(f)||!Vo(f,["kind","status","sha256","observed_at_ms"])||f.observed_at_ms!==null&&(typeof f.observed_at_ms!=="number"||bt(f.observed_at_ms)===null))return null;if(f.kind==="entrypoint_file"){if(f.status!=="observed"||typeof f.sha256!=="string"||!/^[a-f0-9]{64}$/.test(f.sha256)||f.observed_at_ms===null)return null}else if(f.kind!=="unavailable"||f.sha256!==null||typeof f.status!=="string"||!["unsupported_entrypoint","read_failed","file_changed","size_limit","time_limit"].includes(f.status))return null;return e}var Tn=c({kind:s(["workspace_source","mcp_control"]),target_revision:o().int().nonnegative(),root_grant_revision:o().int().positive()}),Yo=new RegExp(st.tokenPattern),Qi=c({token_url:xt().max(2048),request_token:t().min(1).max(8192).regex(Yo),aws_credentials_url:xt().max(2048).nullable()});function Xo(e,l){let f=(g,w)=>{try{let S=new URL(g);return S.origin===new URL(l).origin&&S.pathname===w&&!S.username&&!S.password&&!S.search&&!S.hash}catch{return!1}};if(!Yo.test(e.request_token)||!f(e.token_url,st.tokenPath)||e.aws_credentials_url!==null&&!f(e.aws_credentials_url,st.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 Zo(e){return new TextEncoder().encode(e).byteLength}function ea(e){return Zo(JSON.stringify(e)+`
|
|
4
4
|
`)}var fr=c({version:n(1),snapshot_id:k(),revision:o().int().positive(),run_id:t().min(1).max(160),device_id:k(),root_id:k(),binding:Tn.extend({target_generation:o().int().positive(),target_fence_id:k()}),expires_at:y.datetime({offset:!0}),variables:ee(t().max(128).regex(It),t().refine((e)=>!e.includes("\x00")&&Zo(e)<=V.valueBytes)).refine((e)=>Object.keys(e).length<=V.variables),github_auth:n("local_gh").optional(),git:c({base_url:xt().max(2048),token:t().min(1).max(4096).regex(/^[A-Za-z0-9._~-]+$/),expires_at:y.datetime({offset:!0})}).nullable(),cloud_access:Qi.optional()}).refine((e)=>e.github_auth!=="local_gh"||e.git===null,"conflicting git authority").refine((e)=>ea(e)<=V.snapshotBytes,"snapshot too large");import{spawn as ra}from"child_process";import{basename as ta,isAbsolute as Eu}from"path";var na=0,Qo=120000,es=15000,oa=65536;function Dn(e=process.execPath,l=process.argv[1]){let f=ta(e),g=(f.startsWith("bun")||f.startsWith("node"))&&typeof l==="string"&&l.length>0;return{command:e,prefix:g?[l]:[]}}function Zi(e={}){let{command:l,prefix:f}=Dn(e.executablePath,e.sourceEntrypoint),g=e.spawnProcess??ra,w=e.now??Date.now,S=null,I=0,W=!1,x=(G)=>{try{G.kill("SIGKILL")}catch{}},M=()=>{if(W)return;if(S&&w()-I<Qo-es)return;if(S){let F=S;S=null,x(F)}let G;try{G=g(l,[...f,"__device","__hands-worker","--handoff-fd",String(na)],{cwd:"/",env:{PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin"},shell:!1,stdio:["pipe","ignore","pipe"]})}catch{return}S=G,I=w(),G.on("error",()=>{if(S===G)S=null}),G.once("exit",(F,T)=>{if(S!==G)return;S=null,e.log?.("hands.worker_prespawn_exited",{exit_code:F,exit_signal:T})}),e.log?.("hands.worker_prespawned",{pid:G.pid??null})};return{arm:M,take(G){let F=S;if(!F||W)return null;let T=G.args.at(-1),re=G.options.env,J=G.options.cwd,z=[...f,"__device","__hands-worker","--config"];if(G.command!==l||G.args.length!==z.length+1||z.some((Re,Fe)=>G.args[Fe]!==Re)||typeof T!=="string"||!re||typeof J!=="string"||G.options.shell||JSON.stringify(G.options.stdio)!==JSON.stringify(["ignore","ignore","pipe"]))return null;S=null;let fe=F.stdin,ke={configPath:T,cwd:J,env:Object.fromEntries(Object.entries(re).filter((Re)=>typeof Re[1]==="string"))},be=JSON.stringify(ke);if(F.exitCode!==null||F.signalCode!==null||!fe||fe.destroyed||w()-I>=Qo-es||Buffer.byteLength(be,"utf8")>oa)return x(F),null;return fe.on("error",()=>{return}),fe.end(be),F.once("exit",()=>{M()}),e.log?.("hands.worker_prespawn_taken",{pid:F.pid??null}),F},adopt(G){G.once("exit",()=>{M()})},close(){if(W=!0,S)x(S);S=null}}}import{accessSync as la,constants as ua,statSync as fa}from"fs";import{homedir as pa,tmpdir as _a,userInfo as ma}from"os";import{delimiter as ha,win32 as ga}from"path";var sa=new Set(["ALL_PROXY","BUN_BE_BUN","BUN_OPTIONS","CURL_CA_BUNDLE","GIT_SSL_CAINFO","GRPC_DEFAULT_SSL_ROOTS_FILE_PATH","HTTPS_PROXY","HTTP_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED","REQUESTS_CA_BUNDLE","SSLKEYLOGFILE","SSL_CERT_DIR","SSL_CERT_FILE","all_proxy","http_proxy","https_proxy","no_proxy"]);var ia=["BUN_CONFIG_","BUN_INSPECT","DYLD_","NODE_DEBUG"],aa=new Set(["BUN_INSTALL"]);var ca=/^--(?:max-old-space-size|max-semi-space-size|stack-size)=\d{1,9}$/;function da(e){return(e??"").split(/\s+/).filter(Boolean).every((l)=>ca.test(l.replaceAll("_","-")))}function rs(e){return Object.keys(e).filter((l)=>sa.has(l)&&!(l==="NODE_OPTIONS"&&da(e[l]))||ia.some((f)=>l.startsWith(f))||l.startsWith("BUN_")&&!aa.has(l)).sort()}var ba=new Set(["HOME","PATH","PWD","OLDPWD","SHLVL","_","TMPDIR","TMP","TEMP","SHELL","BASH_ENV","ENV","ZDOTDIR","PROMPT_COMMAND","IFS","CDPATH","GLOBIGNORE","SHELLOPTS","BASHOPTS","NODE_PATH"]),wa=/^(?:ARA_|REASON_|PI_|GIT_|GH_|GITHUB_|LD_|DYLD_|BUN_|BASH_FUNC_|SSH_)/,ya=/TOKEN|SECRET|PASSW|PASSPHRASE|CREDENTIAL|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|AUTH/i,va=/^[A-Za-z_][A-Za-z0-9_]*$/;function mr(e=process.env){let l=(w)=>{if(!(process.platform==="win32"?ga.isAbsolute(w):w.startsWith("/"))||/[\0\r\n]/.test(w)||w.length>32768)throw Error("invalid_host_execution_environment");return w};if(e.PATH!==void 0&&(/[\0\r\n]/.test(e.PATH)||e.PATH.length>32768))throw Error("invalid_host_execution_environment");let f=new Set(rs(e)),g=Object.fromEntries(Object.entries(e).filter((w)=>{let[S,I]=w;return typeof I==="string"&&I.length<=32768&&!I.includes("\x00")&&S.length<=128&&va.test(S)&&!f.has(S)&&!ba.has(S)&&!wa.test(S)&&!ya.test(S)}).sort(([w],[S])=>w.localeCompare(S)).slice(0,512));return{home:l(e.HOME||(process.platform==="win32"?e.USERPROFILE:void 0)||pa()),path:((w)=>process.platform==="win32"?vn(w):w)(kr(e.PATH??"").join(ha)||xr),temporaryDirectory:l(e.TMPDIR||e.TMP||e.TEMP||_a()),variables:g}}function gr(e=process.env,l=()=>ma().shell){if(process.platform==="win32")return se();let f=(w)=>{if(!w||!/^\/[A-Za-z0-9._/-]*\/(?:bash|zsh)$/.test(w))return!1;try{return la(w,ua.X_OK),fa(w).isFile()}catch{return!1}};if(f(e.SHELL))return e.SHELL;let g;try{g=l()}catch{g=void 0}return f(g)?g:"/bin/zsh"}import{readdir as ka}from"fs/promises";var Sa=15000;function hn(e){let l=e instanceof Error&&"code"in e?e.code:null;return l==="EPERM"||l==="EACCES"}function fn(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 try again.")}async function ts(e,{timeoutMs:l=Sa,open:f=(g)=>ka(g)}={}){let g,w=new Promise((S)=>{g=setTimeout(()=>S("pending"),l)});try{if(await Promise.race([f(e).then(()=>"open"),w])==="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(S){if(hn(S))throw fn(e);if(S instanceof r)throw S}finally{clearTimeout(g)}}import{chmodSync as rc,closeSync as tc,constants as $n,fstatSync as nc,lstatSync as vs,openSync as oc,readSync as sc,realpathSync as Kn,unlinkSync as ic}from"fs";import{lookup as ac}from"dns/promises";import{createRequire as cc}from"module";import{request as dc}from"http";import{request as lc}from"https";import dt from"net";import{platform as Os}from"os";import{basename as uc,extname as fc,isAbsolute as ks,relative as Gn,resolve as vt,sep as Jn}from"path";var ns=String.raw`
|
|
5
5
|
async (roots) => {
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{readdirSync as b,readFileSync as P}from"fs";import{userInfo as k}from"os";var ar="--vm-hands-op-runner-kind=person",cr="--vm-hands-op-runner-kind=surface",Ct="--vm-hands-surface-uid=",At="--vm-hands-surface-dir=",Pt=new Set(["automation.call.v1","display.stream.v1","preview.serve.v1"]);function R(t){let c=new Set([t]),l=[];try{l=b("/proc")}catch{}for(let o of l){if(!/^\d+$/.test(o))continue;try{let d=P(`/proc/${o}/stat`,"utf8");if(Number(d.slice(d.lastIndexOf(")")+2).split(" ")[3])===t)c.add(Number(o))}catch{}}for(let o of c)try{process.kill(o,"SIGKILL")}catch{}}var A=(t)=>{let c=globalThis.Bun;if(!c)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");let l=c.spawn({cmd:[t.shell,...t.args],cwd:t.cwd,env:{...t.environment,TERM:"xterm-256color"},terminal:{cols:t.cols,rows:t.rows,data:(i,s)=>t.onData(s)}}),o=l.terminal,d=()=>{R(l.pid);try{o?.close()}catch{}};if(!o)throw d(),new r("pty_unavailable","Reason could not allocate a pseudo-terminal.");return{write:(i)=>o.write(i),resize:(i,s)=>o.resize(i,s),kill:d,exited:l.exited.then((i)=>typeof i==="number"?i:null,()=>null)}};function x(){let t=(()=>{try{return k().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 E(t){let[{localAutomationAvailable:c},{localDisplayReady:l},{localDisplayVideoAvailable:o},{probeWorkerPreview:d},y]=await Promise.all([import("./local-automation-
|
|
2
|
+
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{readdirSync as b,readFileSync as P}from"fs";import{userInfo as k}from"os";var ar="--vm-hands-op-runner-kind=person",cr="--vm-hands-op-runner-kind=surface",Ct="--vm-hands-surface-uid=",At="--vm-hands-surface-dir=",Pt=new Set(["automation.call.v1","display.stream.v1","preview.serve.v1"]);function R(t){let c=new Set([t]),l=[];try{l=b("/proc")}catch{}for(let o of l){if(!/^\d+$/.test(o))continue;try{let d=P(`/proc/${o}/stat`,"utf8");if(Number(d.slice(d.lastIndexOf(")")+2).split(" ")[3])===t)c.add(Number(o))}catch{}}for(let o of c)try{process.kill(o,"SIGKILL")}catch{}}var A=(t)=>{let c=globalThis.Bun;if(!c)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");let l=c.spawn({cmd:[t.shell,...t.args],cwd:t.cwd,env:{...t.environment,TERM:"xterm-256color"},terminal:{cols:t.cols,rows:t.rows,data:(i,s)=>t.onData(s)}}),o=l.terminal,d=()=>{R(l.pid);try{o?.close()}catch{}};if(!o)throw d(),new r("pty_unavailable","Reason could not allocate a pseudo-terminal.");return{write:(i)=>o.write(i),resize:(i,s)=>o.resize(i,s),kill:d,exited:l.exited.then((i)=>typeof i==="number"?i:null,()=>null)}};function x(){let t=(()=>{try{return k().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 E(t){let[{localAutomationAvailable:c},{localDisplayReady:l},{localDisplayVideoAvailable:o},{probeWorkerPreview:d},y]=await Promise.all([import("./local-automation-0gmnztwx.js"),import("./local-display-session-bnc6whgt.js"),import("./local-display-video-mtd0gnyg.js"),import("./worker-preview-readiness-w62n91kr.js"),import("fs")]),i=AbortSignal.timeout(15000),s=null;try{y.mkdirSync(t,{recursive:!0,mode:448}),s=y.mkdtempSync(`${t}/probe-`);let[g,p,m]=await Promise.all([Promise.resolve().then(()=>c()).catch(()=>!1),l().catch(()=>!1),d(s,i).catch(()=>!1)]);return{t:"readiness",display_video:p&&await o().catch(()=>!1),lanes:{"automation.call.v1":g,"display.stream.v1":p,"preview.serve.v1":m,"tunnel.open":m,"tunnel.close":m}}}finally{if(s)y.rmSync(s,{recursive:!0,force:!0})}}async function as(){let[{executeLocalOperation:t,spawnCaptured:c},{runLocalPtySession:l},{configureDesktopAccount:o,desktopAccount:d},{configureWorkerSandbox:y}]=await Promise.all([import("./local-capabilities-vfteeg61.js"),import("./local-pty-session-rpk05ap5.js"),import("./desktop-account-6sjrxy69.js"),import("./worker-sandbox-2r5nseff.js")]);y();let i=process.argv.includes(ar),s=process.argv.includes(cr),g=(a,e,u)=>c(a,e[0]==="-lic"?["-lc",...e.slice(1)]:e,u),p=(process.geteuid?.()??0)!==0;if(s){p=!1;let a=process.argv.find((e)=>e.startsWith(Ct))?.slice(Ct.length);if((process.geteuid?.()??-1)===0&&a)try{p=o({value:a})!==null&&d()!==null}catch{p=!1}}let m=new Map,v=new Map,f=(a)=>{try{process.send?.(a)}catch{}};if(process.on("message",(a)=>{let e=a;if(e?.t==="cancel"){m.get(e.id)?.abort();return}if(e?.t==="control"){let n=v.get(e.id);if(s&&n&&e.control&&typeof e.control.kind==="string")import("./local-managed-process-khhmd6pe.js").then(({controlManagedDeviceProcess:_})=>_(n,{kind:e.control.kind,payload:e.control.payload??{}})).catch(()=>!1);return}if(e?.t==="retire"){if(s&&typeof e.operation_id==="string"&&typeof e.status==="string")import("./local-managed-process-khhmd6pe.js").then(({retireManagedDeviceProcess:n})=>n(e.operation_id,e.status)).catch(()=>!1);return}if(e?.t!=="op")return;if(!p){f({t:"done",id:e.id,completion:{status:"failed",error_code:"vm_hands_payload_account_unavailable"}});return}let u=e.claim.capability;if(u==="pty.start"&&!i){f({t:"done",id:e.id,completion:{status:"failed",error_code:"capability_not_granted"}});return}if(Pt.has(u)!==s){f({t:"done",id:e.id,completion:{status:"failed",error_code:"capability_not_granted"}});return}let w=new AbortController;m.set(e.id,w),v.set(e.id,e.claim);let S=u==="pty.start"?{runPtySession:(n)=>l(n,{spawnPty:A,environment:x(),loadProxy:()=>null})}:{worker:e.worker,...u==="exec.full"?{spawnFullControl:g}:{}};t(e.state,e.claim,{...S,signal:w.signal,emit:(n)=>{let{deliverySignal:_,...h}=n;f({t:"event",id:e.id,event:h})}}).then((n)=>f({t:"done",id:e.id,completion:n}),(n)=>f({t:"done",id:e.id,completion:{status:"failed",error_code:n&&typeof n==="object"&&"code"in n&&typeof n.code==="string"?n.code:"vm_hands_op_failed"}})).finally(()=>{m.delete(e.id),v.delete(e.id)})}),process.on("disconnect",()=>process.exit(0)),s){let a=process.argv.find((u)=>u.startsWith(At))?.slice(At.length),e={t:"readiness",display_video:!1,lanes:{}};f(p&&a?await E(a).catch(()=>e):e)}await new Promise(()=>{})}
|
|
3
3
|
export{ar,cr,Ct,At,Pt,as};
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Gn,Ao,Jt}from"./vm-hands-entry-lite-jzz73e3f.js";import{Pn,Ve,ao,Tn,Rn,On,Pr,x}from"./vm-hands-entry-lite-kz0b5h2f.js";import{kt}from"./vm-hands-entry-lite-fbhqfzbq.js";import{Ir}from"./vm-hands-entry-lite-nzmkyezg.js";import{j}from"./vm-hands-entry-lite-pf5qtbj5.js";import{a}from"./vm-hands-entry-lite-jev771b3.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as z,spawn as H}from"child_process";import{randomBytes as Qe}from"crypto";import{chmodSync as _e,existsSync as I,lstatSync as De,mkdirSync as we,readFileSync as Re,rmSync as ee,writeFileSync as U}from"fs";import{connect as de}from"net";import{join as y}from"path";var P=32,w=76;var B="./desktop-wallpaper-0pjhgyfk.jpg";var O="./dock-browser-afp005mt.png";var F="./dock-files-rywdm96b.png";var k="./dock-terminal-s41cj1jp.png";var K=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
|
|
3
|
+
# The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
|
|
4
|
+
# python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
|
|
5
|
+
# Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
|
|
6
|
+
import ctypes, sys
|
|
7
|
+
import gi
|
|
8
|
+
gi.require_version("GdkPixbuf", "2.0")
|
|
9
|
+
from gi.repository import GdkPixbuf
|
|
10
|
+
x = ctypes.cdll.LoadLibrary("libX11.so.6")
|
|
11
|
+
x.XOpenDisplay.restype = ctypes.c_void_p
|
|
12
|
+
x.XOpenDisplay.argtypes = [ctypes.c_char_p]
|
|
13
|
+
d = x.XOpenDisplay(None)
|
|
14
|
+
if not d: sys.exit("no display")
|
|
15
|
+
for name, res, args in [
|
|
16
|
+
("XDefaultScreen", ctypes.c_int, [ctypes.c_void_p]),
|
|
17
|
+
("XRootWindow", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_int]),
|
|
18
|
+
("XDisplayWidth", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
|
|
19
|
+
("XDisplayHeight", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
|
|
20
|
+
("XDefaultDepth", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
|
|
21
|
+
("XDefaultVisual", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_int]),
|
|
22
|
+
("XDefaultGC", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_int]),
|
|
23
|
+
("XCreatePixmap", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint]),
|
|
24
|
+
("XCreateImage", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint, ctypes.c_uint, ctypes.c_int, ctypes.c_int]),
|
|
25
|
+
("XPutImage", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint]),
|
|
26
|
+
("XInternAtom", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]),
|
|
27
|
+
("XChangeProperty", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]),
|
|
28
|
+
("XSetWindowBackgroundPixmap", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong]),
|
|
29
|
+
("XClearWindow", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong]),
|
|
30
|
+
("XSetCloseDownMode", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
|
|
31
|
+
("XCloseDisplay", ctypes.c_int, [ctypes.c_void_p]),
|
|
32
|
+
]:
|
|
33
|
+
f = getattr(x, name); f.restype = res; f.argtypes = args
|
|
34
|
+
s = x.XDefaultScreen(d); root = x.XRootWindow(d, s)
|
|
35
|
+
w, h = x.XDisplayWidth(d, s), x.XDisplayHeight(d, s)
|
|
36
|
+
if x.XDefaultDepth(d, s) != 24: sys.exit("unsupported depth")
|
|
37
|
+
# Scale to cover the screen, then crop the centre.
|
|
38
|
+
src = GdkPixbuf.Pixbuf.new_from_file(sys.argv[1])
|
|
39
|
+
k = max(w / src.get_width(), h / src.get_height())
|
|
40
|
+
sw, sh = max(w, round(src.get_width() * k)), max(h, round(src.get_height() * k))
|
|
41
|
+
pb = src.scale_simple(sw, sh, GdkPixbuf.InterpType.BILINEAR).new_subpixbuf((sw - w) // 2, (sh - h) // 2, w, h).copy()
|
|
42
|
+
if pb.get_has_alpha(): pb = pb.composite_color_simple(w, h, GdkPixbuf.InterpType.NEAREST, 255, 1, 0, 0)
|
|
43
|
+
rgb, stride = pb.get_pixels(), pb.get_rowstride()
|
|
44
|
+
bgrx = bytearray(w * h * 4)
|
|
45
|
+
for y in range(h):
|
|
46
|
+
row = rgb[y * stride:y * stride + w * 3]; o = y * w * 4
|
|
47
|
+
bgrx[o:o + w * 4:4] = row[2::3]; bgrx[o + 1:o + w * 4:4] = row[1::3]; bgrx[o + 2:o + w * 4:4] = row[0::3]
|
|
48
|
+
buf = ctypes.create_string_buffer(bytes(bgrx), len(bgrx))
|
|
49
|
+
pix = x.XCreatePixmap(d, root, w, h, 24)
|
|
50
|
+
img = x.XCreateImage(d, x.XDefaultVisual(d, s), 24, 2, 0, buf, w, h, 32, 0) # ZPixmap
|
|
51
|
+
x.XPutImage(d, pix, x.XDefaultGC(d, s), img, 0, 0, 0, 0, w, h)
|
|
52
|
+
ref = ctypes.c_ulong(pix)
|
|
53
|
+
for atom in (b"_XROOTPMAP_ID", b"ESETROOT_PMAP_ID"):
|
|
54
|
+
x.XChangeProperty(d, root, x.XInternAtom(d, atom, 0), 20, 32, 0, ctypes.byref(ref), 1) # XA_PIXMAP, PropModeReplace
|
|
55
|
+
x.XSetWindowBackgroundPixmap(d, root, pix)
|
|
56
|
+
x.XClearWindow(d, root)
|
|
57
|
+
x.XSetCloseDownMode(d, 1) # RetainPermanent: the pixmap outlives this process
|
|
58
|
+
x.XCloseDisplay(d)
|
|
59
|
+
`;function ye(e){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
60
|
+
<openbox_config xmlns="http://openbox.org/3.4/rc">
|
|
61
|
+
<theme><keepBorder>no</keepBorder></theme>
|
|
62
|
+
<applications>
|
|
63
|
+
<!-- Debian Chromium is "Chromium"; Chrome for Testing is "Chromium-browser". -->
|
|
64
|
+
<application class="Chromium*">
|
|
65
|
+
<decor>no</decor>
|
|
66
|
+
<position force="yes"><x>${P}</x><y>${P}</y></position>
|
|
67
|
+
<size><width>${e.width-P*2}</width><height>${e.height-P-w}</height></size>
|
|
68
|
+
</application>
|
|
69
|
+
</applications>
|
|
70
|
+
</openbox_config>`}var le=`# Remote sandbox dock \u2014 launcher icons only, centred, no panel fill
|
|
71
|
+
panel_items = L
|
|
72
|
+
panel_size = 100% 46
|
|
73
|
+
panel_margin = 0 10
|
|
74
|
+
panel_padding = 0 0 10
|
|
75
|
+
panel_position = bottom center horizontal
|
|
76
|
+
panel_shrink = 1
|
|
77
|
+
panel_background_id = 0
|
|
78
|
+
panel_layer = top
|
|
79
|
+
mouse_effects = 1
|
|
80
|
+
mouse_hover_icon_asb = 100 0 12
|
|
81
|
+
mouse_pressed_icon_asb = 100 0 -12
|
|
82
|
+
|
|
83
|
+
launcher_icon_size = 46
|
|
84
|
+
launcher_padding = 0 0 10
|
|
85
|
+
launcher_background_id = 0
|
|
86
|
+
launcher_tooltip = 1
|
|
87
|
+
|
|
88
|
+
launcher_item_app = /tmp/ara-chromium.desktop
|
|
89
|
+
launcher_item_app = /tmp/ara-terminal.desktop
|
|
90
|
+
launcher_item_app = /tmp/ara-files.desktop
|
|
91
|
+
`,ue=`corner-radius = 12;
|
|
92
|
+
rounded-corners-exclude = [
|
|
93
|
+
"class_g = 'tint2'",
|
|
94
|
+
"window_type = 'dock'",
|
|
95
|
+
"window_type = 'desktop'"
|
|
96
|
+
];
|
|
97
|
+
backend = "xrender";
|
|
98
|
+
shadow = false;
|
|
99
|
+
fading = false;
|
|
100
|
+
vsync = false;
|
|
101
|
+
inactive-opacity = 1.0;
|
|
102
|
+
active-opacity = 1.0;
|
|
103
|
+
`,Pe="/tmp/ara-dock-browser.png",Se=`[Desktop Entry]
|
|
104
|
+
Name=Chrome
|
|
105
|
+
Exec=chromium --no-sandbox %U
|
|
106
|
+
Icon=${Pe}
|
|
107
|
+
Type=Application
|
|
108
|
+
Categories=Network;WebBrowser;
|
|
109
|
+
`,Xe=`[Desktop Entry]
|
|
110
|
+
Name=Terminal
|
|
111
|
+
Exec=bash -c "DISPLAY=:99 xterm -fa DejaVuSansMono -fs 11 -bg black -fg white"
|
|
112
|
+
Icon=/tmp/ara-dock-terminal.png
|
|
113
|
+
Type=Application
|
|
114
|
+
Categories=System;TerminalEmulator;
|
|
115
|
+
`,fe=`[Desktop Entry]
|
|
116
|
+
Name=Files
|
|
117
|
+
Exec=bash -c "DISPLAY=:99 pcmanfm --no-desktop"
|
|
118
|
+
Icon=/tmp/ara-dock-files.png
|
|
119
|
+
Type=Application
|
|
120
|
+
Categories=System;FileManager;
|
|
121
|
+
`;var V={"wallpaper.jpg":B,"dock-browser.png":O,"dock-terminal.png":k,"dock-files.png":F},Te=K,he='set_wallpaper() { if command -v feh >/dev/null 2>&1; then feh --bg-fill "$1"; else python3 "$2" "$1"; fi; }';function v(e){let s=(i)=>i.replaceAll("DISPLAY=:99",`DISPLAY=${e.display}`).replaceAll("/tmp/ara-",`${e.root}/ara-`),p=new Set(e.absent??[]),n=le.split(`
|
|
122
|
+
`).filter((i)=>!(p.has("terminal")&&i.endsWith("/ara-terminal.desktop"))&&!(p.has("files")&&i.endsWith("/ara-files.desktop"))).join(`
|
|
123
|
+
`),t={"openbox/rc.xml":ye(e.screen),"tint2/tint2rc":s(n),"picom/picom.conf":ue,...p.has("terminal")?{}:{"ara-terminal.desktop":s(Xe)},...p.has("files")?{}:{"ara-files.desktop":s(fe)},"ara-chromium.desktop":s(Se).replace("chromium --no-sandbox %U",e.browserExec),"ara-set-root-wallpaper.py":Te},o=[...R.slice(0,3),he,'[ ! -f "$ROOT/ara-wallpaper.jpg" ] || set_wallpaper "$ROOT/ara-wallpaper.jpg" "$ROOT/ara-set-root-wallpaper.py" || true',...R.slice(3)];return{files:t,start:o}}var R=['ticks() { line=$(cat "/proc/$1/stat" 2>/dev/null) || return 1; rest=${line##*) }; case $rest in Z*|X*) return 1;; esac; printf "%s" "$rest" | cut -d " " -f20; }','alive() { [ -f "$ROOT/$1.pid" ] || return 1; read -r pid start <"$ROOT/$1.pid"; current=$(ticks "$pid") || return 1; [ "$current" = "$start" ] && kill -0 "$pid" 2>/dev/null; }','launch() { name=$1; shift; "$@" 9>&- >"$ROOT/$name.log" 2>&1 & pid=$!; start=$(ticks "$pid"); printf "%s %s\\n" "$pid" "$start" >"$ROOT/$name.pid"; }','if [ -f "$ROOT/tint2/tint2rc" ] && ! alive tint2 && command -v tint2 >/dev/null 2>&1; then launch tint2 tint2 -c "$ROOT/tint2/tint2rc"; fi','if [ -f "$ROOT/picom/picom.conf" ] && ! alive picom && command -v picom >/dev/null 2>&1; then launch picom picom --config "$ROOT/picom/picom.conf"; fi'];var Ae=43200000,_=":99",Ee=60000,D=15000,J={width:1280,height:800},Ne=/^[A-Za-z0-9._:-]{1,160}$/;function Le(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}var Je=["video","viewer","viewer_same_network","viewer_network"];function Ce(e,s=Date.now()){let p=["relay_url","session_id","expires_at"];if(!Le(e)||p.some((c)=>!(c in e))||Object.keys(e).some((c)=>!p.includes(c)&&!Je.includes(c)))throw new r("invalid_display_request","Reason desktop request is malformed.");let n="video"in e?Ao(e.video):void 0,t="viewer"in e?Gn(e.viewer):null;if(n===null)throw new r("invalid_display_request","Reason desktop video request is invalid.");let o=null;try{o=typeof e.relay_url==="string"?new URL(e.relay_url):null}catch{}if(!o||o.protocol!=="wss:"&&o.protocol!=="ws:"||o.username||o.password)throw new r("invalid_display_request","Reason desktop relay URL is invalid.");if(typeof e.session_id!=="string"||!Ne.test(e.session_id))throw new r("invalid_display_request","Reason desktop session identity is invalid.");let i=typeof e.expires_at==="string"?Date.parse(e.expires_at):Number.NaN;if(!Number.isFinite(i)||i<=s)throw new r("invalid_display_request","Reason desktop session has already expired.");return{relay_url:e.relay_url,session_id:e.session_id,expires_at:new Date(Math.min(i,s+Ae)).toISOString(),...n?{video:n}:{},...t?{viewer:t}:{},...n&&e.viewer_same_network===!0?{viewer_same_network:!0}:{}}}function $t(e=process.platform){return(e==="linux"||e==="darwin"||e==="win32")&&x()?.features.display===!0}async function Ls(){if(process.platform==="win32")return $t()&&await Pr();if(process.platform!=="darwin")return $t();return await Pr()}function G(e){we(e,{recursive:!0,mode:448});let s=De(e);if(!s.isDirectory()||s.isSymbolicLink()||process.getuid&&s.uid!==process.getuid())throw new r("display_unavailable","Reason desktop state directory is not private.");_e(e,448)}function Ue(e,s){let p=(t)=>{let o=Buffer.alloc(2);return o.writeUInt16BE(t.length),Buffer.concat([o,t])},n=Buffer.from([255,255]);return Buffer.concat([n,p(Buffer.alloc(0)),p(Buffer.from(e)),p(Buffer.from("MIT-MAGIC-COOKIE-1")),p(s)])}function f(e,s,p=2000){return new Promise((n)=>{let t=de(e),o="",i=(c)=>{t.destroy(),n(c)};t.setTimeout(p,()=>i(!1)),t.once("error",()=>i(!1)),t.once("close",()=>i(!1)),t.once("connect",()=>{if(!s)i(!0)}),t.on("data",(c)=>{if(o+=c.toString("latin1"),o.length>=4)i(o.startsWith("RFB "))})})}async function g(e,s){let p=Date.now()+s;while(Date.now()<p){if(await e())return!0;await new Promise((n)=>setTimeout(n,100))}return!1}function d(e,s,p){return new Promise((n)=>{let t=H(e,s,{detached:!0,stdio:"ignore",env:p});t.once("error",()=>n(-1)),t.once("exit",(o)=>n(o)),t.unref(),setTimeout(()=>n(null),D).unref()})}var C=null;function qe(e=a()){return C??=ge(e).finally(()=>{C=null}),C}async function ge(e){let s=x({home:e});if(!s?.xvfb||!s.x11vnc||!s.openbox)throw new r("display_unavailable","Run `reason desktop install` on this machine to enable its desktop.");kt({root:s.root,automation:s.automation,extensionDir:s.extensionDir});let p=y(s.root,"display");G(p);let n=await Me(e,p,s.x11vnc);if(n)return n;let t={display:_,xauthority:y(p,"Xauthority"),rfbSocket:y(p,"rfb.sock")},o=y(p,"pulse"),i=(async()=>{try{G(o)}catch{return null}return await ao(o,s.pulseaudio)})();G(y(p,"home"));let c=re(p,t,s.pulseaudio),T=async()=>({...t,sound:await i});if(await f({path:t.rfbSocket},!0))return pe(y(p,"theme"),R,c),await T();if(!I(t.xauthority))U(t.xauthority,Ue(_.slice(1),Qe(16)),{mode:384,flag:"wx"});let l=te(y(p,"theme"),t.display,J),S={path:`/tmp/.X11-unix/X${_.slice(1)}`};if(!await f(S,!1)){let u=`${J.width}x${J.height}`;if(s.xvnc)ee(t.rfbSocket,{force:!0}),d(s.xvnc,[t.display,"-geometry",u,"-depth","24","-nolisten","tcp","-auth",t.xauthority,"-rfbport","-1","-rfbunixpath",t.rfbSocket,"-SecurityTypes","None","-AlwaysShared","-desktop","Reason"],c);else d(s.xvfb,[t.display,"-screen","0",`${u}x24`,"-nolisten","tcp","-auth",t.xauthority],c);if(!await g(()=>f(S,!1),D)||s.xvnc&&!await g(()=>f({path:t.rfbSocket},!0),D))throw new r("display_unavailable","Reason could not start the virtual display.");d(s.openbox,["--config-file",l.openboxConfig],c)}if(await ne(l,c),!await se(s.x11vnc,t,p,"x11vnc.log",c))throw new r("display_unavailable","Reason could not start the desktop server.");return await T()}function re(e,s,p){let n={HOME:y(e,"home"),PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:s.display,XAUTHORITY:s.xauthority};if(p)n.PULSE_SERVER=Ve(Pn(y(e,"pulse")));return n}async function se(e,s,p,n,t){if(await f({path:s.rfbSocket},!0))return!0;ee(s.rfbSocket,{force:!0});let o=await d(e,["-display",s.display,"-auth",s.xauthority,"-rfbport","0","-rfbportv6","-1","-unixsock",s.rfbSocket,"-nopw","-forever","-shared","-noxdamage","-sb","0","-rfbversion","3.7","-quiet","-bg","-o",y(p,n)],t);if(o!==null&&o!==0)return!1;return await g(()=>f({path:s.rfbSocket},!0),D)}async function me(){let e=["DISPLAY","XAUTHORITY","WAYLAND_DISPLAY","XDG_SESSION_TYPE"],s=(p)=>Object.fromEntries(e.flatMap((n)=>p[n]?[[n,p[n]]]:[]));if(process.env.DISPLAY)return s(process.env);try{let p=await new Promise((n,t)=>z("systemctl",["--user","show-environment"],{encoding:"utf8",timeout:2000},(o,i)=>o?t(o):n(i)));return s(Object.fromEntries(p.split(`
|
|
124
|
+
`).flatMap((n)=>{let t=n.indexOf("=");return t>0?[[n.slice(0,t),n.slice(t+1)]]:[]})))}catch{return{}}}var Z=new Set;async function Me(e,s,p){let n=await me(),t=/^:(\d+)(?:\.\d+)?$/.exec(n.DISPLAY??"")?.[1];if(!t||`:${t}`===_||n.WAYLAND_DISPLAY||n.XDG_SESSION_TYPE==="wayland")return null;let o={display:`:${t}`,xauthority:n.XAUTHORITY??y(e,".Xauthority"),rfbSocket:y(s,`rfb-${t}.sock`)},i=`${o.display} ${o.xauthority}`;if(Z.has(i)||!await f({path:`/tmp/.X11-unix/X${t}`},!1))return null;let c={HOME:e,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:o.display,XAUTHORITY:o.xauthority};if(await se(p,o,s,`x11vnc-${t}.log`,c))return{...o,sound:null};return Z.add(i),process.stderr.write(`Reason worker: your screen ${o.display} could not be served; using the virtual desktop
|
|
125
|
+
`),null}function te(e,s,p){let n=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,t=[["terminal","xterm"],["files","pcmanfm"]].filter(([,i])=>!I(`/usr/bin/${i}`)).map(([i])=>i),o=v({root:e,display:s,screen:p,browserExec:n,absent:t});for(let i of["","openbox","tint2","picom"])G(y(e,i));for(let[i,c]of Object.entries(o.files))U(y(e,i),c,{mode:384});for(let[i,c]of Object.entries(V))U(y(e,`ara-${i}`),Re(c),{mode:384});return{root:e,openboxConfig:y(e,"openbox","rc.xml"),start:o.start}}function ne(e,s){return pe(e.root,[...e.start,"openbox --reconfigure >/dev/null 2>&1 || true"],s)}function pe(e,s,p){let n=[`ROOT=${JSON.stringify(e)}`,...s].join(`
|
|
126
|
+
`);return new Promise((t)=>{let o=H("/bin/sh",["-c",n],{stdio:"ignore",env:{...p,PATH:"/usr/bin:/bin"}}),i=setTimeout(()=>{o.kill(),t()},D);o.once("error",()=>{clearTimeout(i),t()}),o.once("exit",()=>{clearTimeout(i),t()})})}var We=2073600,je=320;function Be(e,s){let p=Math.min(1,Math.sqrt(We/(e.width*e.height))),n=(t,o)=>Math.min(Math.floor(o/8)*8,Math.max(je,Math.round(t*p/8)*8));return{width:n(e.width,s.width),height:n(e.height,s.height)}}function oe(e,s,p){return new Promise((n)=>z(e,s,{env:p,encoding:"utf8",timeout:5000},(t,o)=>n(t?null:o)))}function Oe(e){let s=/current (\d+) x (\d+), maximum (\d+) x (\d+)/.exec(e),p=e.split(`
|
|
127
|
+
`),n=p.findIndex((o)=>/^\S+ connected/.test(o));if(!s||n<0)return null;let t=[];for(let o of p.slice(n+1)){let i=/^\s+(\d+x\d+)\s/.exec(o);if(!i)break;t.push(i[1])}return{current:{width:Number(s[1]),height:Number(s[2])},maximum:{width:Number(s[3]),height:Number(s[4])},output:p[n].split(" ")[0],modes:t}}async function Fe(e,s,p){if(e.display!==_)return null;let n={PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority},t=(T)=>oe("xrandr",T,n),o=Oe(await t(["--query"])??"");if(!o||o.maximum.width<=o.current.width&&o.maximum.height<=o.current.height)return null;let i=Be(s,o.maximum);if(i.width===o.current.width&&i.height===o.current.height)return{size:i,changed:!1};let c=`${i.width}x${i.height}`;if(!o.modes.includes(c)){if(await t(["--newmode",c,"60",...[i.width,i.width,i.width,i.width,i.height,i.height,i.height,i.height].map(String)]),await t(["--addmode",o.output,c])===null)return null}return p(),await t(["--output",o.output,"--mode",c])===null?null:{size:i,changed:!0}}async function ke(e,s){let p=x({home:a()});if(!p)return;let n=y(p.root,"display"),t=re(n,e,p.pulseaudio);await ne(te(y(n,"theme"),e.display,s),t);let o=s.width-P*2,i=s.height-P-w;await oe("xdotool",["search","--onlyvisible","--class","Chromium","windowsize","%@",String(o),String(i),"windowmove","%@",String(P),String(P)],{...t,PATH:"/usr/bin:/bin"})}var Y=Promise.resolve();function Ge(e,s,p=()=>{}){let n=Y.then(()=>Fe(e,s,p));return Y=n.then((t)=>t?.changed?ke(e,t.size):void 0).catch(()=>{}),n.then((t)=>t?.size??null,()=>null)}async function Bt(e,s={}){let p=s.now??Date.now,n=Ce(e.payload,p());if(e.signal.throwIfAborted(),!n.video)throw new r("display_video_required","Reason desktops stream as video now; this request came without it.");let t=s.platform??process.platform;if(t!=="linux"&&t!=="darwin"&&t!=="win32")throw new r("display_video_unsupported","This machine does not serve desktop video.");let o=n.video,i=(s.video?.desktop??(t==="darwin"?async()=>Tn:t==="win32"?async()=>Rn:qe))();return await Ke(e.signal,n,s,p,(c)=>On(c,{request:o,desktop:i,...n.viewer?{viewer:n.viewer}:{},viewerSameNetwork:n.viewer_same_network===!0},{resizeDesktop:Ge,...s.video}),(c)=>Jt({type:"error",code:c}))}function Ke(e,s,p,n,t,o){let i=n();return new Promise((c,T)=>{let l=null,S=!1,u=!1,m,A,h,M=!1,q=null,X=(b)=>{if(u)return;if(q)b=q;u=!0,clearTimeout(m),clearTimeout(A),e.removeEventListener("abort",N),h?.close();try{l?.close(1000,"display_session_over")}catch{}if("error"in b){T(b.error);return}c({reason:b.reason,...h?.summary(),duration_ms:Math.max(0,n()-i)})},E=()=>X({error:new r("display_relay_unavailable","Reason could not reach the desktop relay.")}),N=()=>{let b=e.reason;X({error:b instanceof r?b:new r("cancelled","Reason closed the desktop session.")})},W=()=>{if(!q||!l)return;let b=q.error;try{l.send(o(b instanceof r?b.code:"display_unavailable"))}catch{}X(q)};if(h=t({get done(){return u||q!==null},get open(){return S&&!u&&q===null},get bufferedAmount(){return l?.bufferedAmount??0},send(b){if(u||q||!S||!l)return;try{l.send(b)}catch{X({reason:"relay_closed"})}},end:(b)=>{if(u||q)return;if(!("error"in b)){X(b);return}if(q=b,M&&S)W()}}),u){h.close();return}if(e.aborted){N();return}e.addEventListener("abort",N,{once:!0}),m=setTimeout(()=>X({reason:"session_expired"}),Math.max(1,Date.parse(s.expires_at)-n())),A=setTimeout(()=>X({reason:"viewer_absent"}),p.viewerWaitMs??Ee);try{l=(p.connect??Ir)(s.relay_url,(p.loadProxy??j)()?.url)}catch{E();return}l.binaryType="arraybuffer",l.onopen=()=>{if(u||!l)return;S=!0,h?.opened()},l.onmessage=(b)=>{if(u)return;let Q=b.data,L=Q instanceof ArrayBuffer?new Uint8Array(Q):ArrayBuffer.isView(Q)?new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength):null;if(!L||L.byteLength===0)return;if(clearTimeout(A),M=!0,q){W();return}h?.received(L)},l.onclose=()=>{if(u)return;if(!S){E();return}X({reason:"relay_closed"})},l.onerror=()=>{if(u||S)return;E()}})}
|
|
128
|
+
export{$t,Ls,G,qe,Bt};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ye,mt}from"./vm-hands-entry-lite-jzz73e3f.js";import{_t}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ye,mt}from"./vm-hands-entry-lite-jzz73e3f.js";import{_t}from"./vm-hands-entry-lite-1pabvq5q.js";import{Po,le,Xr,gt,To}from"./vm-hands-entry-lite-2e15739v.js";import{E}from"./vm-hands-entry-lite-dk79tnax.js";import{a,tr}from"./vm-hands-entry-lite-jev771b3.js";import{spawnSync as H}from"child_process";import{dirname as w}from"path";import{spawn as A}from"child_process";import{accessSync as _,constants as v}from"fs";import{basename as C,join as O}from"path";var l=null;function S(e){if(l===e)l=null;if(e.exitCode===null&&e.signalCode===null)e.kill("SIGTERM")}var Jr=(e,t)=>{if(l)S(l);let s=O(e,Po);try{_(s,v.X_OK)}catch{return()=>{}}let n;try{n=A(s,["--app",e,"--name",C(e,".app"),"--permission",t==="screen"?"screen_recording":"accessibility"],{detached:!0,stdio:"ignore"})}catch{return()=>{}}return n.on("error",()=>{if(l===n)l=null}),n.once("exit",()=>{if(l===n)l=null}),n.unref(),l=n,()=>S(n)};import{chmodSync as ne,existsSync as se,mkdirSync as re,readFileSync as D,realpathSync as ie,renameSync as oe,statSync as j,writeFileSync as ae}from"fs";import{dirname as de,isAbsolute as G,join as N,resolve as T,sep as b}from"path";function F(e=a()){return N(tr(e),"reason","protected-path-grants.json")}var f=null;function L(e){let t=JSON.parse(e);if(!Array.isArray(t?.grants))return[];return t.grants.flatMap((s)=>{let n=s;return n&&typeof n.path==="string"&&G(n.path)&&(n.kind==="file"||n.kind==="folder")&&typeof n.grantedAt==="number"?[{path:n.path,kind:n.kind,grantedAt:n.grantedAt}]:[]})}function y(e=F()){try{let{mtimeMs:t}=j(e);if(f&&f.file===e&&f.mtimeMs===t)return f.grants;let s=L(D(e,"utf8"));return f={file:e,mtimeMs:t,grants:s},s}catch{return[]}}function W(e,t){return e.kind==="file"?t===e.path:t===e.path||t.startsWith(`${e.path}${b}`)}function U(e,t){let s=T(e);return y(t).some((n)=>W(n,s))}function yo(e,t){return E(e)&&!U(e,t)}function wo(e,t,s){let n=t?"file-read* file-write*":"file-read*";return y(s).filter((r)=>r.path===e||r.path.startsWith(`${e}${b}`)).map((r)=>`(allow ${n} (${r.kind==="file"?"literal":"subpath"} ${JSON.stringify(r.path)}))`)}var P="x-apple.systempreferences:com.apple.preference.security",J="curl -fsSL https://reasonmachines.com/install.sh | bash",q=180000,B=2000;var k={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${P}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${P}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${P}?Privacy_AllFiles`}};function R(e){return e.executable}function K(e,t){if(e==="computer_use_identity_missing")return`Reason's background identity is not installed (${e}); reinstall Reason: ${J}`;if(e==="computer_use_identity_outdated")return`Reason's background identity is outdated (${Xr(t)??"unknown"}; this CLI is ${_t}) (${e}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${e}); run the installed \`reason\``}function Qo(e=a()){let t=gt(e);if(t.length>0)return{state:"ready",path:w(w(w(t[0]))),prefix:t};let s=To(t,e)??"computer_use_identity_unavailable";return{state:s,path:le(e),detail:K(s,e)}}function V(){return{identity:()=>Qo(),grants:(e)=>Ye(e),request:(e,t)=>mt(e,t),worker:async()=>(await import("./status-4pmpra54.js")).connectionMacState(),open:(e)=>{H("/usr/bin/open",e,{stdio:"ignore",timeout:1e4})},tile:Jr,restartConnection:async()=>(await import("./connect-cli-qtbe4v66.js")).restartConnection(),sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now()}}function M(e,t,s){if(e.state!=="ready"||!t)return"unknown";return t[s]?"granted":"missing"}async function es(e){let t=e.identity(),s=t.state==="ready"?await e.grants(t.prefix):null,n=await e.worker(),r=n?R(n):null,i=!r||n?.full_disk_access==="unknown"?"unknown":n?.full_disk_access==="granted"?"granted":"missing",c=(u,d,o)=>{let{label:p,purpose:h,level:m}=k[u];return{id:u,label:p,purpose:h,level:m,state:d,holder:o}};return{identity:{state:t.state,path:t.path,detail:t.state==="ready"?null:t.detail},worker_detail:r?null:"Full Disk Access is read from this computer's running worker; `reason connect` starts it.",permissions:[c("screen",M(t,s,"screen"),t.path),c("accessibility",M(t,s,"accessibility"),t.path),c("disk",i,r)]}}function zs(e){let t=e.identity.state==="ready"?null:e.identity.state,s=e.permissions.filter((i)=>i.state==="granted").length,n=[...t?[t]:[],...e.permissions.filter((i)=>i.state!=="granted"&&!(t&&i.id!=="disk")).map((i)=>`${i.label} ${i.state}`)],r=!t&&e.permissions.some((i)=>i.state==="missing");return`Permissions: ${s} of ${e.permissions.length}${n.length>0?` (${n.join(", ")})`:""}`+(r?" \u2014 reason permissions allow":n.length>0?" \u2014 reason permissions":"")}async function x(e,t){let s=t.now()+q;for(;;){if(await e())return!0;if(t.now()>=s)return!1;await t.sleep(B)}}async function qs(e,t){let s=t.host??V(),{io:n}=t,r=await es(s),i=r.permissions.filter((o)=>e.includes(o.id)&&o.state!=="granted");if(i.length===0)return n.stdout.write(`Reason permissions: ${e.map((o)=>k[o].label).join(", ")} already allowed.
|
|
3
3
|
`),0;let c=!1,u=!1,d=s.identity();for(let o of i){let{label:p,pane:h}=k[o.id];if(o.id!=="disk"){if(d.state!=="ready"){if(!c)n.stderr.write(`Reason permissions: ${d.detail}
|
|
4
4
|
`);c=!0;continue}let g=o.id;await s.request(d.prefix,g),s.open([h]);let I=s.tile(d.path,g);if(n.stdout.write(`Allow Reason in System Settings > Privacy & Security > ${p}.
|
|
5
5
|
`),!t.wait)continue;if(n.stdout.write(`Waiting for it (Ctrl-C to stop)\u2026
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{We,so,F,Ve,Ft,Tr,x}from"./vm-hands-entry-lite-
|
|
2
|
+
import{We,so,F,Ve,Ft,Tr,x}from"./vm-hands-entry-lite-kz0b5h2f.js";import{K}from"./vm-hands-entry-lite-hk6trmwa.js";import{mt}from"./vm-hands-entry-lite-jzz73e3f.js";import{gt}from"./vm-hands-entry-lite-2e15739v.js";import{Jr}from"./vm-hands-entry-lite-dzv12jpj.js";import{kt,Di}from"./vm-hands-entry-lite-fbhqfzbq.js";import{G,qe}from"./vm-hands-entry-lite-dht2p1vj.js";import{Ee,Hn}from"./vm-hands-entry-lite-1qpwpdcc.js";import{St}from"./vm-hands-entry-lite-4vks5phw.js";import{a}from"./vm-hands-entry-lite-jev771b3.js";import{C}from"./vm-hands-entry-lite-6c67a3jc.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{spawn as R,spawnSync as tt}from"child_process";import{createHash as ot,randomUUID as me}from"crypto";import{closeSync as rt,copyFileSync as se,existsSync as M,fstatSync as nt,mkdirSync as ie,openSync as st,readdirSync as U,readFileSync as X,readlinkSync as it,renameSync as fe,rmSync as at,statSync as ct,writeFileSync as lt}from"fs";import{connect as ut}from"net";import{tmpdir as L,userInfo as ge}from"os";import{basename as ae,delimiter as dt,dirname as B,join as f}from"path";var z=`import { spawn, execFileSync } from "node:child_process";
|
|
3
3
|
import { createHash, randomUUID } from "node:crypto";
|
|
4
4
|
import { readFileSync, readlinkSync, lstatSync, realpathSync, statSync, mkdtempSync, mkdirSync, chmodSync, writeFileSync, readdirSync, rmSync, openSync, readSync, closeSync, renameSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{S,Jt,Kn,Ye,Jn,Zn}from"./vm-hands-entry-lite-jzz73e3f.js";import{Yn}from"./vm-hands-entry-lite-
|
|
2
|
+
import{S,Jt,Kn,Ye,Jn,Zn}from"./vm-hands-entry-lite-jzz73e3f.js";import{Yn}from"./vm-hands-entry-lite-2e15739v.js";import{Un}from"./vm-hands-entry-lite-hk6trmwa.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as ys,spawn as Xe}from"child_process";import{existsSync as ws}from"fs";import{connect as xs}from"net";function pn(){let e=new Set,t=null,n=(s)=>({holder:t?.viewer??null,you:t===s,same_user:Boolean(t?.viewer&&s.viewer&&t.viewer.user_id===s.viewer.user_id)}),o=()=>{for(let s of e)s.notify(n(s))};return{join(s){return e.add(s),s.notify(n(s)),()=>{if(!e.delete(s))return;if(t!==s)return;t=null,o()}},claim(s){if(t===s||!e.has(s))return;t=s,o()}}}var ut=pn();import{createHash as St}from"crypto";import{once as Sn}from"events";import{createWriteStream as vn,existsSync as mr,mkdirSync as gr,mkdtempSync as hr,readFileSync as le,readdirSync as br,renameSync as yr,realpathSync as En,rmSync as Dn,statSync as Ne,writeFileSync as wr}from"fs";import{delimiter as _r,dirname as vt,join as b}from"path";import{finished as Cn}from"stream/promises";var We="omljlfpmafedpplnpkkahegadhkimdje",so="https://chromewebstore.google.com/detail/reason/omljlfpmafedpplnpkkahegadhkimdje";var O={ocu:{repository:"https://github.com/iFurySt/open-codex-computer-use.git",revision:"386a260d1ab8b690adbbb27f7471595cf0c2b752",version:"0.3.5"},obu:{repository:"https://github.com/iFurySt/open-browser-use.git",revision:"ac015846df75928fbcf0f3a0f3ba3a210ce1a507",version:"0.1.42"}},H={version:"155.0.8059.84",macArm64Sha256:"13b9e98ce56f5ce18e100a009f455c9285f399e7c9dc8a76fdf2f3a9755bb5f2",linux64Sha256:"cf0f049892dea22e6a6db26d47ed0d7776b7158edcbec4634086633df8bafcbc",win64Sha256:"507f2a031441d10c62b5e3d4e863f09ac1198a571c1419976cbd8387f639afde"};var J={ocu:{url:`https://registry.npmjs.org/open-computer-use/-/open-computer-use-${O.ocu.version}.tgz`,sha256:"7c16a87c8cd357787b02c0ebd040dd5f93880c1fb51c1901caa2e0c05d063130",size_bytes:5844280},obu:{url:`https://registry.npmjs.org/open-browser-use/-/open-browser-use-${O.obu.version}.tgz`,sha256:"9386d8ce0a147b3f55e1807b68edf736836378807541c457c9b5f6ca2cabaa4e",size_bytes:21372018},extension:{url:`https://github.com/iFurySt/open-browser-use/releases/download/v${O.obu.version}/open-browser-use-chrome-extension-${O.obu.version}.zip`,sha256:"c9c07bec1175e12ea6985b0e7784a5ef01fd03f014b958224a1e17dcd838a241",size_bytes:31070}},F="pnbmoicbkopffjjgfgfglopechaiemkp";import{spawn as Me}from"child_process";import{createRequire as fn}from"module";import{join as mn}from"path";var gn=30000,hn=1048576;function Te(){return process.env.SystemRoot??"C:\\Windows"}function bn(){return mn(Te(),"System32","WindowsPowerShell","v1.0","powershell.exe")}var yn=String.raw`
|
|
3
3
|
$ErrorActionPreference = "Stop"
|
|
4
4
|
Add-Type -TypeDefinition @"
|
|
5
5
|
using System;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{H}from"./vm-hands-entry-lite-3krzmhkk.js";import{D,R,b}from"./vm-hands-entry-lite-beyyy1gz.js";import{je,pr,hr,gn,_n,ot}from"./vm-hands-entry-lite-
|
|
2
|
+
import{H}from"./vm-hands-entry-lite-3krzmhkk.js";import{D,R,b}from"./vm-hands-entry-lite-beyyy1gz.js";import{je,pr,hr,gn,_n,ot}from"./vm-hands-entry-lite-aapdds5x.js";import{Nr}from"./vm-hands-entry-lite-pf5qtbj5.js";import{p,at,yn,_e,we}from"./vm-hands-entry-lite-s4bharcb.js";import{v,h}from"./vm-hands-entry-lite-wx4ax7wg.js";import{a,tr,Io}from"./vm-hands-entry-lite-jev771b3.js";import{nn,y,t,k,o,d,rs,Ie,Ri,u,i,W,_,ee,s,n,on}from"./vm-hands-entry-lite-avc65bd7.js";import{se,A}from"./vm-hands-entry-lite-6c67a3jc.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{randomUUID as Q}from"crypto";import{spawn as Le}from"child_process";import{existsSync as Z,lstatSync as me,mkdirSync as We,readFileSync as Ne,realpathSync as G,rmSync as Ve,writeFileSync as He}from"fs";import{dirname as Ue,join as j,relative as qe,sep as Je}from"path";var Se=["process.run.v1","process.full.v1"],xe=600000,Pe=1800000,Ee=20000,ne="process.cancel.v1",ie=i({action:n("start"),request_id:t().uuid(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),cwd:t().min(1).max(4096).refine((e)=>!e.includes("\x00")&&!e.startsWith("/")&&!e.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:s(["host","confined"]).default("host"),timeout_ms:o().int().min(1000).max(Pe).default(xe).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),K={device_id:t().uuid(),root_id:t().uuid()},Re=_("action",[ie.extend(K),i({...K,action:n("inspect"),process_id:t().uuid(),after:o().int().min(0).default(0),wait_ms:o().int().min(0).max(Ee).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),i({...K,action:n("cancel"),process_id:t().uuid()}).strict()]),Fe=nn(Re,{io:"input"}),Ke=ie.extend({process_brain_fence:t().uuid(),process_expires_at:y.datetime()}).strict(),J=i({version:n(1),process_id:t().uuid(),state:s(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:o().int().nullable(),first_cursor:o().int().min(0),next_cursor:o().int().min(0),truncated:d(),observed_at:y.datetime(),output:u(i({cursor:o().int().min(1),stream:s(["stdout","stderr"]),text:t().max(32768)}).strict()).max(128)}).strict().refine((e)=>{if(Buffer.byteLength(JSON.stringify(e))>1e5||e.next_cursor<e.first_cursor-1)return!1;if((e.state==="starting"||e.state==="running"||e.state==="uncertain")&&e.exit_code!==null)return!1;if(e.state==="exited"&&(e.exit_code===null||e.exit_code<0||e.exit_code>255))return!1;if(e.state==="cancelled"&&e.exit_code!==130||e.state==="expired"&&e.exit_code!==124)return!1;let f=e.first_cursor-1;for(let l of e.output){if(l.cursor<=f||l.cursor>e.next_cursor)return!1;f=l.cursor}return!0});function ae(e){return Se.includes(e)}var Xe=i({operation_constraints:ee(t(),Ie())}),Ye=i({ready:n(!0),version:n(1),execution_mode:s(["host","confined"]),max_timeout_ms:o().int().min(1000).optional()});var De=i({version:n(1),process_id:t().uuid(),state:s(["queued","cancelled_before_start","not_started"]),exit_code:rs(),output:u(Ri()).length(0),first_cursor:n(0),next_cursor:n(0),truncated:n(!1),cancellation_requested:n(!1),reason_code:s(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),Ce=i({...J.shape,state:s(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:y.datetime().optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:d(),reason_code:t().nullable().optional(),execution_authority:n("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:i({cause:n("brain_generation_changed"),terminal_confirmed:d(),next_step:s(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:J.shape.state.or(n("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),$e=nn(Ce),Qe=W([J,De.refine((e)=>e.state==="cancelled_before_start")]),X=i({version:n(1),process_id:t().uuid(),state:s(["exited","cancelled","expired"]),exit_code:o().int().min(0).max(255),observed_at:y.datetime()}).strict().refine((e)=>(e.state!=="cancelled"||e.exit_code===130)&&(e.state!=="expired"||e.exit_code===124)),Ze=i({process_terminal_observation:X}).strict();var Bi="preview.serve.v1",Fi=43200000;var ce="preview.open.v1",de=1,dn="gid_proxy_v1",ji="egress",pn=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,Ae=i({version:n(dn),allowed_domains:u(t().max(260).regex(pn)).max(1024)}).strict(),ke=on((e)=>H(e)!==null,"invalid workspace"),Oe=i({version:n(1),request_id:k(),session_id:k(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),port:o().int().min(1024).max(65535),workspace:ke,egress:Ae.optional()}).strict(),Ui=Oe.extend({expires_at:y.datetime()}).strict();var Me=4,Te=5000;function Y(e,c,f){let l=null;try{l=at(e)}catch{}yn({deviceRelayUrl:l?.deviceRelayUrl??"",binding:l?.binding??null,jobId:c,port:l?.binding.port??0,reason:l?f:"binding_invalid"})}function le(e){let c=new Map;return{open(f){let l=(x)=>Y(f,e.claim.operation_id,x),C;try{C=at(f)}catch{return l("binding_invalid")}let{binding:w,deviceRelayUrl:z}=C,E=e.claim.owner;if(!E||w.organizationId!==E.organization_id||w.userId!==E.user_id||w.deviceId!==E.device_id||w.rootId!==e.claim.root_id||w.jobId!==e.claim.operation_id||w.fenceId!==e.claim.operation_id||w.generation!==de||w.expiresAtMs>Math.min(Date.now()+p.lifetimeMs+Te,e.expiresAtMs))return l("binding_mismatch");if(w.expiresAtMs<=Date.now())return l("binding_expired");if(c.get(w.port)?.abort(),c.delete(w.port),c.size>=Me)return l("preview_capacity");let L=new AbortController;c.set(w.port,L);let P=we({binding:w,deniedPorts:e.deniedPorts,readCurrentJob:async()=>{if(L.signal.aborted)return null;let x=await e.inspect();return x?{binding:w,executorLaunchId:e.executorLaunchId,job:x}:null}});_e({binding:w,deviceRelayUrl:z,port:P,signal:L.signal}).then((x)=>x.closed,(x)=>{let I=x instanceof Error?x.message:"preview_failed";if(I!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:w.jobId,port:w.port,reason_code:I})}
|
|
3
3
|
`)}).finally(()=>{if(c.get(w.port)===L)c.delete(w.port)})},dispose(){for(let f of c.values())f.abort();c.clear()}}}class nt extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var fe=256,B=new Map,he="preview.serve.v1",V=new Map;function be(e){let c=V.get(e.operation_id);if(c){if(c.claim!==e)throw M("process_authority_lost");return c}if(V.size>=fe)throw M("process_journal_capacity");let f={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return V.set(e.operation_id,f),f}function pe(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ue=(e)=>new Promise((c)=>setTimeout(c,e)),M=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function ze(e=a(),c=Ge()){let f=Ue(Nr({},e)),l=qe(tr(e),f),[C,...w]=l.split(Je);return{directory:j(c,l,"processes"),previous:[j(f,"processes"),...C==="reason"?[j(c,"ara",...w,"processes")]:[]]}}function Ge(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=Io();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function ur(e){if(!e.claim.owner||e.signal.aborted||e.expiresAtMs<=Date.now())throw M("process_authority_lost");let c=be(e.claim);if(c.executing)throw M("process_busy");if(c.executing=!0,c.cancelRequested)return c.phase="settling",pe(e.claim.operation_id);c.phase="starting";let f=e.journals??ze();We(f.directory,{recursive:!0,mode:448});let l=pr({runtimeDirectory:G(f.directory),previousRuntimeDirectories:(f.previous??[]).filter((m)=>Z(m)).map((m)=>G(m)),root:e.root,runId:JSON.stringify([e.claim.owner,e.claim.run_id,e.claim.root_id,e.claim.operation_id]),maxScopes:fe});try{for(let m of[e.root,e.cwd])if(!je(G(m),l.journalDirectory))throw new r("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(m){throw l.disposeSocket(),m}let C=me(l.journalDirectory),w=e.claim.capability===he,z=()=>B.set(e.claim.operation_id,{path:l.journalDirectory,ino:C.ino,dev:C.dev,anyCompletion:w}),E=l.launchDirectory,L=j(E,"config.json"),P={url:"",transport:"local_job_ipc",directShell:{mode:e.mode,executable:e.shell,jobId:e.claim.operation_id},workerVersion:D,protocolVersion:2,workerArtifactSha256:b,workerEntrypoint:R,targetGeneration:1,fenceId:Q(),...process.platform==="win32"?{bashExecutable:se()}:{},workRoot:e.root,workspaceAliasPath:e.root,repoPath:e.cwd,jobEnvPath:j(E,"unused.env"),replSocketPath:j(E,"unused.sock"),readyPath:j(E,"ready.json"),directTerminalReceiptPath:j(E,"terminal.json"),launchId:Q(),expiresAtMs:e.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:l.journalDirectory,scopeId:l.scopeId},jobControlSocketPath:l.socketPath,...e.prefix?{bashCommandPrefix:e.prefix}:{},...e.jobsUser?{jobsUser:e.jobsUser}:{}},x;try{He(L,JSON.stringify(P),{mode:384});let m=gn({configPath:L,root:e.cwd,grantedRoot:e.root,workRoot:e.root,temporaryDirectory:E});x=e.spawnWorker?.(L,P)??Le(m.command,m.args,{...m.options,env:e.environment,stdio:[_n,"ignore","ignore"]})}catch(m){throw l.disposeSocket(),m}let I=!1,F=new Promise((m,S)=>{x.once("exit",(g)=>{I=!0,m(g)}),x.once("error",(g)=>{I=!0,S(g)})});F.catch(()=>{});let ge={root:e.root,runId:e.claim.run_id,scopeId:l.scopeId,socketPath:l.socketPath,generation:1,fenceId:P.fenceId,executorLaunchId:P.launchId,expiresAtMs:P.expiresAtMs},N=async(m)=>{let S=await hr(ge,{type:"job",version:2,generation:1,id:Q(),jobId:e.claim.operation_id,...m==="start"?{action:m,input:{script:e.command,leaseExpiresAtMs:e.expiresAtMs}}:m==="inspect"?{action:m,input:{after:0}}:m==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:m,input:{}}},new AbortController().signal);if(!S.ok)throw M(S.error);return S.job},U=!1,q=!1,te,re=()=>{U=!0,ot(x,"SIGTERM")};e.signal.addEventListener("abort",re,{once:!0});let T,oe=0,ve=async(m)=>{let S=[...m.output],g={version:1,process_id:e.claim.operation_id,state:m.state,exit_code:m.exitCode,first_cursor:m.firstCursor,next_cursor:m.nextCursor,truncated:m.truncated,output:S,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(g))>90000&&S.length)S.shift(),g.truncated=!0,g.first_cursor=S[0]?.cursor??g.next_cursor+1;T=J.parse(g),await e.emit(T),oe=Date.now()};try{let m=Math.min(Date.now()+1e4,e.expiresAtMs);while(!Z(P.readyPath)){if(I)throw new r("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if(e.signal.aborted||Date.now()>=m)throw M("process_start_unconfirmed");await ue(25)}let S=JSON.parse(Ne(P.readyPath,"utf8"));if(S.launchId!==P.launchId||S.fenceId!==P.fenceId||S.workerArtifactSha256!==b)throw M();if(e.signal.throwIfAborted(),c.cancelRequested)return pe(e.claim.operation_id);let g;try{q=!0,g=await N("start")}catch(O){if(!(O instanceof r)||O.code!=="hands_job_result_unknown")throw O;g=await N("inspect")}if(c.phase="running",c.cancel=async()=>{await N("cancel")},w&&e.preview)c.tunnels=le({claim:e.claim,executorLaunchId:P.launchId,expiresAtMs:e.expiresAtMs,deniedPorts:e.preview.deniedPorts,inspect:async()=>c.phase==="running"&&!I?await N("probe"):null});if(c.cancelRequested)await c.cancel(),g=await N("inspect");for(;;){if(!["starting","running"].includes(g.state))c.phase="settling",c.cancel=void 0;if(!T||T.state!==g.state||T.next_cursor!==g.nextCursor&&Date.now()-oe>=5000)await ve(g);if(!["starting","running"].includes(g.state))break;if(e.signal.aborted||I)throw M();await ue(1000);try{g=await N("inspect"),te=void 0}catch(O){if(!(O instanceof r)||O.code!=="hands_job_result_unknown"||e.signal.aborted||I||Date.now()-(te??=Date.now())>120000)throw O}}if(!T||T.state==="uncertain")throw M();return T}finally{if(c.phase="settling",c.cancel=void 0,c.tunnels?.dispose(),c.tunnels=void 0,await c.cancelInFlight?.catch(()=>{}),e.signal.removeEventListener("abort",re),!I&&!U)ot(x,"SIGTERM");let m,S=await Promise.race([F.then((g)=>({code:g})),new Promise((g)=>{m=setTimeout(()=>g(null),6000)})]).finally(()=>{clearTimeout(m)});if(!S){try{ot(x,"SIGKILL")}catch{}try{await F}finally{if(I)l.disposeSocket()}throw M("process_cleanup_unconfirmed")}try{if((U||e.signal.aborted)&&S.code===0&&q){v(E);let g=JSON.parse(h(P.directTerminalReceiptPath)),O=X.safeParse(g.observation);if(Object.keys(g).length===4&&g.launch_id===P.launchId&&g.fence_id===P.fenceId&&g.scope_id===l.scopeId&&O.success&&O.data.process_id===e.claim.operation_id){if(w)z();throw new nt(O.data)}}}catch(g){if(g instanceof nt)throw g}finally{if(I)l.disposeSocket()}if(S.code!==0&&!U&&q)throw M("process_cleanup_unconfirmed");if(!U&&S.code===0&&(T&&["exited","cancelled","expired"].includes(T.state)||!q&&c.cancelRequested)||w&&S.code===0&&!q)z()}}async function Ts(e,c){if(c.kind===ce&&e.capability===he){let C=V.get(e.operation_id);if(C?.claim===e&&C.tunnels)C.tunnels.open(c.payload);else Y(c.payload,e.operation_id,"server_not_running");return!0}if(c.kind!==ne||!ae(e.capability)||!e.owner||c.payload.process_id!==e.operation_id)return!1;let f=V.get(e.operation_id);if(f&&f.claim!==e)return!1;let l=be(e);if(l.cancelRequested=!0,l.phase==="running"&&l.cancel)l.cancelInFlight??=l.cancel(),await l.cancelInFlight;return!0}function Rs(e,c){V.delete(e);let f=B.get(e);if(!f||c!=="succeeded"&&!f.anyCompletion)return B.delete(e),!1;try{let l=me(f.path);if(!l.isDirectory()||l.isSymbolicLink()||l.ino!==f.ino||l.dev!==f.dev||!A(l)||G(f.path)!==f.path||Z(j(f.path,"owner.lock")))return!1;return Ve(f.path,{recursive:!0}),B.delete(e),!0}catch{return!1}}
|
|
4
4
|
export{Bi,Fi,dn,ji,pn,Ui,nt,ur,Ts,Rs};
|