@reason-machines/cli-linux-x64 0.2.506 → 0.2.507
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/{api-credentials-09xx3z37.js → api-credentials-q302458a.js} +1 -1
- package/bin/vm-hands/{api-s4znv8fp.js → api-e589y9e0.js} +1 -1
- package/bin/vm-hands/{connect-cli-f76njmkm.js → connect-cli-zeqyjj5t.js} +1 -1
- package/bin/vm-hands/{local-automation-qbgbpftn.js → local-automation-43ry1qn6.js} +1 -1
- package/bin/vm-hands/{local-capabilities-3j6ftyf5.js → local-capabilities-e43ra579.js} +1 -1
- package/bin/vm-hands/{local-display-session-8dc6mct3.js → local-display-session-9pm9ed2m.js} +1 -1
- package/bin/vm-hands/local-display-video-xtjezayy.js +2 -0
- package/bin/vm-hands/{local-managed-process-qgj5jfnb.js → local-managed-process-d179a1aq.js} +1 -1
- package/bin/vm-hands/{managed-runtime-jwxh8gfp.js → managed-runtime-mydc95fa.js} +1 -1
- package/bin/vm-hands/{permissions-j5ggzkk4.js → permissions-g919jepr.js} +1 -1
- package/bin/vm-hands/{serve-service-2m11vpyd.js → serve-service-5twngyyg.js} +1 -1
- package/bin/vm-hands/{status-qg16wxre.js → status-4da3v86c.js} +1 -1
- package/bin/vm-hands/version-r5qbf8y9.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-nwrqwqhh.js → vm-hands-entry-lite-2cf33ark.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-69ng6mye.js → vm-hands-entry-lite-2mskbtsd.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-622t4qbv.js → vm-hands-entry-lite-3ahrysca.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-3h9rka2b.js → vm-hands-entry-lite-6a96d80a.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-b4ebg75b.js → vm-hands-entry-lite-7651j949.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-cqramfsh.js → vm-hands-entry-lite-7v1rd0sk.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-xwqrndky.js → vm-hands-entry-lite-b4q5e57n.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-r3vd5k1q.js → vm-hands-entry-lite-bnxh4ax9.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-ppzj5jgc.js → vm-hands-entry-lite-qxq147a5.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-t3a1fsnk.js → vm-hands-entry-lite-ra8c0ytm.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-xh59ch7y.js → vm-hands-entry-lite-rn2rhavz.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-t0wbspg5.js → vm-hands-entry-lite-v6yygjyx.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-23m94yra.js → vm-hands-entry-lite-v9engyp5.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-gs7j14bz.js → vm-hands-entry-lite-vrenpefs.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-nkp4ccvt.js → vm-hands-entry-lite-vtc8mjpc.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-znd9c7x0.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-bcw4gm80.js → vm-hands-executor-68r7m0z1.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-r4m9whbb.js → vm-hands-op-runner-gppbedw9.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-x79a9j7q.js → vm-hands-runtime-w2fb9gsk.js} +3 -3
- package/package.json +1 -1
- package/bin/vm-hands/local-display-video-zj8mz5vs.js +0 -2
- package/bin/vm-hands/version-96pq5c8m.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-ezbs3nn1.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Gt,j}from"./vm-hands-entry-lite-rzr2ncf5.js";import{ue,Ce,Z,Ae,de,rr,et,X,O,H,tn}from"./vm-hands-entry-lite-38g65s5x.js";import{Lo,ri}from"./vm-hands-entry-lite-nqdstx24.js";import{xo,P,Je,Se,Ze,ne,Xe,Vn,Ee,Xt,ae,U,N,ce,Hr,zr,Kn}from"./vm-hands-entry-lite-5gevvgec.js";import{Pe,oe,pe,Y,Re,q,Q}from"./vm-hands-entry-lite-5tbntcyq.js";import{It,kr,at,V,D,R,b,En}from"./vm-hands-entry-lite-77j164ps.js";import{Er,xr,vn,oo,He,Sn}from"./vm-hands-entry-lite-tebh7dcm.js";import{K}from"./vm-hands-entry-lite-ncbzy69k.js";import{Mi}from"./vm-hands-entry-lite-v9qq2cgv.js";import{p,ze,Dt,ct,so,_e,we}from"./vm-hands-entry-lite-psywfz8m.js";import{v,h,lo}from"./vm-hands-entry-lite-f69t48dj.js";import{E}from"./vm-hands-entry-lite-txd50spx.js";import{Qt}from"./vm-hands-entry-lite-xh59ch7y.js";import{a,ie,$o}from"./vm-hands-entry-lite-swrymqj9.js";import{L,Ii,Di,Ho,y,t,k,Et,o,d,u,i,c,g,ee,s,n}from"./vm-hands-entry-lite-gvjffc5t.js";import{Li}from"./vm-hands-entry-lite-mk5ayds8.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{qo,se,Wo,C,De,Me,A}from"./vm-hands-entry-lite-87vmbt38.js";var gi=()=>{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"},_={nan:"NaN"};return(w)=>{switch(w.code){case"invalid_type":{let S=_[w.expected]??w.expected,I=Ho(w.input),W=_[I]??I;return`Invalid input: expected ${S}, received ${W}`}case"invalid_value":if(w.values.length===1)return`Invalid input: expected ${Di(w.values[0])}`;return`Invalid option: expected one of ${Ii(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":""}: ${Ii(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 Rn(){return{localeError:gi()}}L(Rn());class pt extends Error{}function Ao(e){let l;try{l=new URL(e)}catch{throw new pt("The proxy must be a URL like https://proxy.example.com:3128.")}if(l.protocol!=="https:"&&l.protocol!=="http:")throw new pt("The proxy URL must use the https or http scheme.");if(!l.hostname)throw new pt("The proxy URL must name a host.");if(l.port!==""&&Number(l.port)<1)throw new pt("The proxy URL must use a port between 1 and 65535.");if(l.pathname!==""&&l.pathname!=="/"||l.search||l.hash)throw new pt("The proxy URL must not carry a path, query, or fragment.");return l.toString()}import{createHash as bi}from"crypto";import{isAbsolute as To,join as Do,relative as Co,resolve as Vt,sep as No}from"path";var Jt=t().min(1).refine(To,"absolute path required"),xn=c({version:n(1),apiOrigin:Et(),channel:s(["staging","production"]),stateDirectory:Jt,workspaceRoot:Jt,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(Gt),url:t().refine((e)=>{try{return Ao(e)===e}catch{return!1}},"invalid proxy URL"),caFile:Jt.optional()}).optional(),userChrome:d().optional(),cloudSessions:n(!0).optional(),localLogins:d().optional(),folders:u(Jt).min(1).max(31).optional()}),wi=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,B=g("channel",[xn,xn.extend({channel:n("pr"),apiOrigin:t(),prEnvironment:t()}),xn.extend({channel:n("local-qa"),apiOrigin:t()})]).superRefine((e,l)=>{if(e.channel==="local-qa"){if(!wi.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 _=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(!_||/^pr-[1-9][0-9]*$/.exec(_)?.[0]!==_||w?.[0]!==e.apiOrigin||S?.length!==1||S[0]!==_)l.addIssue({code:"custom",message:"PR worker requires explicit prEnvironment and an exact same-PR HTTPS Railway origin"})}else{let _=new URL(e.apiOrigin);if(_.origin!==e.apiOrigin||_.username||_.password||_.protocol!=="https:"&&!(_.protocol==="http:"&&ri(_.origin))||!ri(_.origin)&&!Lo(e.channel,_.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((_)=>!je(_,e.stateDirectory)))l.addIssue({code:"custom",message:"folders must be distinct and disjoint from state"})});function m(e){return Do(e.stateDirectory,`headless-${e.channel==="pr"?e.prEnvironment:e.channel}`)}function je(e,l){if(Fr(l,e))return!1;return!Fr(e,l)||E(Do(No,Co(Vt(e),Vt(l))))}function Fr(e,l){let f=Co(Vt(e),Vt(l));return f===""||f!==".."&&!f.startsWith(`..${No}`)&&!To(f)}function te(e){let{proxy:l,userChrome:f,cloudSessions:_,localLogins:w,folders:S,...I}=e;return bi("sha256").update(JSON.stringify(I)).digest("hex")}var yi=4,vi=[2375,2376,9222,9229];function pr(e){let l=new Set(vi);for(let f of e){let _=new URL(f);l.add(Number(_.port||(["https:","wss:"].includes(_.protocol)?443:80)))}return l}function Gr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var ki=60000;function Bo(e){let l=new AbortController,f=new Map,_=(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)Gr()}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())>ki)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(),ve=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},Oe=re?T:be;if(G.aborted||!fe)return null;if(fe.generation!==F.generation||fe.fenceId!==F.fenceId||ve?.snapshot_id!==J?.snapshot_id||ve?.revision!==J?.revision)return"moved";let $e=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||!Oe||!$e)return null;if(($e.snapshotId!==Oe.snapshotId||$e.revision!==Oe.revision)&&(re||!e.environment.carried($e.snapshotId,$e.revision)))return null;if(!T&&F.generation===x.generation&&F.fenceId===x.fenceId)M.opened={...Oe,...$e};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:Oe.attachmentRevision,grantRevision:Oe.grantRevision,generation:Oe.generation,fenceId:Oe.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}=ct(x);if(G.aborted||F.expiresAtMs<=Date.now()||F.expiresAtMs>Date.now()+p.lifetimeMs||new URL(T).origin!==e.authority.relayOrigin)Gr();let re=_(F),J=f.get(re);if(J){if(!ze(J.binding,F)||J.relay!==T)Gr();if(await J.opened,!await Dt(()=>J.port.check())||G.aborted||J.abort.signal.aborted)Gr();return{opened:!0,binding:F}}if(f.size>=yi)Gr();let z=new AbortController,fe={},ve=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 Oe=_e({binding:F,deviceRelayUrl:T,port:ve,signal:z.signal}),$e={binding:F,relay:T,abort:z,port:ve,opened:Oe};f.set(re,$e);let qe=()=>{if(G.removeEventListener("abort",be),l.signal.removeEventListener("abort",be),f.get(re)===$e)f.delete(re)};try{if((await Oe).closed.then(qe),G.removeEventListener("abort",be),w(M),z.signal.aborted||!await Dt(()=>ve.check()))Gr();return{opened:!0,binding:F}}catch{z.abort(),qe(),Gr()}},async close(x,M){w(M);let{binding:G}=so(x),F=f.get(_(G));if(!F||!ze(F.binding,G))Gr();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 Pn}from"ws";var jo=(e)=>("data"in e)?e.data.length:e.bytes,Mo=2*Xe;function ir(e){throw new r(e,"The bound Hands terminal is unavailable or its outcome is unconfirmed.")}var _t=(e)=>!["starting","running"].includes(e.state);function Ji(e,l,f=Date.now()){let _=["relay_url","session_id","expires_at","cols","rows","pty","workspace"];if(Object.keys(e).length!==_.length||Object.keys(e).some((M)=>!_.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)<=Ee))ir("invalid_pty_request");let w=e.pty;if(!w||typeof w!=="object"||Array.isArray(w))ir("invalid_pty_request");let S=w;if(Object.keys(S).length!==2||S.version!==1||!ce(S.jobId))ir("invalid_pty_request");let I;try{I=new URL(e.relay_url)}catch{return ir("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))ir("invalid_pty_request");let W=Date.parse(e.expires_at);if(!Number.isSafeInteger(W)||W<=f)ir("invalid_pty_request");return{workspace:H(e.workspace)??ir("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 Fo(e){let{session:l,binding:f}=e;if(f.assertCurrent(),e.signal.aborted||Date.now()>=l.leaseExpiresAtMs)ir("cancelled");let _=new Pn(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,ve,be=(le)=>{ve=new r(le,"Bound terminal input was refused."),I()};_.on("error",()=>be("pty_relay_unavailable")),_.on("close",I),_.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 Ke=x.at(-1),Le=he&&Ke!==void 0&&"data"in Ke&&Ke.data.length+xe.length<=ne;if(xe.length>ne||M+xe.length>Vn){be("pty_input_backpressure");return}if(Le)Ke.data=Buffer.concat([Ke.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((ke)=>Number.isSafeInteger(ke)&&ke>=1&&ke<=Ee))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 Oe(le){return Kn(JSON.stringify({...f.scope,version:1,sessionId:l.sessionId,operationId:l.operationId,job:{...le,output:[],pty:le.pty?{...le.pty,output:[]}:void 0}}))}function $e(le){if(!le.ok)ir(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))ir("pty_binding_changed");if(Oe(he),he.process)fe??={...he.process};return he}async function qe(le){f.assertCurrent();let he=await f.request(le,w.signal);if(f.assertCurrent(),w.signal.aborted)ir("cancelled");let xe=$e(he);if(xe.inputSequence!==G)ir("job_input_sequence");if(!_t(xe)&&xe.leaseExpiresAtMs<=Date.now())ir("pty_binding_changed");return xe}function ye(le){if(f.assertCurrent(),w.signal.aborted||_.readyState!==Pn.OPEN||_.bufferedAmount+Buffer.byteLength(le)>Mo)ir("pty_output_backpressure");_.send(le)}function Fe(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)ir("pty_output_gap");let xe=Buffer.from(he.dataBase64,"base64");if(_.bufferedAmount+xe.length>Mo)return!1;ye(xe),F=he.cursor}if(F!==le.nextCursor)ir("pty_output_gap");return!0}async function Ve(le,he){let xe;try{await Promise.race([e.emit(le,he),new Promise((Ke,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(Xt),he=f.request({jobId:l.jobId,action:"cancel",input:{}},le),xe,Ke=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,Ke]);if(le.aborted)ir("pty_cleanup_unconfirmed");return $e(Le)}finally{le.removeEventListener("abort",xe)}}try{await new Promise((Le,Be)=>{let ke=setTimeout(()=>{I(),Be(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),We=()=>{clearTimeout(ke),Be(new r("cancelled","Terminal pairing was cancelled."))};if(w.signal.addEventListener("abort",We,{once:!0}),_.once("open",()=>{clearTimeout(ke),w.signal.removeEventListener("abort",We),Le()}),w.signal.aborted)We()}),f.assertCurrent(),T=!0,z=await qe({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)ir("pty_not_ready");await new Promise((Le)=>setTimeout(Le,25)),z=await qe({jobId:l.jobId,action:"inspect",input:{after:F}})}if(z.state!=="running"||z.inputSequence!==0||z.leaseExpiresAtMs<=Date.now())ir("pty_not_ready");await Ve("pty.ready",Oe(z)),re=!0,ye(JSON.stringify({t:"open",cols:z.pty.cols,rows:z.pty.rows,receipt:Oe(z)}));let he=!1,xe=0,Ke=!1;while(!w.signal.aborted){let Le=z.firstCursor>F+1,Be=Fe(z);if(_t(z)){if(Be)break}else if(Le)he=!0;else if(he&&Be&&Date.now()>=xe){he=!1,xe=Date.now()+1000;let{cols:We,rows:tr}=z.pty;for(let nr of[{cols:We,rows:tr>1?tr-1:2},{cols:We,rows:tr}]){if(_t(z))break;let Pr=++G;if(z=await qe({jobId:l.jobId,action:"resize",input:{sequence:Pr,...nr}}),z.inputSequence!==Pr)ir("job_input_sequence")}continue}let ke=_t(z)||Ke?void 0:x.shift();if(ke){M-=jo(ke);let We=++G;try{z=await qe("data"in ke?{jobId:l.jobId,action:"input",input:{sequence:We,dataBase64:ke.data.toString("base64")}}:{jobId:l.jobId,action:"resize",input:{sequence:We,cols:ke.cols,rows:ke.rows}})}catch(tr){if(!(tr instanceof r)||tr.code!=="job_input_backpressure")throw tr;G-=1,x.unshift(ke),M+=jo(ke),Ke=!0;continue}if(z.inputSequence!==We)ir("job_input_sequence")}else if(await new Promise((We)=>{let tr=setTimeout(We,Ke||!Be?10:50);if(S=()=>{clearTimeout(tr),We()},w.signal.aborted||!Ke&&x.length)S()}),Ke=!1,S=()=>{},!w.signal.aborted&&Be)try{z=await qe({jobId:l.jobId,action:"inspect",input:{after:F}})}catch(We){if(!J||!(We instanceof r)||We.code!=="cancelled")throw We}}}catch(le){ve??=le}finally{if(re=!1,x.length=0,clearTimeout(W),e.signal.removeEventListener("abort",I),I(),T&&(!z||!_t(z)))try{z=await Te()}catch{z=void 0}try{if(!z||!_t(z)||z.pty?.cleanup!=="confirmed")ir("pty_cleanup_unconfirmed");let le=Oe(z);if(_.readyState===Pn.OPEN)await new Promise((he)=>{let xe=setTimeout(he,500);_.send(JSON.stringify({t:"exit",code:z.exitCode,receipt:le}),()=>{clearTimeout(xe),he()})});await Ve("pty.stopped",le)}catch(le){ve??=le}_.terminate()}if(ve)throw ve;if(e.signal.aborted)ir("cancelled");if(!z)ir("pty_cleanup_unconfirmed");return{receipt:Oe(z)}}import{createHash as Si,randomUUID as Tn}from"crypto";import{spawnSync as Go}from"child_process";import{closeSync as Uo,constants as In,fstatSync as Ei,fsyncSync as Ri,lstatSync as Lt,mkdirSync as Oi,mkdtempSync as Jo,openSync as zo,readFileSync as xi,readdirSync as Vo,realpathSync as Nt,rmSync as An,unlinkSync as Pi}from"fs";import{createConnection as Ai}from"net";import{dirname as Ti,join as tt,sep as Ci}from"path";import{tmpdir as Hi}from"os";var Or=new Map,Jr=new Map;function Ur(e,l){return Si("sha256").update(JSON.stringify([e,l])).digest("hex")}function mt(e){try{Oi(e,{mode:448})}catch(f){if(!(f instanceof Error&&("code"in f)&&f.code==="EEXIST"))throw f}let l=Lt(e);if(!l.isDirectory()||l.isSymbolicLink()||!A(l)||Nt(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function Ni(e){let l;try{l=Lt(e)}catch(f){if(f instanceof Error&&"code"in f&&f.code==="ENOENT")return!1;throw f}return!l.isDirectory()||l.isSymbolicLink()||Vo(e).length>0}function hr(e){let l=Ur(e.root,e.runId),f=e.previousRuntimeDirectories?.find((I)=>Ni(tt(I,"jobs",l.slice(0,16))))??e.runtimeDirectory;mt(f);let _=tt(f,"jobs");mt(_);let w=tt(_,l.slice(0,16));if(e.maxScopes!==void 0){let I=Vo(_);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.")}mt(w);let S=Jo(tt(Wo(),"reason-j-"));try{return mt(S),{journalDirectory:w,scopeId:l,launchDirectory:S,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${Tn()}`:tt(S,"control.sock"),disposeSocket:()=>An(S,{recursive:!0,force:!0})}}catch(I){throw An(S,{recursive:!0,force:!0}),I}}var Bi=60000,ji=5000;function Wi(e){if(process.platform==="win32")return Fi(e);let l=Go("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,_=f?"JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(f[1]):-1;if(!f||_<0||_%3!==0)return null;let w=new Date(Number(f[6]),_/3,Number(f[2]),Number(f[3]),Number(f[4]),Number(f[5])).getTime();return Number.isFinite(w)?w:null}function Fi(e){let l=Go(C("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().ToString('o')`],{encoding:"utf8",timeout:5000,windowsHide:!0,env:De()}),f=l.status===0?Date.parse(l.stdout.trim()):Number.NaN;return Number.isFinite(f)?f:null}function Yo(e,l={}){let f=tt(e.journalDirectory,"owner.lock"),_;try{_=zo(f,In.O_RDONLY|In.O_NOFOLLOW)}catch{return null}try{let w=Ei(_);if(!w.isFile()||w.nlink!==1||!A(w)||w.size>4096)return null;let S=null;try{S=JSON.parse(xi(_,"utf8"))}catch{}let I;if(S===null){if((l.now??Date.now)()-w.mtimeMs<Bi)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??Wi)(F);if(z===null||z<=T+ji)return null;I={reason:"pid_reused",executorLaunchId:re}}}let W=Lt(f);if(W.dev!==w.dev||W.ino!==w.ino)return null;Pi(f);let x=zo(e.journalDirectory,In.O_RDONLY);try{Ri(x)}finally{Uo(x)}return I}catch{return null}finally{Uo(_)}}function Xo(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=Ur(l.root,l.runId);if(Or.has(f)||l.operationId!==void 0&&Jr.has(l.operationId))throw new r("hands_jobs_busy","The Session already has a live Hands job supervisor.");let _={binding:l,key:f,terminals:new Map};if(l.previewAuthority&&l.environment)_.previews=Bo({authority:l.previewAuthority,runId:l.runId,expiresAtMs:l.expiresAtMs,executorLaunchId:l.executorLaunchId,environment:l.environment,isCurrent:()=>Or.get(_.key)===_,identity:()=>{try{return ht(l)}catch{return null}},inspect:(w,S)=>{if(Or.get(_.key)!==_)throw new r("preview_unavailable","The Hands supervisor is no longer current.");return Zo(l,{jobId:w,action:"inspect",input:{after:0}},S)}});if(Or.set(f,_),l.operationId!==void 0)Jr.set(l.operationId,_);return()=>{if(Or.get(_.key)===_)Or.delete(_.key);if(l.operationId!==void 0&&Jr.get(l.operationId)===_)Jr.delete(l.operationId);_.previews?.dispose();for(let w of _.terminals.values())w.abort()}}var Ui=5000,zi=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=Jr.get(e.operationId);if(!f||f.binding.root!==e.root)return l("No live Hands supervisor owns this operation.");for(let w=Date.now()+Ui;;){if(e.signal?.aborted)l("The Hands rebind was cancelled.");if(Jr.get(e.operationId)!==f)l("The Hands supervisor is no longer current.");let S=null;try{S=ht(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,zi))}if(Jr.get(e.operationId)!==f||Or.get(f.key)!==f)l("The Hands supervisor is no longer current.");let _=Ur(e.root,e.runId);if(f.key===_)return;if(Or.has(_))l("The taking run already has a live Hands job supervisor.");Or.delete(f.key);for(let w of f.terminals.values())w.abort();f.key=_,Or.set(_,f)}function ot(e){let l="operationId"in e?Jr.get(e.operationId):Or.get(Ur(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 Xi(e){let l=Or.get(Ur(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 Yi(e){let l=Or.get(Ur(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 Qi(e){let l=Ur(e.root,e.runId),f=Or.get(l),_=f?.binding,w=_?.runId,S=_?.previewAuthority,I=_?.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||!_||!S||!I||!W||!x||!_.workspace)return M();let G=Object.freeze({..._.workspace}),F=ht(_),T=I.current(),re=()=>{if(Or.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=ht(_),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 Fo({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)=>fr(F,Hr(JSON.stringify({...z,type:"job",version:2,generation:F.generation,id:Tn()})),fe)}})}finally{if(f.terminals.get(e.session.jobId)===J)f.terminals.delete(e.session.jobId)}}async function eo(e){if(ce(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let l=Or.get(Ur(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 Zo(l,e.payload,e.signal)}var $i=1e4,Ki=20,Gi=Se/2,Vi=Je/2,qi=(e)=>e.output.reduce((l,f)=>l+f.text.length,0);async function Zo(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:_,...w}=l;if(_!==void 0&&(w.action!=="start"||typeof w.input!=="object"||w.input===null||!("script"in w.input)||typeof _!=="number"||!Number.isSafeInteger(_)||_<1||_>$i))throw new r("invalid_payload","Only a script start may wait for its job, within its bound.");let S=(M)=>{let G=ht(e);return fr(G,Hr(JSON.stringify({...M,type:"job",version:2,generation:G.generation,id:Tn()})),f)},I=await S(w);if(_===void 0)return I;let W=Date.now()+_,x=I;while(x.ok&&["starting","running"].includes(x.job.state)&&x.job.output.length<Gi&&qi(x.job)<Vi&&!f.aborted&&Date.now()<W){if(await new Promise((M)=>setTimeout(M,Math.min(Ki,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 ht(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 fr(e,l,f){if(f.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((_,w)=>{let S=Ai(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 _(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{Gt,j}from"./vm-hands-entry-lite-rzr2ncf5.js";import{ue,Ce,Z,Ae,de,rr,et,X,O,H,tn}from"./vm-hands-entry-lite-38g65s5x.js";import{Lo,ri}from"./vm-hands-entry-lite-nqdstx24.js";import{xo,P,Je,Se,Ze,ne,Xe,Vn,Ee,Xt,ae,U,N,ce,Hr,zr,Kn}from"./vm-hands-entry-lite-5gevvgec.js";import{Pe,oe,pe,Y,Re,q,Q}from"./vm-hands-entry-lite-5tbntcyq.js";import{It,kr,at,V,D,R,b,En}from"./vm-hands-entry-lite-77j164ps.js";import{Er,xr,vn,oo,He,Sn}from"./vm-hands-entry-lite-tebh7dcm.js";import{K}from"./vm-hands-entry-lite-ncbzy69k.js";import{Mi}from"./vm-hands-entry-lite-v9qq2cgv.js";import{p,ze,Dt,ct,so,_e,we}from"./vm-hands-entry-lite-psywfz8m.js";import{v,h,lo}from"./vm-hands-entry-lite-f69t48dj.js";import{E}from"./vm-hands-entry-lite-txd50spx.js";import{Qt}from"./vm-hands-entry-lite-rn2rhavz.js";import{a,ie,$o}from"./vm-hands-entry-lite-swrymqj9.js";import{L,Ii,Di,Ho,y,t,k,Et,o,d,u,i,c,g,ee,s,n}from"./vm-hands-entry-lite-gvjffc5t.js";import{Li}from"./vm-hands-entry-lite-mk5ayds8.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{qo,se,Wo,C,De,Me,A}from"./vm-hands-entry-lite-87vmbt38.js";var gi=()=>{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"},_={nan:"NaN"};return(w)=>{switch(w.code){case"invalid_type":{let S=_[w.expected]??w.expected,I=Ho(w.input),W=_[I]??I;return`Invalid input: expected ${S}, received ${W}`}case"invalid_value":if(w.values.length===1)return`Invalid input: expected ${Di(w.values[0])}`;return`Invalid option: expected one of ${Ii(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":""}: ${Ii(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 Rn(){return{localeError:gi()}}L(Rn());class pt extends Error{}function Ao(e){let l;try{l=new URL(e)}catch{throw new pt("The proxy must be a URL like https://proxy.example.com:3128.")}if(l.protocol!=="https:"&&l.protocol!=="http:")throw new pt("The proxy URL must use the https or http scheme.");if(!l.hostname)throw new pt("The proxy URL must name a host.");if(l.port!==""&&Number(l.port)<1)throw new pt("The proxy URL must use a port between 1 and 65535.");if(l.pathname!==""&&l.pathname!=="/"||l.search||l.hash)throw new pt("The proxy URL must not carry a path, query, or fragment.");return l.toString()}import{createHash as bi}from"crypto";import{isAbsolute as To,join as Do,relative as Co,resolve as Vt,sep as No}from"path";var Jt=t().min(1).refine(To,"absolute path required"),xn=c({version:n(1),apiOrigin:Et(),channel:s(["staging","production"]),stateDirectory:Jt,workspaceRoot:Jt,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(Gt),url:t().refine((e)=>{try{return Ao(e)===e}catch{return!1}},"invalid proxy URL"),caFile:Jt.optional()}).optional(),userChrome:d().optional(),cloudSessions:n(!0).optional(),localLogins:d().optional(),folders:u(Jt).min(1).max(31).optional()}),wi=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,B=g("channel",[xn,xn.extend({channel:n("pr"),apiOrigin:t(),prEnvironment:t()}),xn.extend({channel:n("local-qa"),apiOrigin:t()})]).superRefine((e,l)=>{if(e.channel==="local-qa"){if(!wi.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 _=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(!_||/^pr-[1-9][0-9]*$/.exec(_)?.[0]!==_||w?.[0]!==e.apiOrigin||S?.length!==1||S[0]!==_)l.addIssue({code:"custom",message:"PR worker requires explicit prEnvironment and an exact same-PR HTTPS Railway origin"})}else{let _=new URL(e.apiOrigin);if(_.origin!==e.apiOrigin||_.username||_.password||_.protocol!=="https:"&&!(_.protocol==="http:"&&ri(_.origin))||!ri(_.origin)&&!Lo(e.channel,_.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((_)=>!je(_,e.stateDirectory)))l.addIssue({code:"custom",message:"folders must be distinct and disjoint from state"})});function m(e){return Do(e.stateDirectory,`headless-${e.channel==="pr"?e.prEnvironment:e.channel}`)}function je(e,l){if(Fr(l,e))return!1;return!Fr(e,l)||E(Do(No,Co(Vt(e),Vt(l))))}function Fr(e,l){let f=Co(Vt(e),Vt(l));return f===""||f!==".."&&!f.startsWith(`..${No}`)&&!To(f)}function te(e){let{proxy:l,userChrome:f,cloudSessions:_,localLogins:w,folders:S,...I}=e;return bi("sha256").update(JSON.stringify(I)).digest("hex")}var yi=4,vi=[2375,2376,9222,9229];function pr(e){let l=new Set(vi);for(let f of e){let _=new URL(f);l.add(Number(_.port||(["https:","wss:"].includes(_.protocol)?443:80)))}return l}function Gr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var ki=60000;function Bo(e){let l=new AbortController,f=new Map,_=(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)Gr()}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())>ki)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(),ve=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},Oe=re?T:be;if(G.aborted||!fe)return null;if(fe.generation!==F.generation||fe.fenceId!==F.fenceId||ve?.snapshot_id!==J?.snapshot_id||ve?.revision!==J?.revision)return"moved";let $e=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||!Oe||!$e)return null;if(($e.snapshotId!==Oe.snapshotId||$e.revision!==Oe.revision)&&(re||!e.environment.carried($e.snapshotId,$e.revision)))return null;if(!T&&F.generation===x.generation&&F.fenceId===x.fenceId)M.opened={...Oe,...$e};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:Oe.attachmentRevision,grantRevision:Oe.grantRevision,generation:Oe.generation,fenceId:Oe.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}=ct(x);if(G.aborted||F.expiresAtMs<=Date.now()||F.expiresAtMs>Date.now()+p.lifetimeMs||new URL(T).origin!==e.authority.relayOrigin)Gr();let re=_(F),J=f.get(re);if(J){if(!ze(J.binding,F)||J.relay!==T)Gr();if(await J.opened,!await Dt(()=>J.port.check())||G.aborted||J.abort.signal.aborted)Gr();return{opened:!0,binding:F}}if(f.size>=yi)Gr();let z=new AbortController,fe={},ve=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 Oe=_e({binding:F,deviceRelayUrl:T,port:ve,signal:z.signal}),$e={binding:F,relay:T,abort:z,port:ve,opened:Oe};f.set(re,$e);let qe=()=>{if(G.removeEventListener("abort",be),l.signal.removeEventListener("abort",be),f.get(re)===$e)f.delete(re)};try{if((await Oe).closed.then(qe),G.removeEventListener("abort",be),w(M),z.signal.aborted||!await Dt(()=>ve.check()))Gr();return{opened:!0,binding:F}}catch{z.abort(),qe(),Gr()}},async close(x,M){w(M);let{binding:G}=so(x),F=f.get(_(G));if(!F||!ze(F.binding,G))Gr();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 Pn}from"ws";var jo=(e)=>("data"in e)?e.data.length:e.bytes,Mo=2*Xe;function ir(e){throw new r(e,"The bound Hands terminal is unavailable or its outcome is unconfirmed.")}var _t=(e)=>!["starting","running"].includes(e.state);function Ji(e,l,f=Date.now()){let _=["relay_url","session_id","expires_at","cols","rows","pty","workspace"];if(Object.keys(e).length!==_.length||Object.keys(e).some((M)=>!_.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)<=Ee))ir("invalid_pty_request");let w=e.pty;if(!w||typeof w!=="object"||Array.isArray(w))ir("invalid_pty_request");let S=w;if(Object.keys(S).length!==2||S.version!==1||!ce(S.jobId))ir("invalid_pty_request");let I;try{I=new URL(e.relay_url)}catch{return ir("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))ir("invalid_pty_request");let W=Date.parse(e.expires_at);if(!Number.isSafeInteger(W)||W<=f)ir("invalid_pty_request");return{workspace:H(e.workspace)??ir("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 Fo(e){let{session:l,binding:f}=e;if(f.assertCurrent(),e.signal.aborted||Date.now()>=l.leaseExpiresAtMs)ir("cancelled");let _=new Pn(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,ve,be=(le)=>{ve=new r(le,"Bound terminal input was refused."),I()};_.on("error",()=>be("pty_relay_unavailable")),_.on("close",I),_.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 Ke=x.at(-1),Le=he&&Ke!==void 0&&"data"in Ke&&Ke.data.length+xe.length<=ne;if(xe.length>ne||M+xe.length>Vn){be("pty_input_backpressure");return}if(Le)Ke.data=Buffer.concat([Ke.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((ke)=>Number.isSafeInteger(ke)&&ke>=1&&ke<=Ee))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 Oe(le){return Kn(JSON.stringify({...f.scope,version:1,sessionId:l.sessionId,operationId:l.operationId,job:{...le,output:[],pty:le.pty?{...le.pty,output:[]}:void 0}}))}function $e(le){if(!le.ok)ir(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))ir("pty_binding_changed");if(Oe(he),he.process)fe??={...he.process};return he}async function qe(le){f.assertCurrent();let he=await f.request(le,w.signal);if(f.assertCurrent(),w.signal.aborted)ir("cancelled");let xe=$e(he);if(xe.inputSequence!==G)ir("job_input_sequence");if(!_t(xe)&&xe.leaseExpiresAtMs<=Date.now())ir("pty_binding_changed");return xe}function ye(le){if(f.assertCurrent(),w.signal.aborted||_.readyState!==Pn.OPEN||_.bufferedAmount+Buffer.byteLength(le)>Mo)ir("pty_output_backpressure");_.send(le)}function Fe(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)ir("pty_output_gap");let xe=Buffer.from(he.dataBase64,"base64");if(_.bufferedAmount+xe.length>Mo)return!1;ye(xe),F=he.cursor}if(F!==le.nextCursor)ir("pty_output_gap");return!0}async function Ve(le,he){let xe;try{await Promise.race([e.emit(le,he),new Promise((Ke,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(Xt),he=f.request({jobId:l.jobId,action:"cancel",input:{}},le),xe,Ke=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,Ke]);if(le.aborted)ir("pty_cleanup_unconfirmed");return $e(Le)}finally{le.removeEventListener("abort",xe)}}try{await new Promise((Le,Be)=>{let ke=setTimeout(()=>{I(),Be(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),We=()=>{clearTimeout(ke),Be(new r("cancelled","Terminal pairing was cancelled."))};if(w.signal.addEventListener("abort",We,{once:!0}),_.once("open",()=>{clearTimeout(ke),w.signal.removeEventListener("abort",We),Le()}),w.signal.aborted)We()}),f.assertCurrent(),T=!0,z=await qe({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)ir("pty_not_ready");await new Promise((Le)=>setTimeout(Le,25)),z=await qe({jobId:l.jobId,action:"inspect",input:{after:F}})}if(z.state!=="running"||z.inputSequence!==0||z.leaseExpiresAtMs<=Date.now())ir("pty_not_ready");await Ve("pty.ready",Oe(z)),re=!0,ye(JSON.stringify({t:"open",cols:z.pty.cols,rows:z.pty.rows,receipt:Oe(z)}));let he=!1,xe=0,Ke=!1;while(!w.signal.aborted){let Le=z.firstCursor>F+1,Be=Fe(z);if(_t(z)){if(Be)break}else if(Le)he=!0;else if(he&&Be&&Date.now()>=xe){he=!1,xe=Date.now()+1000;let{cols:We,rows:tr}=z.pty;for(let nr of[{cols:We,rows:tr>1?tr-1:2},{cols:We,rows:tr}]){if(_t(z))break;let Pr=++G;if(z=await qe({jobId:l.jobId,action:"resize",input:{sequence:Pr,...nr}}),z.inputSequence!==Pr)ir("job_input_sequence")}continue}let ke=_t(z)||Ke?void 0:x.shift();if(ke){M-=jo(ke);let We=++G;try{z=await qe("data"in ke?{jobId:l.jobId,action:"input",input:{sequence:We,dataBase64:ke.data.toString("base64")}}:{jobId:l.jobId,action:"resize",input:{sequence:We,cols:ke.cols,rows:ke.rows}})}catch(tr){if(!(tr instanceof r)||tr.code!=="job_input_backpressure")throw tr;G-=1,x.unshift(ke),M+=jo(ke),Ke=!0;continue}if(z.inputSequence!==We)ir("job_input_sequence")}else if(await new Promise((We)=>{let tr=setTimeout(We,Ke||!Be?10:50);if(S=()=>{clearTimeout(tr),We()},w.signal.aborted||!Ke&&x.length)S()}),Ke=!1,S=()=>{},!w.signal.aborted&&Be)try{z=await qe({jobId:l.jobId,action:"inspect",input:{after:F}})}catch(We){if(!J||!(We instanceof r)||We.code!=="cancelled")throw We}}}catch(le){ve??=le}finally{if(re=!1,x.length=0,clearTimeout(W),e.signal.removeEventListener("abort",I),I(),T&&(!z||!_t(z)))try{z=await Te()}catch{z=void 0}try{if(!z||!_t(z)||z.pty?.cleanup!=="confirmed")ir("pty_cleanup_unconfirmed");let le=Oe(z);if(_.readyState===Pn.OPEN)await new Promise((he)=>{let xe=setTimeout(he,500);_.send(JSON.stringify({t:"exit",code:z.exitCode,receipt:le}),()=>{clearTimeout(xe),he()})});await Ve("pty.stopped",le)}catch(le){ve??=le}_.terminate()}if(ve)throw ve;if(e.signal.aborted)ir("cancelled");if(!z)ir("pty_cleanup_unconfirmed");return{receipt:Oe(z)}}import{createHash as Si,randomUUID as Tn}from"crypto";import{spawnSync as Go}from"child_process";import{closeSync as Uo,constants as In,fstatSync as Ei,fsyncSync as Ri,lstatSync as Lt,mkdirSync as Oi,mkdtempSync as Jo,openSync as zo,readFileSync as xi,readdirSync as Vo,realpathSync as Nt,rmSync as An,unlinkSync as Pi}from"fs";import{createConnection as Ai}from"net";import{dirname as Ti,join as tt,sep as Ci}from"path";import{tmpdir as Hi}from"os";var Or=new Map,Jr=new Map;function Ur(e,l){return Si("sha256").update(JSON.stringify([e,l])).digest("hex")}function mt(e){try{Oi(e,{mode:448})}catch(f){if(!(f instanceof Error&&("code"in f)&&f.code==="EEXIST"))throw f}let l=Lt(e);if(!l.isDirectory()||l.isSymbolicLink()||!A(l)||Nt(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function Ni(e){let l;try{l=Lt(e)}catch(f){if(f instanceof Error&&"code"in f&&f.code==="ENOENT")return!1;throw f}return!l.isDirectory()||l.isSymbolicLink()||Vo(e).length>0}function hr(e){let l=Ur(e.root,e.runId),f=e.previousRuntimeDirectories?.find((I)=>Ni(tt(I,"jobs",l.slice(0,16))))??e.runtimeDirectory;mt(f);let _=tt(f,"jobs");mt(_);let w=tt(_,l.slice(0,16));if(e.maxScopes!==void 0){let I=Vo(_);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.")}mt(w);let S=Jo(tt(Wo(),"reason-j-"));try{return mt(S),{journalDirectory:w,scopeId:l,launchDirectory:S,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${Tn()}`:tt(S,"control.sock"),disposeSocket:()=>An(S,{recursive:!0,force:!0})}}catch(I){throw An(S,{recursive:!0,force:!0}),I}}var Bi=60000,ji=5000;function Wi(e){if(process.platform==="win32")return Fi(e);let l=Go("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,_=f?"JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(f[1]):-1;if(!f||_<0||_%3!==0)return null;let w=new Date(Number(f[6]),_/3,Number(f[2]),Number(f[3]),Number(f[4]),Number(f[5])).getTime();return Number.isFinite(w)?w:null}function Fi(e){let l=Go(C("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().ToString('o')`],{encoding:"utf8",timeout:5000,windowsHide:!0,env:De()}),f=l.status===0?Date.parse(l.stdout.trim()):Number.NaN;return Number.isFinite(f)?f:null}function Yo(e,l={}){let f=tt(e.journalDirectory,"owner.lock"),_;try{_=zo(f,In.O_RDONLY|In.O_NOFOLLOW)}catch{return null}try{let w=Ei(_);if(!w.isFile()||w.nlink!==1||!A(w)||w.size>4096)return null;let S=null;try{S=JSON.parse(xi(_,"utf8"))}catch{}let I;if(S===null){if((l.now??Date.now)()-w.mtimeMs<Bi)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??Wi)(F);if(z===null||z<=T+ji)return null;I={reason:"pid_reused",executorLaunchId:re}}}let W=Lt(f);if(W.dev!==w.dev||W.ino!==w.ino)return null;Pi(f);let x=zo(e.journalDirectory,In.O_RDONLY);try{Ri(x)}finally{Uo(x)}return I}catch{return null}finally{Uo(_)}}function Xo(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=Ur(l.root,l.runId);if(Or.has(f)||l.operationId!==void 0&&Jr.has(l.operationId))throw new r("hands_jobs_busy","The Session already has a live Hands job supervisor.");let _={binding:l,key:f,terminals:new Map};if(l.previewAuthority&&l.environment)_.previews=Bo({authority:l.previewAuthority,runId:l.runId,expiresAtMs:l.expiresAtMs,executorLaunchId:l.executorLaunchId,environment:l.environment,isCurrent:()=>Or.get(_.key)===_,identity:()=>{try{return ht(l)}catch{return null}},inspect:(w,S)=>{if(Or.get(_.key)!==_)throw new r("preview_unavailable","The Hands supervisor is no longer current.");return Zo(l,{jobId:w,action:"inspect",input:{after:0}},S)}});if(Or.set(f,_),l.operationId!==void 0)Jr.set(l.operationId,_);return()=>{if(Or.get(_.key)===_)Or.delete(_.key);if(l.operationId!==void 0&&Jr.get(l.operationId)===_)Jr.delete(l.operationId);_.previews?.dispose();for(let w of _.terminals.values())w.abort()}}var Ui=5000,zi=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=Jr.get(e.operationId);if(!f||f.binding.root!==e.root)return l("No live Hands supervisor owns this operation.");for(let w=Date.now()+Ui;;){if(e.signal?.aborted)l("The Hands rebind was cancelled.");if(Jr.get(e.operationId)!==f)l("The Hands supervisor is no longer current.");let S=null;try{S=ht(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,zi))}if(Jr.get(e.operationId)!==f||Or.get(f.key)!==f)l("The Hands supervisor is no longer current.");let _=Ur(e.root,e.runId);if(f.key===_)return;if(Or.has(_))l("The taking run already has a live Hands job supervisor.");Or.delete(f.key);for(let w of f.terminals.values())w.abort();f.key=_,Or.set(_,f)}function ot(e){let l="operationId"in e?Jr.get(e.operationId):Or.get(Ur(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 Xi(e){let l=Or.get(Ur(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 Yi(e){let l=Or.get(Ur(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 Qi(e){let l=Ur(e.root,e.runId),f=Or.get(l),_=f?.binding,w=_?.runId,S=_?.previewAuthority,I=_?.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||!_||!S||!I||!W||!x||!_.workspace)return M();let G=Object.freeze({..._.workspace}),F=ht(_),T=I.current(),re=()=>{if(Or.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=ht(_),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 Fo({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)=>fr(F,Hr(JSON.stringify({...z,type:"job",version:2,generation:F.generation,id:Tn()})),fe)}})}finally{if(f.terminals.get(e.session.jobId)===J)f.terminals.delete(e.session.jobId)}}async function eo(e){if(ce(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let l=Or.get(Ur(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 Zo(l,e.payload,e.signal)}var $i=1e4,Ki=20,Gi=Se/2,Vi=Je/2,qi=(e)=>e.output.reduce((l,f)=>l+f.text.length,0);async function Zo(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:_,...w}=l;if(_!==void 0&&(w.action!=="start"||typeof w.input!=="object"||w.input===null||!("script"in w.input)||typeof _!=="number"||!Number.isSafeInteger(_)||_<1||_>$i))throw new r("invalid_payload","Only a script start may wait for its job, within its bound.");let S=(M)=>{let G=ht(e);return fr(G,Hr(JSON.stringify({...M,type:"job",version:2,generation:G.generation,id:Tn()})),f)},I=await S(w);if(_===void 0)return I;let W=Date.now()+_,x=I;while(x.ok&&["starting","running"].includes(x.job.state)&&x.job.output.length<Gi&&qi(x.job)<Vi&&!f.aborted&&Date.now()<W){if(await new Promise((M)=>setTimeout(M,Math.min(Ki,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 ht(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 fr(e,l,f){if(f.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((_,w)=>{let S=Ai(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 _(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)>Ze)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=zr(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 Ko(e){let l=Nt(e.root),f=e.authority,_=Date.parse(e.leaseUntil),w=()=>{if(e.signal.throwIfAborted(),!Number.isFinite(_)||_<=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:_,assertCurrent:w};let S=Ur(l,e.runId),I=Or.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=ht(W);if(Or.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:_,privateDirectory:Ti(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 to(e,l){let f=Pe.parse(e.request),_=oe.parse(e.authority);if(_.contributorRefresh&&f.kind==="read"&&_.readOnly)return l(Ko(e));let w=Boolean(_.contributorRefresh);if(w&&(_.merge||f.kind!=="pr_mutation"||f.mutation.action!=="edit"||typeof f.mutation.body!=="string"||f.mutation.title!==void 0||f.mutation.base!==void 0||_.readOnly||_.runId!==e.runId||_.repoFullName!==f.repoFullName))throw Error("local_device_gh_contributor_refresh_authority_invalid");if(f.kind!=="pr_merge"&&!w){if(_.merge)throw Error("local_device_gh_merge_authority_invalid");return l(Ko(e))}if(!w&&(!_.merge||_.readOnly||_.runId!==e.runId||_.repoFullName!==f.repoFullName||_.merge.source==="agent"&&(_.generation===null||_.fenceId===null)))throw Error("local_device_gh_merge_authority_invalid");let S=Nt(e.root),I=Lt(S),W=Date.parse(e.leaseUntil);if(!Number.isFinite(W)||W<=Date.now())throw Error("local_device_gh_lease_expired");let x=Nt(Hi());if(x===S||x.startsWith(S+Ci))throw Error("local_device_gh_private_scope_unavailable");let M=Jo(tt(x,"reason-gh-merge-"));try{mt(M);let G=()=>{if(e.signal.throwIfAborted(),Date.now()>=W)throw Error("local_device_gh_lease_expired");let F=Lt(e.root);if(F.isSymbolicLink()||F.dev!==I.dev||F.ino!==I.ino||Nt(e.root)!==S)throw Error("local_device_gh_authority_changed");mt(M)};return G(),await l({root:S,readOnly:!1,privateDirectory:M,forbiddenSecretValues:[],signal:e.signal,deadlineMs:W,assertCurrent:G})}finally{An(M,{recursive:!0,force:!0})}}var rs=43200000;function gt(e){return Number.isSafeInteger(e)&&Math.abs(e)<=8640000000000000?e:null}function Qo(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function es(e,l){return Object.keys(e).length===l.length&&l.every((f)=>Object.hasOwn(e,f))}function ro(e){if(!Qo(e)||!es(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 _ of["validation_now_ms","expiry_ms"]){let w=e[_];if(w!==null&&(typeof w!=="number"||gt(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(!Qo(f)||!es(f,["kind","status","sha256","observed_at_ms"])||f.observed_at_ms!==null&&(typeof f.observed_at_ms!=="number"||gt(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 Dn=c({kind:s(["workspace_source","mcp_control"]),target_revision:o().int().nonnegative(),root_grant_revision:o().int().positive()}),ts=new RegExp(at.tokenPattern),ea=c({token_url:Et().max(2048),request_token:t().min(1).max(8192).regex(ts),aws_credentials_url:Et().max(2048).nullable()});function ns(e,l){let f=(_,w)=>{try{let S=new URL(_);return S.origin===new URL(l).origin&&S.pathname===w&&!S.username&&!S.password&&!S.search&&!S.hash}catch{return!1}};if(!ts.test(e.request_token)||!f(e.token_url,at.tokenPath)||e.aws_credentials_url!==null&&!f(e.aws_credentials_url,at.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 os(e){return new TextEncoder().encode(e).byteLength}function ra(e){return os(JSON.stringify(e)+`
|
|
4
4
|
`)}var mr=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:Dn.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")&&os(e)<=V.valueBytes)).refine((e)=>Object.keys(e).length<=V.variables),github_auth:n("local_gh").optional(),git:c({base_url:Et().max(2048),token:t().min(1).max(4096).regex(/^[A-Za-z0-9._~-]+$/),expires_at:y.datetime({offset:!0})}).nullable(),cloud_access:ea.optional()}).refine((e)=>e.github_auth!=="local_gh"||e.git===null,"conflicting git authority").refine((e)=>ra(e)<=V.snapshotBytes,"snapshot too large");import{spawn as ta}from"child_process";import{basename as na,isAbsolute as Ou}from"path";var oa=0,ss=120000,is=15000,sa=65536;function Cn(e=process.execPath,l=process.argv[1]){let f=na(e),_=(f.startsWith("bun")||f.startsWith("node"))&&typeof l==="string"&&l.length>0;return{command:e,prefix:_?[l]:[]}}function no(e={}){let{command:l,prefix:f}=Cn(e.executablePath,e.sourceEntrypoint),_=e.spawnProcess??ta,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<ss-is)return;if(S){let F=S;S=null,x(F)}let G;try{G=_(l,[...f,"__device","__hands-worker","--handoff-fd",String(oa)],{cwd:"/",env:{PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin"},shell:!1,stdio:["pipe","ignore","pipe"]})}catch{return}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((Oe,$e)=>G.args[$e]!==Oe)||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,ve={configPath:T,cwd:J,env:Object.fromEntries(Object.entries(re).filter((Oe)=>typeof Oe[1]==="string"))},be=JSON.stringify(ve);if(F.exitCode!==null||F.signalCode!==null||!fe||fe.destroyed||w()-I>=ss-is||Buffer.byteLength(be,"utf8")>sa)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 ua,constants as fa,statSync as pa}from"fs";import{homedir as _a,tmpdir as ma,userInfo as ha}from"os";import{delimiter as ga,win32 as ba}from"path";var ia=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 aa=["BUN_CONFIG_","BUN_INSPECT","DYLD_","NODE_DEBUG"],ca=new Set(["BUN_INSTALL"]);var da=/^--(?:max-old-space-size|max-semi-space-size|stack-size)=\d{1,9}$/;function la(e){return(e??"").split(/\s+/).filter(Boolean).every((l)=>da.test(l.replaceAll("_","-")))}function as(e){return Object.keys(e).filter((l)=>ia.has(l)&&!(l==="NODE_OPTIONS"&&la(e[l]))||aa.some((f)=>l.startsWith(f))||l.startsWith("BUN_")&&!ca.has(l)).sort()}var wa=new Set(["HOME","PATH","PWD","OLDPWD","SHLVL","_","TMPDIR","TMP","TEMP","SHELL","BASH_ENV","ENV","ZDOTDIR","PROMPT_COMMAND","IFS","CDPATH","GLOBIGNORE","SHELLOPTS","BASHOPTS","NODE_PATH"]),ya=/^(?:ARA_|REASON_|PI_|GIT_|GH_|GITHUB_|LD_|DYLD_|BUN_|BASH_FUNC_|SSH_)/,va=/TOKEN|SECRET|PASSW|PASSPHRASE|CREDENTIAL|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|AUTH/i,ka=/^[A-Za-z_][A-Za-z0-9_]*$/;function gr(e=process.env){let l=(w)=>{if(!(process.platform==="win32"?ba.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(as(e)),_=Object.fromEntries(Object.entries(e).filter((w)=>{let[S,I]=w;return typeof I==="string"&&I.length<=32768&&!I.includes("\x00")&&S.length<=128&&ka.test(S)&&!f.has(S)&&!wa.has(S)&&!ya.test(S)&&!va.test(S)}).sort(([w],[S])=>w.localeCompare(S)).slice(0,512));return{home:l(e.HOME||(process.platform==="win32"?e.USERPROFILE:void 0)||_a()),path:((w)=>process.platform==="win32"?Sn(w):w)(xr(e.PATH??"").join(ga)||Er),temporaryDirectory:l(e.TMPDIR||e.TMP||e.TEMP||ma()),variables:_}}function _r(e=process.env,l=()=>ha().shell){if(process.platform==="win32")return se();let f=(w)=>{if(!w||!/^\/[A-Za-z0-9._/-]*\/(?:bash|zsh)$/.test(w))return!1;try{return ua(w,fa.X_OK),pa(w).isFile()}catch{return!1}};if(f(e.SHELL))return e.SHELL;let _;try{_=l()}catch{_=void 0}return f(_)?_:"/bin/zsh"}import{readdir as Sa}from"fs/promises";var Ea=15000;function gn(e){let l=e instanceof Error&&"code"in e?e.code:null;return l==="EPERM"||l==="EACCES"}function _n(e){return new r("folder_access_denied",`macOS blocked Reason from opening ${e}. Allow Reason in System Settings \u203A Privacy & Security \u203A Files and Folders `+"(or Full Disk Access), then restart the Reason app or worker on this Mac and try again: until it restarts it keeps the earlier refusal.")}async function cs(e,{timeoutMs:l=Ea,open:f=(_)=>Sa(_)}={}){let _,w=new Promise((S)=>{_=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(gn(S))throw _n(e);if(S instanceof r)throw S}finally{clearTimeout(_)}}import{chmodSync as tc,closeSync as nc,constants as zn,fstatSync as oc,lstatSync as xs,openSync as sc,readSync as ic,realpathSync as $n,unlinkSync as ac}from"fs";import{lookup as cc}from"dns/promises";import{createRequire as dc}from"module";import{request as lc}from"http";import{request as uc}from"https";import it from"net";import{platform as Ds}from"os";import{basename as fc,extname as pc,isAbsolute as Ps,relative as Gn,resolve as yt,sep as Jn}from"path";var ds=String.raw`
|
|
5
5
|
async (roots) => {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Pt,I}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Pt,I}from"./vm-hands-entry-lite-vrenpefs.js";import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{_,er}from"./vm-hands-entry-lite-nqdstx24.js";import{be}from"./vm-hands-entry-lite-yretc2th.js";function Bi(e,i){let t=T(e,"REASON_API_URL")?.trim();if(!t)return er(i);let n=new URL(t);if(n.protocol!=="https:"&&!(n.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(n.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return n.origin}function Vo(e){return T(e,"REASON_API_URL")?.trim()?Bi(e,"production"):void 0}function Go(e){return T(e,"REASON_API_KEY")?.trim()||void 0}async function ys(e,i){let t=e.env??process.env,n=Go(t);if(!n)return(e.getCredentials??Pt)({apiOrigin:Vo(t),signal:i});let a=Bi(t,e.channel??_({env:t})),o=await(e.fetchImpl??fetch)(a+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+n,accept:"application/json"},signal:i}),p=await o.json().catch(()=>({})),r=be(p)?p:{};if(!o.ok){let s=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:"API key authentication failed ("+o.status+")";throw new I(o.status,typeof r.error==="string"?r.error:"api_key_auth_failed",s)}if(typeof r.org_id!=="string"||!r.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let l=Array.isArray(r.scopes)?r.scopes.filter((s)=>typeof s==="string"):[];return{credentialKind:"api_key",apiOrigin:a,accessToken:n,orgId:r.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:l}}export{Bi,Vo,Go,ys};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$n,Eo,zt}from"./vm-hands-entry-lite-eabever7.js";import{On,Ve,po,In,Dn,Nn,Pr,x}from"./vm-hands-entry-lite-
|
|
2
|
+
import{$n,Eo,zt}from"./vm-hands-entry-lite-eabever7.js";import{On,Ve,po,In,Dn,Nn,Pr,x}from"./vm-hands-entry-lite-v6yygjyx.js";import{xt}from"./vm-hands-entry-lite-v9qq2cgv.js";import{Dr}from"./vm-hands-entry-lite-qpdpzg8g.js";import{j}from"./vm-hands-entry-lite-rzr2ncf5.js";import{a}from"./vm-hands-entry-lite-swrymqj9.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 De,existsSync as I,lstatSync as _e,mkdirSync as we,readFileSync as Re,rmSync as ee,writeFileSync as g}from"fs";import{connect as de}from"net";import{join as y}from"path";var S=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
3
|
# The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
|
|
4
4
|
# python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
|
|
5
5
|
# Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var Qt={name:"github-native-engineer-device-worker-production",version:"0.2.
|
|
2
|
+
var Qt={name:"github-native-engineer-device-worker-production",version:"0.2.507",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@agentclientprotocol/sdk":"1.9.0","@anthropic-ai/sandbox-runtime":"^0.0.80","@earendil-works/pi-tui":"1.0.0","@reason/runtime-distribution":"workspace:*",diff:"8.0.4","open-browser-use-sdk":"0.1.42","playwright-core":"1.60.0",toml:"4.2.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.1",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^4.2.0",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
|
|
3
3
|
export{Qt};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{S,zt,Bn,Ge,Fn,jn}from"./vm-hands-entry-lite-eabever7.js";import{Yn}from"./vm-hands-entry-lite-
|
|
2
|
+
import{S,zt,Bn,Ge,Fn,jn}from"./vm-hands-entry-lite-eabever7.js";import{Yn}from"./vm-hands-entry-lite-vtc8mjpc.js";import{Mn}from"./vm-hands-entry-lite-ncbzy69k.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as ys,spawn as qe}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 Pn,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",uo="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,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{lt,Lt,Cr,kn,Ar,Cn,An,Pn}from"./vm-hands-entry-lite-8wcyveeh.js";import{Pe,ir,ni,yt,Bo,oe,Fo,jo,tt,Te,rn,oi,bt,li,ui,di,pi,hi,fi,mi,gi,_i,yi,wi,bi,vi,pe,Y,Re,q,Si,Ei,xi,ki,Ci,Ai,Pi,Ti,vt,Ri}from"./vm-hands-entry-lite-5tbntcyq.js";import{ue,Z,O}from"./vm-hands-entry-lite-38g65s5x.js";import{P,Jt}from"./vm-hands-entry-lite-5gevvgec.js";import{pr,Ji,Zi,ot,Xi,Yi,Qi,eo,to,ro,mr,gr,_r,gn,_n,yr,io,yn,wr,me,ge,Rt,br,Sr,Ot}from"./vm-hands-entry-lite-
|
|
2
|
+
import{lt,Lt,Cr,kn,Ar,Cn,An,Pn}from"./vm-hands-entry-lite-8wcyveeh.js";import{Pe,ir,ni,yt,Bo,oe,Fo,jo,tt,Te,rn,oi,bt,li,ui,di,pi,hi,fi,mi,gi,_i,yi,wi,bi,vi,pe,Y,Re,q,Si,Ei,xi,ki,Ci,Ai,Pi,Ti,vt,Ri}from"./vm-hands-entry-lite-5tbntcyq.js";import{ue,Z,O}from"./vm-hands-entry-lite-38g65s5x.js";import{P,Jt}from"./vm-hands-entry-lite-5gevvgec.js";import{pr,Ji,Zi,ot,Xi,Yi,Qi,eo,to,ro,mr,gr,_r,gn,_n,yr,io,yn,wr,me,ge,Rt,br,Sr,Ot}from"./vm-hands-entry-lite-bnxh4ax9.js";import{D,R,b}from"./vm-hands-entry-lite-77j164ps.js";import{Wi,Vi,fn,Gi,mn,Ki,it,dr}from"./vm-hands-entry-lite-7v1rd0sk.js";import{K}from"./vm-hands-entry-lite-ncbzy69k.js";import{He}from"./vm-hands-entry-lite-tebh7dcm.js";import{j}from"./vm-hands-entry-lite-rzr2ncf5.js";import{ur,hn,qi}from"./vm-hands-entry-lite-6x1an7es.js";import{go,_o,ut,yo,wo,bo,vo,So}from"./vm-hands-entry-lite-eabever7.js";import{Or,qt,Ir,Un,Hn}from"./vm-hands-entry-lite-qpdpzg8g.js";import{$t,qe,Bt}from"./vm-hands-entry-lite-ra8c0ytm.js";import{Ln,x,ho}from"./vm-hands-entry-lite-v6yygjyx.js";import{fo,mo}from"./vm-hands-entry-lite-6a96d80a.js";import{Mt,Tn,Rn}from"./vm-hands-entry-lite-2mskbtsd.js";import{ye,ao,co}from"./vm-hands-entry-lite-psywfz8m.js";import{be}from"./vm-hands-entry-lite-yretc2th.js";import{Nt}from"./vm-hands-entry-lite-np07qyeq.js";import{ve,jt,Ut,Ht,E}from"./vm-hands-entry-lite-txd50spx.js";import{a,ie}from"./vm-hands-entry-lite-swrymqj9.js";import{t,k,o,d,u,i,W,g,ee,s,n,zo}from"./vm-hands-entry-lite-gvjffc5t.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{fe,Ne,Le,Me,sn}from"./vm-hands-entry-lite-87vmbt38.js";import{$e}from"./vm-hands-entry-lite-mcjca0ez.js";import{request as kl}from"http";import{request as Tl}from"https";import{lookup as Dl}from"dns/promises";import{isIP as Nl}from"net";async function Ml(e){let l=new URL(e.url);return await new Promise((c,p)=>{let m=(l.protocol==="https:"?Tl:kl)(l,{method:"POST",headers:{...e.headers,"accept-encoding":"identity"},signal:e.signal,timeout:kn},(f)=>c({response:f,close:()=>{f.destroy(),m.destroy(),f.socket?.destroy()}}));m.once("error",p),m.once("timeout",()=>m.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),m.end(e.body)})}var zi=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),$l=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function es(e,l=0){if(!e||typeof e!=="object"||l>3)return null;let c=e.code;if(typeof c==="string"){if(zi.has(c))return"custom_endpoint_host_not_found";if($l.has(c))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(c))return"custom_endpoint_tls_failed"}for(let p of[...e instanceof AggregateError?e.errors:[],e.cause]){let m=es(p,l+1);if(m)return m}return null}async function Bl(e,l){let c=es(e),p=new URL(l).hostname.replace(/^\[|\]$/g,"");if(c!==null&&c!=="custom_endpoint_connection_failed"||Nl(p)!==0)return c;let m;return await Promise.race([Dl(p).then(()=>!0,(h)=>!zi.has(String(h?.code))),new Promise((h)=>{m=setTimeout(()=>h(!0),5000)})]).finally(()=>clearTimeout(m))?c:"custom_endpoint_host_not_found"}function Fl(e){for(let l=42;;l++){if(l===127)l=256;let c=String.fromCodePoint(l);if(!e.includes(c))return c}}function Ul(e,l){let c=Buffer.from(e),p=Buffer.from(l),m=new Uint32Array(c.length);for(let h=1,y=0;h<c.length;h++){while(y&&c[h]!==c[y])y=m[y-1];if(c[h]===c[y])y++;m[h]=y}let f=0;return(h,y=!1)=>{let S=Buffer.allocUnsafe(h.length*p.length+f),w=0;for(let _ of h){while(f&&c[f]!==_){let v=m[f-1];w+=c.copy(S,w,0,f-v),f=v}if(c[f]===_){if(f++,f===c.length)w+=p.copy(S,w),f=0}else S[w++]=_}if(y)w+=c.copy(S,w,0,f),f=0;return S.subarray(0,w)}}async function ts(e){e.signal.throwIfAborted();let l=Cn.safeParse(e.payload);if(!l.success)throw new r("custom_endpoint_invalid_request","Invalid local model request.");let c=l.data,p=An.parse(await e.credential(e.signal));if(!Ar(c,{baseUrl:c.baseUrl,api:p.api,execution:"device"}))throw new r("custom_endpoint_invalid_request","The request does not match the configured API.");e.signal.throwIfAborted();let m,f,h=0,y=0,S=0,w=Fl(p.apiKey),_=Ul(p.apiKey,w),v=async(I,A)=>{e.signal.throwIfAborted(),await new Promise((M,N)=>{let L=()=>{e.signal.removeEventListener("abort",L),N(e.signal.reason)};if(e.signal.addEventListener("abort",L,{once:!0}),e.signal.aborted){L();return}Promise.resolve().then(()=>(e.signal.throwIfAborted(),e.emit(I,A))).then(()=>{e.signal.removeEventListener("abort",L),M()},(B)=>{e.signal.removeEventListener("abort",L),N(B)})})},C=async(I)=>{if(h+=I.length,h>Lt)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let A=0;A<I.length;A+=lt){if(S>=Cr)throw new r("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await v(`custom_endpoint.chunk.${S++}`,{eof:!1,data:I.subarray(A,A+lt).toString("base64")})}};try{let I=await Ml({url:c.url,body:c.body,signal:e.signal,headers:{...c.headers,...p.api==="anthropic-messages"?{"x-api-key":p.apiKey}:{authorization:`Bearer ${p.apiKey}`}}});m=I.response,f=I.close;let A=m.statusCode??500;if(A>=300&&A<400)throw new r("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(m.headers["content-encoding"]&&m.headers["content-encoding"]!=="identity")throw new r("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let M={};for(let N of["content-type","retry-after","x-request-id","request-id"]){let L=m.headers[N];if(typeof L==="string")M[N]=L.replaceAll(p.apiKey,w).slice(0,4096)}await v("custom_endpoint.headers",{status:A,statusText:(m.statusMessage??"").replaceAll(p.apiKey,w).slice(0,256),headers:M});for await(let N of m){e.signal.throwIfAborted();let L=Buffer.isBuffer(N)?N:Buffer.from(N);if(y+=L.length,y>Lt)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await C(_(L))}return await C(_(Buffer.alloc(0),!0)),await v(`custom_endpoint.chunk.${S}`,{eof:!0}),{bytes:h,chunks:S}}catch(I){if(e.signal.throwIfAborted(),I instanceof r)throw I;throw new r((m?null:await Bl(I,c.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{f?.()}}import{join as rs}from"path";function Hl(e,l){return e===rs(l,".ara","workspace")||e===rs(l,".reason","workspace")}function ns(e,l){let c=e.filter((p)=>Hl(p.path,l));return c.length===1?c[0].path:null}var jl=/^[a-f0-9]{64}$/;var nn=32,ql=/^\/[^\x00-\x1f\x7f\\]*$/;function xr(e){if(typeof e!=="string"||e.length>4096||!ql.test(e))return!1;if(e==="/")return!0;return e.split("/").slice(1).every((l)=>l!==""&&l!=="."&&l!=="..")}function Er(e,l){let c=l==="win32"?/^([A-Za-z]):[\\/]*(.*)$/.exec(e):null;if(!c)return e;let p=c[2].split(/[\\/]+/).filter(Boolean).join("/");return`/${c[1].toUpperCase()}:${p?`/${p}`:""}`}function on(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let l=e;if(!xr(l.home)||!Array.isArray(l.roots)||l.roots.length>nn)return;let c=[];for(let p of l.roots){if(!p||typeof p!=="object"||Array.isArray(p))return;let{path_fingerprint:m,path:f}=p;if(typeof m!=="string"||!jl.test(m)||!xr(f))return;c.push({path_fingerprint:m,path:f})}return{home:l.home,roots:c}}function Wl(e){let l=/^Reason contributor (rc_[0-9a-f]{32})$/.exec(e.name)?.[1];return e.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&l?l:void 0}function zl(e){return Wl(e)??e.email.toLowerCase()}function an(e){let l=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec(e.trim());return l?zl({name:l[1],email:l[2]}):e.trim().toLowerCase()}var zt=(e)=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(l)=>`[${l.toLowerCase()}${l.toUpperCase()}]`),Gl=[...ve.map((e)=>`/(${e.map(zt).join("/")})(/|$)`),...jt.map((e)=>`/(${e.map(zt).join("/")})(/|$)`),...[...Ut].map((e)=>`/(${zt(e)})$`),`/${zt(".env.")}[^/]*$`,...Ht.map((e)=>`/[^/]*${zt(e)}$`)],os=`function localGithubSandboxProfile(root, temporary) {
|
|
3
3
|
return ['(version 1)','(deny default)','(import "system.sb")','(allow process-exec process-fork)',
|
|
4
4
|
'(allow file-read* (subpath "/bin") (subpath "/sbin") (subpath "/usr/bin") (subpath "/usr/sbin") (subpath "/usr/libexec") (subpath "/usr/share") (subpath "/private/var/select") (literal "/private/var/db/xcode_select_link"))',
|
|
5
5
|
'(allow file-read-metadata (path-ancestors "/opt/homebrew/bin") (path-ancestors "/usr/local/bin") (path-ancestors "/Library/Developer/CommandLineTools"))',
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{Do}from"./vm-hands-entry-lite-nqdstx24.js";import{Fe,an,Tt,cn}from"./vm-hands-entry-lite-f62fvme8.js";import{Qn}from"./vm-hands-entry-lite-ezbs3nn1.js";import{t,o,d,u,i,cs,W,g,s,n}from"./vm-hands-entry-lite-gvjffc5t.js";var M=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function k(e){let r=typeof e==="string"?M.exec(e):null;return r?{major:Number(r[1]),minor:Number(r[2])}:null}var E=25,v=1e5,L=/^[0-9a-f]{64}$/,N=i({day:t().regex(/^\d{4}-\d{2}-\d{2}$/),sent:o().int().min(0).max(v),received:o().int().min(0).max(v)}),xe=i({machine:t().min(1).max(200),person:t().min(1).max(200),team:t().min(1).max(200),team_id:t().min(1).max(200).optional(),workspace:d().optional(),version:t().max(64).optional(),wait_seconds:o().int().min(0).max(E).optional(),message_counts:u(N).max(14).optional().catch(void 0),endpoint:t().regex(L).optional().catch(void 0)}),D=g("kind",[i({id:t(),kind:n("who"),all:d().optional()}),i({id:t(),kind:n("send"),to:t(),body:t(),from_name:t(),from_agent:t(),wake:d(),reply_to:t().max(100).optional(),notify:d().optional()})]),P=i({job:D.nullable(),retry_after_seconds:o().optional()}),H=i({address:t(),person:t(),machine:t(),agent:t(),repo:t().nullable(),branch:t().nullable(),status:t(),since:o().nullable(),doing:t().nullable(),worker:d(),tier:t().max(10).optional()}),B=i({person:t(),machine:t(),online:d()}),F=i({team:t().nullable(),sessions:u(H).max(2000),machines:u(B).max(500),all:d().optional()}),J=i({address:t().max(300),state:t().max(40),note:t().max(500)}),Ie=W([i({who:F}),i({sent:i({ids:u(t().max(100)).max(500),recipients:u(t().max(300)).max(500),from:t().max(300),deliveries:u(J).max(500).optional()})}),i({error:t().min(1).max(2000)})]),G=i({id:t().max(100),from:t().max(300),from_agent:t().max(100).nullable(),to:t().max(300),reply_to:t().max(100).nullable(),body:t().max(64000),sent_at:o()}),Ce=i({messages:u(G).max(100),team:t().min(1).max(200).optional(),team_id:t().min(1).max(200).optional(),workspace:d().optional()});var x=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var Be=x.filter((e)=>e!=="network:read"&&e!=="network:write");class R extends Error{oauthCode;constructor(e,r=null){super(e);this.oauthCode=r;this.name="LoginError"}}function Q(e,r){let a=typeof e.error==="string"?e.error:null,l=typeof e.error_description==="string"?e.error_description:a?a:r;return new R(l,a)}async function K(e,r,a,l){let c=await a(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:r,signal:l}),m=await c.json().catch(()=>({}));if(!c.ok)throw Q(m,`OAuth token request failed (${c.status})`);return m}var V=1e4;async function Y(e,r={}){let a=r.fetchImpl??fetch,l=await K(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),a,AbortSignal.timeout(V)).catch((m)=>{if(m instanceof Error&&m.name==="TimeoutError")throw new R("Reason did not answer the login refresh in time. Check the network and retry.");throw m});if(typeof l.access_token!=="string"||typeof l.refresh_token!=="string"||typeof l.expires_in!=="number")throw new R("Reason returned an incomplete refreshed login.");let c={...e,accessToken:l.access_token,refreshToken:l.refresh_token,expiresAt:new Date(Date.now()+l.expires_in*1000).toISOString(),scopes:typeof l.scope==="string"?l.scope.split(/\s+/).filter(Boolean):e.scopes};return an(c,r.path??Fe()),c}var b=new Map,X=2000,Z=100;function C(e,r){if(!r)return e;if(r.aborted)return Promise.reject(r.reason);return new Promise((a,l)=>{let c=()=>l(r.reason);r.addEventListener("abort",c,{once:!0}),e.then(a,l).finally(()=>r.removeEventListener("abort",c))})}async function Pt(e={}){let r=e.path??Fe(),a=Tt(r);if(!a)return null;let l=e.apiOrigin??T(process.env,"REASON_API_URL")?.trim();if(l&&!Do(a.apiOrigin,new URL(l).origin))return null;if(!(Date.parse(a.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&a.accessToken!==e.refused))return a;let m=[r,a.apiOrigin,a.clientId,a.refreshToken].join("\x00"),p=b.get(m);if(p)return C(p,e.signal);let f;return f=Y(a,{fetchImpl:e.fetchImpl,path:r}).catch(async(y)=>{if(!(y instanceof R)||y.oauthCode!=="invalid_grant"&&y.oauthCode!=="invalid_client")throw y;let S=(_)=>_!==null&&(y.oauthCode==="invalid_client"?_.clientId!==a.clientId:_.refreshToken!==a.refreshToken),z=Date.now()+X;while(!S(Tt(r))&&Date.now()<z)await new Promise((_)=>setTimeout(_,Z));if(S(Tt(r)))return Pt({fetchImpl:e.fetchImpl,path:r});return cn(r),null}).finally(()=>{if(b.get(m)===f)b.delete(m)}),b.set(m,f),C(f,e.signal)}var ee=i({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:d().nullable()}),ne=i({groups:u(i({selectable:d().optional(),accounts:u(i({source_id:t().min(1),model_ids:u(t().min(1)).optional()}))}))});function te(e){let r=ne.safeParse(e);if(!r.success)return;return r.data.groups.some((a)=>a.selectable!==!1&&a.accounts.some((l)=>l.model_ids===void 0||l.model_ids.length>0))}class I extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor(e,r,a,l,c,m){super(a);this.status=e;this.code=r;this.suggestedModel=l;this.retryAfterMs=c;this.resolutionReason=m;this.name="ApiError"}static rateLimitDelayMs(e,r){if(!(e instanceof I)||e.status!==429)return null;return Math.min(60000,Math.max(r,e.retryAfterMs??0))}}var se=["minimal","low","medium","high","xhigh","max"],oe=i({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:d(),compatible:d().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:u(i({id:t().min(1),label:t()}))}),re=i({devices:u(oe),end_cursor:t().nullish(),has_next_page:d().optional()}),ie=i({id:t().min(1),name:t()}),ae=i({items:u(ie)}),le=i({id:t().min(1),name:t(),main:d(),mine:d(),session_id:t().nullish(),appearance:i({color:t().nullish()}).nullish().catch(null)}),ce=i({items:u(le)}),de=i({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:u(t()).default([]),is_enabled:d().default(!0)}),me=i({items:u(de).default([])}),ue=i({id:t().min(1),kind:t(),enabled:d(),schedule:i({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:i({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),U=i({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:d(),triggers:u(ue).default([])}),ge=i({items:u(U).default([]),end_cursor:t().nullish(),has_next_page:d().optional()}),he=i({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:d()}),pe=i({items:u(he).default([])}),fe=i({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),A=i({tags:u(t()).default([])}),ye=s(["linux","macos"]),q=i({id:t().min(1),name:t().min(1),platform:ye.nullable(),workers:i({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:i({queued:o().int(),running:o().int()})}),_e=i({machines:u(q)}),Re=i({machine:q}),be=i({deleted:n(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),we=i({token:i({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),O=cs({machine_id:t().min(1),machine_name:t().min(1)}),Se=O.extend({organization_id:t().min(1)}),Ye=i({id:t().min(1),name:t().min(1),state:s(["waiting","placed"]),queue_position:o().int().nullable()});var Xe=W([i({kind:n("cloud")}),i({kind:s(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function h(e,r,a){let l=e.safeParse(r);if(!l.success)throw new I(502,a,"Reason returned an unexpected response.");return l.data}var ke=i({error:i({type:t(),message:t()})});function w(e,r,a){let l=ke.safeParse(r),c=typeof r.error==="string"?r.error:l.success?l.data.error.type:`http_${e}`,m=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:l.success?l.data.error.message:`Reason request failed (${e}${typeof r.error==="string"?` ${r.error}`:""})`,p=c==="github_connection_required"&&typeof r.connect_url==="string"&&/^https?:\/\//.test(r.connect_url)?` Connect it at ${r.connect_url}`:"",f=a===null||a.trim()===""?NaN:Number(a);return new I(e,c,`${m}${p}`,typeof r.suggested_model==="string"?r.suggested_model:void 0,Number.isFinite(f)&&f>=0?f*1000:void 0,typeof r.resolution_reason==="string"?r.resolution_reason:void 0)}async function bs(e){let r=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),a=await r.json().catch(()=>({}));if(!r.ok)throw w(r.status,a,r.headers.get("retry-after"));return h(Se,a,"invalid_machine_ticket")}class Ko{options;credentials;constructor(e,r={}){this.options=r;this.credentials=e}trackEvent(e,r={}){}async request(e,r={}){let{status:a,headers:l,json:c}=await this.exchange(e,r);if(a<200||a>299)throw w(a,c,l.get("retry-after"));return c}async exchange(e,r={},a=!1){let l=this.options.fetchImpl??fetch,c=await l(`${this.credentials.apiOrigin}/v3${e}`,{method:r.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Qn,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...r.raw?{"content-type":r.raw.contentType}:r.body===void 0?{}:{"content-type":"application/json"},...r.headers,...r.ifNoneMatch?{"if-none-match":r.ifNoneMatch}:{}},body:r.raw?r.raw.bytes:r.body===void 0?void 0:JSON.stringify(r.body),signal:r.signal,redirect:r.ifNoneMatch?"manual":"error"}),m=await c.json().catch(()=>({}));if(c.status===401&&!a&&r.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let p=await Pt({fetchImpl:l,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:r.signal});if(p)return this.credentials=p,this.exchange(e,r,!0)}return{status:c.status,headers:c.headers,json:m}}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(r){if(r instanceof I&&(r.status===404||r.status===405||r.status===403&&r.code==="endpoint_not_available"))return null;throw r}}addDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(r)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,r=""){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?a:`${a}/${encodeURIComponent(e)}${r}`}async listMachines(){return h(_e,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let r=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return h(Re,r,"invalid_machine").machine}async deleteMachine(e){let r=await this.request(this.machinePath(e),{method:"DELETE"});return h(be,r,"invalid_machine_deletion")}async createMachineToken(e){let r=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return h(we,r,"invalid_machine_token")}async createMachineEnrollmentTicket(e,r){let a=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:r,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return h(O,a,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:r});return h(P,a,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((r)=>typeof r.email==="string"?[{email:r.email,role:typeof r.role==="string"?r.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,r,a={}){let l=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:a.retryUnauthorized,signal:a.signal,body:{...l,...r?{account_key:r}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((r)=>{let a=typeof r.full_name==="string"?r.full_name:typeof r.repo_full_name==="string"?r.repo_full_name:null;if(!a)return[];return[{repo_id:typeof r.repo_id==="string"?r.repo_id:void 0,full_name:a,provider:r.provider==="gitlab"?"gitlab":"github",default_branch:typeof r.default_branch==="string"?r.default_branch:null,private:typeof r.private==="boolean"?r.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),r=ae.safeParse(e);if(!r.success)throw new I(502,"invalid_project_list","Reason returned an unexpected project list.");return r.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return h(ce,e,"invalid_reason_list").items}async openReasonConversation(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return h(i({session_id:t().min(1)}),r,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return h(me,e,"invalid_skill_list").items}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${r?`?after=${encodeURIComponent(r)}`:""}`),c=re.safeParse(l);if(!c.success)throw new I(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...c.data.devices),r=c.data.has_next_page?c.data.end_cursor??null:null,!r)break}return e}async listModels(){try{let r=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((c)=>c.hidden!==!0),a=r.filter((c)=>c.available!==!1).map(({reasoning_efforts:c,hidden:m,available:p,...f})=>({...f,...Array.isArray(c)?{reasoning_efforts:se.filter((y)=>c.includes(y))}:{}})),l=new Set(a.map((c)=>c.detail));return{models:a.length>1&&l.size===1?a.map(({detail:c,...m})=>m):a,runnable:a.length>0||r.length===0}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let r=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return k(r.reason_version)?r.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=ee.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let r;try{r=te(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:r}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let r=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)r.set("origin",e.origin);r.set("fields",e.fields.join(","));let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${r.toString()}`,{status:l,headers:c,json:m}=await this.exchange(a,e.etag?{ifNoneMatch:e.etag}:{});if(l===304)return null;if(l<200||l>299)throw w(l,m,c.get("retry-after"));return{items:Array.isArray(m.items)?m.items:[],etag:c.get("etag")}}async listSessions(e=50,r,a={}){let l=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:a.status??"active"});if(r)l.set("project_id",r);if(a.origin)l.set("origin",a.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${l.toString()}`)).items??[]}getSession(e,r){let a=r?.fields.length?`?fields=${encodeURIComponent(r.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${a}`)}async prestartSession(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return r?.status==="starting"||r?.status==="ready"}async createSession(e){let r=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(r||e.runtimeProfile){let c=await this.request("/deployment");if(r&&(!Array.isArray(c.session_modes)||!c.session_modes.includes(e.mode??"standard")||!Array.isArray(c.workspace_ownerships)||!c.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(c.experimental_runtime_profiles)||!c.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),l=await this.getSession(a.session_id);if(r){let c=l.session_policy,m=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!c||c.version!==1||c.mode!==(e.mode??"standard")||c.workspaceOwnership!==(e.workspaceOwnership??"managed")||!c.components||m.some((p)=>c.components[p]!==!0))throw await this.cancelSession(a.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&l.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(a.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return l}async getEvents(e,r=-1,a={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${r}&limit=500${a.waitMs?`&wait_ms=${a.waitMs}`:""}`,a.signal?{signal:a.signal}:{})}catch(l){if(!(l instanceof I)||l.status!==403&&l.status!==404)throw l;return{session:await this.getSession(e),items:[],next_seq:r}}}async getMessages(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${r===void 0?"":`&after_seq=${r}`}`)}async getAttachments(e,r){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${r?`?view=${r}`:""}`)).items??[]}catch(a){if(a instanceof I&&(a.status===403||a.status===404))return[];throw a}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let r=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,a=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,l=[r,a].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${l?` (${l})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,r,a={}){if(a.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:r,...a.attachments?.length?{attachments:a.attachments}:{},...a.model?{model:a.model}:{},...a.reasoningEffort?{reasoning_effort:a.reasoningEffort}:{},...a.target?{target:a.target}:{},...a.delivery?{delivery:a.delivery}:{}}})}async steerQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/queued`,{method:"DELETE"})}async getConversation(e){let r=[],a=null;for(let l=0;l<50;l+=1){let c=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${a?`?after=${encodeURIComponent(a)}`:""}`);if(r.push(...c.items??[]),!c.has_next_page||!c.end_cursor)break;a=c.end_cursor}return r}createSharedLink(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:r.url,...r.label?{label:r.label}:{},...r.expiresInSeconds!==void 0?{expires_in_seconds:r.expiresInSeconds}:{}}})}sessionAction(e,r,a={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${r}`,{method:"POST",body:a})}renameSession(e,r){return this.sessionAction(e,"rename",{title:r||null})}moveSessionToProject(e,r){return this.sessionAction(e,"project",{project_id:r})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,r){return this.sessionAction(e,"rewind",{message_id:r.messageId,content:r.content,request_id:r.requestId})}forkSession(e,r){return this.sessionAction(e,"fork",{...r.message?{message:r.message}:{},client_session_id:r.clientSessionId})}cancelSession(e,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:r.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,r=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return h(A,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,r){let a=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:r}});return h(A,a,"invalid_session_tags").tags}async sessionInsight(e,r=!1){let a=await this.request(this.sessionPath(e,r?"/insights/generate":"/insights"),r?{method:"POST",body:{}}:{});return h(fe,a,"invalid_session_insight")}async listAutomations(){let e=[],r=null;for(let a=0;a<20;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${r?`&after=${encodeURIComponent(r)}`:""}`),c=h(ge,l,"invalid_automation_list");if(e.push(...c.items),r=c.has_next_page?c.end_cursor??null:null,!r)break}return e}async createScheduledAutomation(e,r){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,l=h(U,await this.request(a,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${a}/${encodeURIComponent(l.id)}/triggers`,{method:"POST",body:r})}catch(c){throw await this.deleteAutomation(l.id).catch(()=>{return}),c}return l}async setAutomationEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:r}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:r}});return h(i({transcript:t()}),a,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return h(pe,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:r}})}}
|
|
2
|
+
import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{Do}from"./vm-hands-entry-lite-nqdstx24.js";import{Fe,an,Tt,cn}from"./vm-hands-entry-lite-f62fvme8.js";import{Qn}from"./vm-hands-entry-lite-znd9c7x0.js";import{t,o,d,u,i,cs,W,g,s,n}from"./vm-hands-entry-lite-gvjffc5t.js";var M=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function k(e){let r=typeof e==="string"?M.exec(e):null;return r?{major:Number(r[1]),minor:Number(r[2])}:null}var E=25,v=1e5,L=/^[0-9a-f]{64}$/,N=i({day:t().regex(/^\d{4}-\d{2}-\d{2}$/),sent:o().int().min(0).max(v),received:o().int().min(0).max(v)}),xe=i({machine:t().min(1).max(200),person:t().min(1).max(200),team:t().min(1).max(200),team_id:t().min(1).max(200).optional(),workspace:d().optional(),version:t().max(64).optional(),wait_seconds:o().int().min(0).max(E).optional(),message_counts:u(N).max(14).optional().catch(void 0),endpoint:t().regex(L).optional().catch(void 0)}),D=g("kind",[i({id:t(),kind:n("who"),all:d().optional()}),i({id:t(),kind:n("send"),to:t(),body:t(),from_name:t(),from_agent:t(),wake:d(),reply_to:t().max(100).optional(),notify:d().optional()})]),P=i({job:D.nullable(),retry_after_seconds:o().optional()}),H=i({address:t(),person:t(),machine:t(),agent:t(),repo:t().nullable(),branch:t().nullable(),status:t(),since:o().nullable(),doing:t().nullable(),worker:d(),tier:t().max(10).optional()}),B=i({person:t(),machine:t(),online:d()}),F=i({team:t().nullable(),sessions:u(H).max(2000),machines:u(B).max(500),all:d().optional()}),J=i({address:t().max(300),state:t().max(40),note:t().max(500)}),Ie=W([i({who:F}),i({sent:i({ids:u(t().max(100)).max(500),recipients:u(t().max(300)).max(500),from:t().max(300),deliveries:u(J).max(500).optional()})}),i({error:t().min(1).max(2000)})]),G=i({id:t().max(100),from:t().max(300),from_agent:t().max(100).nullable(),to:t().max(300),reply_to:t().max(100).nullable(),body:t().max(64000),sent_at:o()}),Ce=i({messages:u(G).max(100),team:t().min(1).max(200).optional(),team_id:t().min(1).max(200).optional(),workspace:d().optional()});var x=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var Be=x.filter((e)=>e!=="network:read"&&e!=="network:write");class R extends Error{oauthCode;constructor(e,r=null){super(e);this.oauthCode=r;this.name="LoginError"}}function Q(e,r){let a=typeof e.error==="string"?e.error:null,l=typeof e.error_description==="string"?e.error_description:a?a:r;return new R(l,a)}async function K(e,r,a,l){let c=await a(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:r,signal:l}),m=await c.json().catch(()=>({}));if(!c.ok)throw Q(m,`OAuth token request failed (${c.status})`);return m}var V=1e4;async function Y(e,r={}){let a=r.fetchImpl??fetch,l=await K(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),a,AbortSignal.timeout(V)).catch((m)=>{if(m instanceof Error&&m.name==="TimeoutError")throw new R("Reason did not answer the login refresh in time. Check the network and retry.");throw m});if(typeof l.access_token!=="string"||typeof l.refresh_token!=="string"||typeof l.expires_in!=="number")throw new R("Reason returned an incomplete refreshed login.");let c={...e,accessToken:l.access_token,refreshToken:l.refresh_token,expiresAt:new Date(Date.now()+l.expires_in*1000).toISOString(),scopes:typeof l.scope==="string"?l.scope.split(/\s+/).filter(Boolean):e.scopes};return an(c,r.path??Fe()),c}var b=new Map,X=2000,Z=100;function C(e,r){if(!r)return e;if(r.aborted)return Promise.reject(r.reason);return new Promise((a,l)=>{let c=()=>l(r.reason);r.addEventListener("abort",c,{once:!0}),e.then(a,l).finally(()=>r.removeEventListener("abort",c))})}async function Pt(e={}){let r=e.path??Fe(),a=Tt(r);if(!a)return null;let l=e.apiOrigin??T(process.env,"REASON_API_URL")?.trim();if(l&&!Do(a.apiOrigin,new URL(l).origin))return null;if(!(Date.parse(a.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&a.accessToken!==e.refused))return a;let m=[r,a.apiOrigin,a.clientId,a.refreshToken].join("\x00"),p=b.get(m);if(p)return C(p,e.signal);let f;return f=Y(a,{fetchImpl:e.fetchImpl,path:r}).catch(async(y)=>{if(!(y instanceof R)||y.oauthCode!=="invalid_grant"&&y.oauthCode!=="invalid_client")throw y;let S=(_)=>_!==null&&(y.oauthCode==="invalid_client"?_.clientId!==a.clientId:_.refreshToken!==a.refreshToken),z=Date.now()+X;while(!S(Tt(r))&&Date.now()<z)await new Promise((_)=>setTimeout(_,Z));if(S(Tt(r)))return Pt({fetchImpl:e.fetchImpl,path:r});return cn(r),null}).finally(()=>{if(b.get(m)===f)b.delete(m)}),b.set(m,f),C(f,e.signal)}var ee=i({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:d().nullable()}),ne=i({groups:u(i({selectable:d().optional(),accounts:u(i({source_id:t().min(1),model_ids:u(t().min(1)).optional()}))}))});function te(e){let r=ne.safeParse(e);if(!r.success)return;return r.data.groups.some((a)=>a.selectable!==!1&&a.accounts.some((l)=>l.model_ids===void 0||l.model_ids.length>0))}class I extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor(e,r,a,l,c,m){super(a);this.status=e;this.code=r;this.suggestedModel=l;this.retryAfterMs=c;this.resolutionReason=m;this.name="ApiError"}static rateLimitDelayMs(e,r){if(!(e instanceof I)||e.status!==429)return null;return Math.min(60000,Math.max(r,e.retryAfterMs??0))}}var se=["minimal","low","medium","high","xhigh","max"],oe=i({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:d(),compatible:d().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:u(i({id:t().min(1),label:t()}))}),re=i({devices:u(oe),end_cursor:t().nullish(),has_next_page:d().optional()}),ie=i({id:t().min(1),name:t()}),ae=i({items:u(ie)}),le=i({id:t().min(1),name:t(),main:d(),mine:d(),session_id:t().nullish(),appearance:i({color:t().nullish()}).nullish().catch(null)}),ce=i({items:u(le)}),de=i({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:u(t()).default([]),is_enabled:d().default(!0)}),me=i({items:u(de).default([])}),ue=i({id:t().min(1),kind:t(),enabled:d(),schedule:i({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:i({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),U=i({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:d(),triggers:u(ue).default([])}),ge=i({items:u(U).default([]),end_cursor:t().nullish(),has_next_page:d().optional()}),he=i({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:d()}),pe=i({items:u(he).default([])}),fe=i({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),A=i({tags:u(t()).default([])}),ye=s(["linux","macos"]),q=i({id:t().min(1),name:t().min(1),platform:ye.nullable(),workers:i({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:i({queued:o().int(),running:o().int()})}),_e=i({machines:u(q)}),Re=i({machine:q}),be=i({deleted:n(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),we=i({token:i({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),O=cs({machine_id:t().min(1),machine_name:t().min(1)}),Se=O.extend({organization_id:t().min(1)}),Ye=i({id:t().min(1),name:t().min(1),state:s(["waiting","placed"]),queue_position:o().int().nullable()});var Xe=W([i({kind:n("cloud")}),i({kind:s(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function h(e,r,a){let l=e.safeParse(r);if(!l.success)throw new I(502,a,"Reason returned an unexpected response.");return l.data}var ke=i({error:i({type:t(),message:t()})});function w(e,r,a){let l=ke.safeParse(r),c=typeof r.error==="string"?r.error:l.success?l.data.error.type:`http_${e}`,m=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:l.success?l.data.error.message:`Reason request failed (${e}${typeof r.error==="string"?` ${r.error}`:""})`,p=c==="github_connection_required"&&typeof r.connect_url==="string"&&/^https?:\/\//.test(r.connect_url)?` Connect it at ${r.connect_url}`:"",f=a===null||a.trim()===""?NaN:Number(a);return new I(e,c,`${m}${p}`,typeof r.suggested_model==="string"?r.suggested_model:void 0,Number.isFinite(f)&&f>=0?f*1000:void 0,typeof r.resolution_reason==="string"?r.resolution_reason:void 0)}async function bs(e){let r=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),a=await r.json().catch(()=>({}));if(!r.ok)throw w(r.status,a,r.headers.get("retry-after"));return h(Se,a,"invalid_machine_ticket")}class Ko{options;credentials;constructor(e,r={}){this.options=r;this.credentials=e}trackEvent(e,r={}){}async request(e,r={}){let{status:a,headers:l,json:c}=await this.exchange(e,r);if(a<200||a>299)throw w(a,c,l.get("retry-after"));return c}async exchange(e,r={},a=!1){let l=this.options.fetchImpl??fetch,c=await l(`${this.credentials.apiOrigin}/v3${e}`,{method:r.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Qn,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...r.raw?{"content-type":r.raw.contentType}:r.body===void 0?{}:{"content-type":"application/json"},...r.headers,...r.ifNoneMatch?{"if-none-match":r.ifNoneMatch}:{}},body:r.raw?r.raw.bytes:r.body===void 0?void 0:JSON.stringify(r.body),signal:r.signal,redirect:r.ifNoneMatch?"manual":"error"}),m=await c.json().catch(()=>({}));if(c.status===401&&!a&&r.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let p=await Pt({fetchImpl:l,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:r.signal});if(p)return this.credentials=p,this.exchange(e,r,!0)}return{status:c.status,headers:c.headers,json:m}}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(r){if(r instanceof I&&(r.status===404||r.status===405||r.status===403&&r.code==="endpoint_not_available"))return null;throw r}}addDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(r)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,r=""){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?a:`${a}/${encodeURIComponent(e)}${r}`}async listMachines(){return h(_e,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let r=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return h(Re,r,"invalid_machine").machine}async deleteMachine(e){let r=await this.request(this.machinePath(e),{method:"DELETE"});return h(be,r,"invalid_machine_deletion")}async createMachineToken(e){let r=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return h(we,r,"invalid_machine_token")}async createMachineEnrollmentTicket(e,r){let a=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:r,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return h(O,a,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:r});return h(P,a,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((r)=>typeof r.email==="string"?[{email:r.email,role:typeof r.role==="string"?r.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,r,a={}){let l=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:a.retryUnauthorized,signal:a.signal,body:{...l,...r?{account_key:r}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((r)=>{let a=typeof r.full_name==="string"?r.full_name:typeof r.repo_full_name==="string"?r.repo_full_name:null;if(!a)return[];return[{repo_id:typeof r.repo_id==="string"?r.repo_id:void 0,full_name:a,provider:r.provider==="gitlab"?"gitlab":"github",default_branch:typeof r.default_branch==="string"?r.default_branch:null,private:typeof r.private==="boolean"?r.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),r=ae.safeParse(e);if(!r.success)throw new I(502,"invalid_project_list","Reason returned an unexpected project list.");return r.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return h(ce,e,"invalid_reason_list").items}async openReasonConversation(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return h(i({session_id:t().min(1)}),r,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return h(me,e,"invalid_skill_list").items}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${r?`?after=${encodeURIComponent(r)}`:""}`),c=re.safeParse(l);if(!c.success)throw new I(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...c.data.devices),r=c.data.has_next_page?c.data.end_cursor??null:null,!r)break}return e}async listModels(){try{let r=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((c)=>c.hidden!==!0),a=r.filter((c)=>c.available!==!1).map(({reasoning_efforts:c,hidden:m,available:p,...f})=>({...f,...Array.isArray(c)?{reasoning_efforts:se.filter((y)=>c.includes(y))}:{}})),l=new Set(a.map((c)=>c.detail));return{models:a.length>1&&l.size===1?a.map(({detail:c,...m})=>m):a,runnable:a.length>0||r.length===0}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let r=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return k(r.reason_version)?r.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=ee.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let r;try{r=te(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:r}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let r=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)r.set("origin",e.origin);r.set("fields",e.fields.join(","));let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${r.toString()}`,{status:l,headers:c,json:m}=await this.exchange(a,e.etag?{ifNoneMatch:e.etag}:{});if(l===304)return null;if(l<200||l>299)throw w(l,m,c.get("retry-after"));return{items:Array.isArray(m.items)?m.items:[],etag:c.get("etag")}}async listSessions(e=50,r,a={}){let l=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:a.status??"active"});if(r)l.set("project_id",r);if(a.origin)l.set("origin",a.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${l.toString()}`)).items??[]}getSession(e,r){let a=r?.fields.length?`?fields=${encodeURIComponent(r.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${a}`)}async prestartSession(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return r?.status==="starting"||r?.status==="ready"}async createSession(e){let r=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(r||e.runtimeProfile){let c=await this.request("/deployment");if(r&&(!Array.isArray(c.session_modes)||!c.session_modes.includes(e.mode??"standard")||!Array.isArray(c.workspace_ownerships)||!c.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(c.experimental_runtime_profiles)||!c.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),l=await this.getSession(a.session_id);if(r){let c=l.session_policy,m=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!c||c.version!==1||c.mode!==(e.mode??"standard")||c.workspaceOwnership!==(e.workspaceOwnership??"managed")||!c.components||m.some((p)=>c.components[p]!==!0))throw await this.cancelSession(a.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&l.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(a.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return l}async getEvents(e,r=-1,a={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${r}&limit=500${a.waitMs?`&wait_ms=${a.waitMs}`:""}`,a.signal?{signal:a.signal}:{})}catch(l){if(!(l instanceof I)||l.status!==403&&l.status!==404)throw l;return{session:await this.getSession(e),items:[],next_seq:r}}}async getMessages(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${r===void 0?"":`&after_seq=${r}`}`)}async getAttachments(e,r){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${r?`?view=${r}`:""}`)).items??[]}catch(a){if(a instanceof I&&(a.status===403||a.status===404))return[];throw a}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let r=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,a=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,l=[r,a].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${l?` (${l})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,r,a={}){if(a.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:r,...a.attachments?.length?{attachments:a.attachments}:{},...a.model?{model:a.model}:{},...a.reasoningEffort?{reasoning_effort:a.reasoningEffort}:{},...a.target?{target:a.target}:{},...a.delivery?{delivery:a.delivery}:{}}})}async steerQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/queued`,{method:"DELETE"})}async getConversation(e){let r=[],a=null;for(let l=0;l<50;l+=1){let c=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${a?`?after=${encodeURIComponent(a)}`:""}`);if(r.push(...c.items??[]),!c.has_next_page||!c.end_cursor)break;a=c.end_cursor}return r}createSharedLink(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:r.url,...r.label?{label:r.label}:{},...r.expiresInSeconds!==void 0?{expires_in_seconds:r.expiresInSeconds}:{}}})}sessionAction(e,r,a={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${r}`,{method:"POST",body:a})}renameSession(e,r){return this.sessionAction(e,"rename",{title:r||null})}moveSessionToProject(e,r){return this.sessionAction(e,"project",{project_id:r})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,r){return this.sessionAction(e,"rewind",{message_id:r.messageId,content:r.content,request_id:r.requestId})}forkSession(e,r){return this.sessionAction(e,"fork",{...r.message?{message:r.message}:{},client_session_id:r.clientSessionId})}cancelSession(e,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:r.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,r=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return h(A,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,r){let a=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:r}});return h(A,a,"invalid_session_tags").tags}async sessionInsight(e,r=!1){let a=await this.request(this.sessionPath(e,r?"/insights/generate":"/insights"),r?{method:"POST",body:{}}:{});return h(fe,a,"invalid_session_insight")}async listAutomations(){let e=[],r=null;for(let a=0;a<20;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${r?`&after=${encodeURIComponent(r)}`:""}`),c=h(ge,l,"invalid_automation_list");if(e.push(...c.items),r=c.has_next_page?c.end_cursor??null:null,!r)break}return e}async createScheduledAutomation(e,r){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,l=h(U,await this.request(a,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${a}/${encodeURIComponent(l.id)}/triggers`,{method:"POST",body:r})}catch(c){throw await this.deleteAutomation(l.id).catch(()=>{return}),c}return l}async setAutomationEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:r}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:r}});return h(i({transcript:t()}),a,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return h(pe,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:r}})}}
|
|
3
3
|
export{Pt,I,bs,Ko};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Qe}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Qe}from"./vm-hands-entry-lite-znd9c7x0.js";import{a}from"./vm-hands-entry-lite-swrymqj9.js";import{randomUUID as L}from"crypto";import{spawnSync as b}from"child_process";import{chmodSync as ee,cpSync as te,existsSync as x,lstatSync as A,mkdirSync as Y,readdirSync as ne,readFileSync as w,readlinkSync as re,realpathSync as T,renameSync as E,rmdirSync as ie,rmSync as g,symlinkSync as M,writeFileSync as oe}from"fs";import{dirname as I,join as u,relative as se,resolve as ce}from"path";var Xn="so.ara.cli",k=[Xn,"com.reasonmachines.cli"],F="5LJFSBRY2F";function Vr(e){return`(${e.map((t)=>`identifier "${t}"`).join(" or ")}) and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = "${F}"`}var G="ReasonBackgroundIdentity",To="Contents/Helpers/ReasonPermissionTile",ae="so.ara.cli.permission-tile",Ne=Vr([ae,"com.reasonmachines.cli.permission-tile"]),v="AraBackgroundIdentity",ue="Reason",Ce=Vr(k),de=`anchor apple generic and (${k.map((e)=>`identifier "${e}"`).join(" or ")}) and certificate leaf[subject.OU] = "${F}"`;class h extends Error{code;constructor(e,t){super(t);this.code=e;this.name="MacOSBackgroundIdentityError"}}var R="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";function le(e=a()){return u(e,"Library","Application Support","Reason","Background","Reason.app")}function O(e=a()){return u(e,"Library","Application Support","Ara","Background","Ara.app")}function fe(e){try{return A(e).isFile()}catch{return!1}}function D(e){return[G,v].map((t)=>u(e,"Contents","MacOS",t)).find(fe)??null}function d(e){try{if(!A(e).isDirectory())return!1;let t=w(u(e,"Contents","Info.plist"),"utf8");return k.some((n)=>t.includes(`<string>${n}</string>`))&&(t.includes(`<string>${ue}</string>`)||t.includes("<string>Ara</string>"))&&D(e)!==null}catch{return!1}}function Gr(e=a()){let t=le(e);if(!d(t))return null;try{let n=w(u(t,"Contents","Info.plist"),"utf8");return/<key>CFBundleVersion<\/key>\s*<string>(\d+\.\d+\.\d+)<\/string>/.exec(n)?.[1]??null}catch{return null}}function pe(e,t=a()){let n=Gr(t);return n===null||j(N(n.split(".")),N(e.split(/[.-]/).slice(0,3)))}var ge=1e4;function K(e,t){return b(e,[...t],{stdio:"ignore",timeout:ge}).status??1}var W=new Set;function H(e){if(process.env.REASON_TEST_REFUSE_REAL_IDENTITY!=="1")return;let t=(n)=>{try{return T(n)}catch{return ce(n)}};if(e!==void 0&&t(e)!==t(a()))return;throw Error("A test tried to change this computer's real Reason background identity; pass a temporary home. Refused by scripts/test-env.ts.")}var V=/\/(?:runtime|CLI)\/versions\/(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$|\/\.(?:ara|reason)(?:-staging)?-worker-(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$/,J=new Set(["ara","ara.exe","reason","reason.exe"]);function N(e){return e.map((t)=>Number(t))}function j(e,t){for(let n=0;n<3;n+=1)if(e[n]!==t[n])return e[n]<t[n];return!1}var ye=[0,2,161];function me(e){if(e===null)return!0;let t=ye,n=null;try{n=T(process.execPath)}catch{}return e.some((r)=>{let i=V.exec(r);if(i){let f=i[1]===void 0?i.slice(4,7):i.slice(1,4);return j(N(f),t)}let o=r.slice(r.lastIndexOf("/")+1);return J.has(o)&&r!==n&&r!==process.execPath})}function Ee(){let e=b("/bin/ps",["-xo","pid=,comm="],{encoding:"utf8",timeout:5000});if(e.status!==0)return null;let t=[];for(let n of e.stdout.split(`
|
|
3
3
|
`)){let r=/^\s*(\d+)\s+(\S.*)$/.exec(n);if(!r||Number(r[1])===process.pid)continue;let i=r[2].trimEnd(),o=i.slice(i.lastIndexOf("/")+1);if(!V.test(i)&&J.has(o)){let c=b("/usr/sbin/lsof",["-a","-p",r[1],"-d","txt","-Fn"],{encoding:"utf8",timeout:5000}).stdout?.split(`
|
|
4
4
|
`).find((l)=>l.startsWith("n/"));if(c)i=c.slice(1)}t.push(i)}return t}function _e(e){if(H(e.home),!d(e.sourceApp))throw new h("identity_invalid","The packaged Reason background identity is missing or invalid.");let t=e.command??K,n=le(e.home),r=I(n);Y(r,{recursive:!0,mode:448}),ee(r,448);let i=T(e.sourceApp),o=null;try{o=T(n)}catch{}if(i!==o){let f=`${process.pid}.${L()}`,c=u(r,`.Reason.app.${f}.tmp`),l=u(r,`.Reason.app.${f}.old`),y=!1;try{if(te(i,c,{recursive:!0,errorOnExist:!0,preserveTimestamps:!0}),!d(c))throw new h("identity_invalid","The copied Reason background identity is invalid.");let _=e.releaseSigned?["--test-requirement",`=${de}`]:[];if(t("/usr/bin/codesign",["--verify","--strict",..._,c])!==0)throw new h("identity_invalid_signature","The installed Reason background identity has an invalid signature.");let S=!1;for(let p=0;p<4;p+=1){let m=!1;try{E(n,l),m=!0,y=!0}catch(s){if(s.code!=="ENOENT")throw s}if(p===0)e.beforePublish?.();try{E(c,n),S=!0}catch(s){let Z=s.code;if(!["EEXIST","ENOTEMPTY"].includes(Z??""))throw s;if(m)g(l,{recursive:!0,force:!0}),y=!1;if(p===3)throw s;continue}if(m)g(l,{recursive:!0,force:!0}),y=!1;break}if(!S)throw Error("Could not publish Reason's background identity.")}catch(_){if(y&&!x(n)&&x(l))E(l,n);throw _}finally{g(c,{recursive:!0,force:!0}),g(l,{recursive:!0,force:!0})}}return z(n,e,{verified:i!==o}),n}function X(e){return u(I(e),".Reason.app.registered")}function q(e){try{let t=A(e);return t.isDirectory()?`${t.ino}:${t.birthtimeMs}`:null}catch{return null}}function C(e){let t=q(e);try{return t!==null&&w(X(e),"utf8")===t}catch{return!1}}function Q(e){if(d(e))return"bundle";try{if(A(u(e,"Contents","Info.plist"),{throwIfNoEntry:!1}))return null;return A(u(e,"Contents","MacOS",v)).isSymbolicLink()?"retired":null}catch{return null}}function z(e,t,n={}){let r=t.command??K;if(!n.verified&&r("/usr/bin/codesign",["--verify","--strict",e])!==0)throw new h("identity_invalid_signature","The installed Reason background identity has an invalid signature.");if(r(R,["-f",e])!==0)throw new h("identity_register_failed","Could not register Reason's macOS background identity.");let i=q(e);try{if(i)oe(X(e),i,{mode:384})}catch{}try{Se(e,t.home,r,t.runningExecutables??Ee)}catch(o){let f=o.code??"unknown";process.stderr.write(`Reason background identity: legacy_identity_retire_failed (${f})
|
|
5
5
|
`)}}function Se(e,t,n,r){let i=D(e);if(!i)return;let o=O(t),f=I(o),c=(s)=>u(s,"Contents","MacOS",v),l=se(I(c(o)),i),y=`${process.pid}.${L()}`,_=Q(o);if(_===null)return;let S=_==="bundle";if(S)n(R,["-u",o]);let p=u(f,`.Ara.app.${y}.old`);if(!W.has(o)&&!me(r())){if(!S)n(R,["-u",o]);try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}g(p,{recursive:!0,force:!0}),Ie(f);return}if(!S){if(re(c(o))===l)return;let s=`${c(o)}.${y}`;M(l,s);try{E(s,c(o))}finally{g(s,{force:!0})}return}let m=u(f,`.Ara.app.${y}.shim`);Y(I(c(m)),{recursive:!0}),M(l,c(m));try{try{E(o,p)}catch(s){if(s.code==="ENOENT")return;throw s}try{E(m,o)}catch(s){if(x(o))return;throw E(p,o),s}}finally{g(m,{recursive:!0,force:!0}),g(p,{recursive:!0,force:!0})}}function Ie(e){try{if(ne(e).some((n)=>n!==".DS_Store"))return;g(u(e,".DS_Store"),{force:!0}),ie(e)}catch{}}var B=new Map;function Yn(e=a()){let t=B.get(e);if(t)return t;if(process.platform!=="darwin")return[];let n=U(e);if(n===null&&x(I(le(e))))Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100),n=U(e);if(n===null)return[];return B.set(e,n),n}function U(e){let t=le(e),n=O(e);if(!d(t)||!C(t))try{he({home:e,skipWhenSettled:!0})}catch{}let r=d(t)&&(C(t)||!d(n))?t:d(n)?n:null,i=r?D(r):null;if(!i)return null;if(r===n)W.add(n);let o=b(i,["--can-spawn"],{env:{},timeout:2000,encoding:"utf8"});return o.status===0&&o.stdout===`spawn
|