@reason-machines/cli-linux-x64 0.2.497 → 0.2.498
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-5xx26tvk.js → api-credentials-pg2p63wf.js} +1 -1
- package/bin/vm-hands/{api-x5pnj1t0.js → api-mhfwgwta.js} +1 -1
- package/bin/vm-hands/{connect-cli-1p1cpd32.js → connect-cli-f7mc1dsg.js} +1 -1
- package/bin/vm-hands/{local-automation-psfea9xa.js → local-automation-xaw463w7.js} +1 -1
- package/bin/vm-hands/{local-capabilities-ht31wxxh.js → local-capabilities-wfsn6k14.js} +1 -1
- package/bin/vm-hands/{local-display-session-ygp5sjjx.js → local-display-session-bj7b9d1b.js} +1 -1
- package/bin/vm-hands/local-display-video-k6cgbwvr.js +2 -0
- package/bin/vm-hands/{local-managed-process-m5k2vf30.js → local-managed-process-h9jtheqj.js} +1 -1
- package/bin/vm-hands/{managed-runtime-mvk6fsfa.js → managed-runtime-skeavwha.js} +1 -1
- package/bin/vm-hands/{permissions-gm5mbzta.js → permissions-ryhxsf61.js} +1 -1
- package/bin/vm-hands/{serve-service-kp6pdwws.js → serve-service-mgc1s0aw.js} +1 -1
- package/bin/vm-hands/{status-wrrwbvgr.js → status-sk609adw.js} +1 -1
- package/bin/vm-hands/version-6msccfxa.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-02wn6p6x.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-gzgkwqa1.js → vm-hands-entry-lite-05f2f2js.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-h0hbf66n.js → vm-hands-entry-lite-3qvd7zm7.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-s8j3wddk.js → vm-hands-entry-lite-7q18275f.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-smydkbwh.js → vm-hands-entry-lite-hnfv3f4a.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-gax1z0jg.js → vm-hands-entry-lite-jcjrhjnp.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-0ryzp6d4.js → vm-hands-entry-lite-n1tzq55r.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-hnp7ngjm.js → vm-hands-entry-lite-n87t5867.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-fba99s5e.js → vm-hands-entry-lite-n8j4pad2.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-4etwkfpy.js → vm-hands-entry-lite-nmp8jvx3.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-z49rbkc5.js → vm-hands-entry-lite-nq72q3dm.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-z6954azn.js → vm-hands-entry-lite-pzv488sb.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-jz9neaxz.js → vm-hands-entry-lite-rzx4y4pj.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-8dk395ph.js → vm-hands-entry-lite-s8px62jm.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-xetb8qer.js → vm-hands-entry-lite-vsxzvjzy.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-02bxx7a9.js → vm-hands-entry-lite-yxph73md.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-4c4q3bw0.js → vm-hands-executor-20sm9njj.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-b46k10sj.js → vm-hands-op-runner-4bvnr7gn.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-0xpt9a97.js → vm-hands-runtime-b84m3a8j.js} +3 -3
- package/package.json +1 -1
- package/bin/vm-hands/local-display-video-x8gf02av.js +0 -2
- package/bin/vm-hands/version-dvaqvt0b.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-rp77m9ya.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{lt,Lt,Cr,kn,Ar,Cn,An,Pn}from"./vm-hands-entry-lite-64z2tjpg.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-9wa2y4x0.js";import{ue,Z,O}from"./vm-hands-entry-lite-38g65s5x.js";import{P,Jt}from"./vm-hands-entry-lite-dw558ggz.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-64z2tjpg.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-9wa2y4x0.js";import{ue,Z,O}from"./vm-hands-entry-lite-38g65s5x.js";import{P,Jt}from"./vm-hands-entry-lite-dw558ggz.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-3qvd7zm7.js";import{D,R,b}from"./vm-hands-entry-lite-3gztfxwt.js";import{Wi,Vi,fn,Gi,mn,Ki,it,dr}from"./vm-hands-entry-lite-rzx4y4pj.js";import{K}from"./vm-hands-entry-lite-8qhz89mt.js";import{He}from"./vm-hands-entry-lite-tebh7dcm.js";import{j}from"./vm-hands-entry-lite-gc7550c0.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-w0pegc58.js";import{Or,qt,Ir,jn,Un}from"./vm-hands-entry-lite-13rapgf5.js";import{$t,qe,Bt}from"./vm-hands-entry-lite-n1tzq55r.js";import{Ln,x,ho}from"./vm-hands-entry-lite-hnfv3f4a.js";import{fo,mo}from"./vm-hands-entry-lite-s8px62jm.js";import{Mt,Tn,Rn}from"./vm-hands-entry-lite-nmp8jvx3.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-a1xa7s06.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,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{Vr}from"./vm-hands-entry-lite-
|
|
2
|
+
import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{Vr}from"./vm-hands-entry-lite-jcjrhjnp.js";import{ft}from"./vm-hands-entry-lite-7777m86y.js";import{a}from"./vm-hands-entry-lite-swrymqj9.js";import{A}from"./vm-hands-entry-lite-87vmbt38.js";import{randomUUID as f}from"crypto";import{chmodSync as U,closeSync as h,constants as g,existsSync as me,fstatSync as F,lstatSync as R,mkdirSync as B,openSync as G,readFileSync as Y,readdirSync as z,readlinkSync as J,realpathSync as P,renameSync as _,rmSync as p,statSync as K,symlinkSync as _t,unlinkSync as M,writeFileSync as L}from"fs";import{basename as vt,dirname as S,isAbsolute as fe,join as c,relative as ge,resolve as b,sep as _e}from"path";import{createRequire as H}from"module";var q=1,j=1,ye=128,ve=65536;var he=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;var D=/^[a-z0-9_.-]{1,80}$/,be=64,Ee="so.ara.device-broker",Me=[Ee,"com.reasonmachines.device-broker"],Pt=Vr(Me);var we=["service.install_started","service.install_completed","service.install_failed","service.launcher_adopted","service.launcher_conflict","service.started","service.reconnecting","service.reconnected","service.idle_sleep_held","service.idle_sleep_released","service.idle_sleep_failed","service.start_failed","service.stopped","service.exit_failed","service.singleton_rejected","credential.migration_started","credential.migration_completed","credential.migration_failed","credential.store_started","credential.store_completed","credential.store_failed","credential.delete_started","credential.delete_completed","credential.delete_failed","update.check_started","update.not_available","update.download_started","update.downloaded","update.verified","update.activated","update.rollback","update.failed","executor.update.check_started","executor.update.not_available","executor.update.download_started","executor.update.downloaded","executor.update.verified","executor.update.activated","executor.update.rollback","executor.update.failed","identity.refresh_completed","identity.refresh_failed","update.device_moved","update.components_installed","update.deferred","update.deferral_expired","worker.previous_exit","worker.capabilities_withheld","identity.computer_use_unavailable"];function W(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function X(e,t,n=[]){let r=new Set([...t,...n]);return t.every((i)=>(i in e))&&Object.keys(e).every((i)=>r.has(i))}function E(e){return typeof e==="string"&&he.test(e)}function Z(e){return typeof e==="string"&&!Number.isNaN(Date.parse(e))&&new Date(e).toISOString()===e}function k(e){B(e,{recursive:!0,mode:448}),U(e,448)}function Re(e,t){k(S(e));let n=`${e}.${process.pid}.${f()}.tmp`;try{L(n,t,{mode:384,flag:"wx"}),U(n,384),_(n,e)}finally{if(me(n))M(n)}}function ys(e={}){if((e.platform??process.platform)!=="darwin")throw new ft("unsupported_platform","The managed Reason runtime is currently available only on macOS.");let n=e.environment??process.env,r=T(n,"REASON_CLI_CHANNEL")==="staging",i=r?T(n,"REASON_MANAGED_RUNTIME_ROOT")?.trim():void 0,o=e.root!==void 0||Boolean(i&&fe(i))?null:c(e.home??a(),"Library","Application Support"),d=e.root??(o?c(o,r?"Reason Staging":"Reason","CLI"):i);return{executableName:"reason",root:d,...o?{legacyRoot:c(o,"Ara",...r?["staging","runtime"]:["runtime"])}:{},versions:c(d,"versions"),current:c(d,"current"),previous:c(d,"previous"),brokerLock:c(d,"broker.lock"),transitionLock:c(d,"transition.lock"),lifecycleEvents:c(d,"lifecycle-events")}}function bs(e){let t=e.legacyRoot;if(!t)return null;return{root:t,versions:c(t,"versions"),current:c(t,"current"),previous:c(t,"previous"),brokerLock:c(t,"broker.lock"),transitionLock:c(t,"transition.lock"),lifecycleEvents:c(t,"lifecycle-events")}}function pe(e,t){let n;try{if(!R(e).isSymbolicLink())return null;n=J(e)}catch{return null}let r=n.match(/^versions\/(\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)\/(ara|Reason|reason)$/);return r&&(r[2]==="ara"||r[2]===t)?r[1]:null}function vs(e){return pe(e.current,e.executableName)}function O(e,t,n){let i=ge(t,e).split(_e);return i.length===2&&E(i[0])&&(i[1]==="ara"||n!==void 0&&i[1]===n)?i[0]:null}function Le(e,t){try{return R(t).isSymbolicLink()&&b(S(t),J(t))===b(e.current)}catch{return!1}}function Ss(e,t=process.execPath){try{return O(P(t),P(e.versions),e.executableName)!==null}catch{let n=b(t);return n===b(e.current)||Le(e,n)||O(n,b(e.versions),e.executableName)!==null}}function Ae(e){return W(e)&&X(e,["schema_version","pid","nonce","started_at","runtime_version"])&&e.schema_version===q&&typeof e.pid==="number"&&Number.isSafeInteger(e.pid)&&e.pid>0&&typeof e.nonce==="string"&&/^[0-9a-f-]{36}$/.test(e.nonce)&&Z(e.started_at)&&E(e.runtime_version)}function Q(e,t){try{let n=R(e);if(!n.isDirectory()||!A(n))return null;let r=G(c(e,t),g.O_RDONLY|g.O_NOFOLLOW|g.O_NONBLOCK);try{let i=F(r);if(!i.isFile()||i.nlink!==1||!A(i)||i.size>4096)return null;return Y(r,"utf8")}finally{h(r)}}catch{return null}}function N(e){try{let t=JSON.parse(Q(e,"owner.json")??"null");return Ae(t)?t:null}catch{return null}}function ee(e){try{return process.kill(e,0),!0}catch(t){return!(t instanceof Error&&("code"in t)&&t.code==="ESRCH")}}var C="lease",Ne=2,Se=4,y;function ke(){if(y!==void 0)return y;if(y=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let e;try{e=H(import.meta.url)("bun:ffi")}catch{return null}let t=process.platform==="darwin"?"__error":"__errno_location",n=process.platform==="darwin"?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`];for(let r of n)try{let i=e.dlopen(r,{flock:{args:[e.FFIType.i32,e.FFIType.i32],returns:e.FFIType.i32},[t]:{args:[],returns:e.FFIType.ptr}}),s=i.symbols[t]();if(s===null)continue;return y={flock:(o,d)=>i.symbols.flock(o,d),errno:()=>e.read.i32(s),wouldBlock:process.platform==="darwin"?35:11},y}catch{}return null}var v,Ie=3221225472,Te=4,xe=128,Pe=32;function De(e){if(v===void 0){v=null;try{let s=H(import.meta.url)("bun:ffi"),{FFIType:o}=s;v={kernel:s.dlopen("kernel32.dll",{CreateFileW:{args:[o.ptr,o.u32,o.u32,o.ptr,o.u32,o.u32,o.ptr],returns:o.i64_fast},CloseHandle:{args:[o.i64_fast],returns:o.i32},GetLastError:{args:[],returns:o.u32}}).symbols,ptr:(l)=>s.ptr(l)}}catch{return null}}if(!v)return null;let{kernel:t,ptr:n}=v,r=Buffer.from(`${e}\x00`,"utf16le"),i=t.CreateFileW(n(r),Ie,0,null,Te,xe,null);if(Number(i)===-1)return t.GetLastError()===Pe?"busy":null;return{release:()=>{t.CloseHandle(i)}}}function Oe(e){if(process.platform==="win32")return De(`${e}.lease`);let t=ke();if(!t)return null;let n=G(`${e}.lease`,g.O_RDWR|g.O_CREAT|g.O_NOFOLLOW,384);try{let r=F(n);if(!r.isFile()||r.nlink!==1||!A(r))return h(n),"busy";if(t.flock(n,Ne|Se)===0)return{release:()=>h(n)};let i=t.errno();return h(n),i===t.wouldBlock?"busy":null}catch(r){throw h(n),r}}function Es(e){k(S(e.path));let t=Oe(e.path);if(t==="busy")return{acquired:!1,owner:N(e.path),recoveredStaleOwner:!1};let n=t!==null;try{let r=Ce(e,t);if(r.acquired)n=!1;return r}finally{if(n)t.release()}}function Ce(e,t){let n=e.alive??ee,r=!1;for(let i=0;i<4;i+=1){let s={schema_version:q,pid:e.pid??process.pid,nonce:e.nonce?.()??f(),started_at:(e.now?.()??new Date).toISOString(),runtime_version:e.runtimeVersion},o=`${e.path}.init-${process.pid}-${f()}`,d=!1;try{if(B(o,{mode:448}),L(c(o,"owner.json"),`${JSON.stringify(s)}
|
|
3
3
|
`,{mode:384,flag:"wx"}),t!==null)L(c(o,C),`flock
|
|
4
4
|
`,{mode:384,flag:"wx"});e.beforePublish?.();try{throw R(e.path),Object.assign(Error("Managed runtime lock exists."),{code:"EEXIST"})}catch(m){if(m.code!=="ENOENT")throw m}_(o,e.path),d=!0;let l=!1;return{acquired:!0,owner:s,recoveredStaleOwner:r,release(){if(l)return;if(l=!0,N(e.path)?.nonce===s.nonce)p(e.path,{recursive:!0,force:!0});t?.release()}}}catch(l){let m=l.code;if(!["EEXIST","ENOTEMPTY"].includes(m??""))throw l;let u=N(e.path),re=(e.now?.()??new Date).getTime(),ie=u&&e.staleAfterMs!==void 0?re-Date.parse(u.started_at)<e.staleAfterMs:!1,ae=u!==null&&!(t!==null&&Q(e.path,C)!==null)&&n(u.pid);if(!u||ae||ie)return{acquired:!1,owner:u,recoveredStaleOwner:!1};let I=`${e.path}.stale-${process.pid}-${f()}`;try{_(e.path,I),p(I,{recursive:!0,force:!0}),r=!0}catch(x){let oe=x.code;if(!["ENOENT","EEXIST"].includes(oe??""))throw x}}finally{if(!d)p(o,{recursive:!0,force:!0})}}throw new ft("lock_unavailable","Could not acquire the managed Reason runtime lock.")}function te(e){return W(e)&&X(e,["schema_version","event_id","occurred_at","event","runtime_version"],["from_version","to_version","reason_code","duration_ms","attempt_count","retry_in_ms","capabilities"])&&e.schema_version===j&&typeof e.event_id==="string"&&/^[0-9a-f-]{36}$/.test(e.event_id)&&Z(e.occurred_at)&&typeof e.event==="string"&&we.includes(e.event)&&E(e.runtime_version)&&(e.from_version===void 0||E(e.from_version))&&(e.to_version===void 0||E(e.to_version))&&(e.reason_code===void 0||typeof e.reason_code==="string"&&D.test(e.reason_code))&&(e.duration_ms===void 0||typeof e.duration_ms==="number"&&Number.isSafeInteger(e.duration_ms)&&e.duration_ms>=0&&e.duration_ms<=86400000)&&(e.attempt_count===void 0||typeof e.attempt_count==="number"&&Number.isSafeInteger(e.attempt_count)&&e.attempt_count>=1&&e.attempt_count<=1e5)&&(e.retry_in_ms===void 0||typeof e.retry_in_ms==="number"&&Number.isSafeInteger(e.retry_in_ms)&&e.retry_in_ms>=0&&e.retry_in_ms<=30000)&&(e.capabilities===void 0||Array.isArray(e.capabilities)&&e.capabilities.length<=be&&e.capabilities.every((t)=>typeof t==="string"&&D.test(t)))}var Ve=/^(\d{22}-[0-9a-f-]{36}\.json)$/,Ue=/^(\d{22}-[0-9a-f-]{36}\.json)\.sending-(\d+)-[0-9a-f-]{36}$/,Fe=300000,w=0n;function Be(e){let t=BigInt(new Date(e.occurred_at).getTime())*1000000n;return w=t>w?t:w+1n,`${String(w).padStart(22,"0")}-${e.event_id}.json`}function ne(e){try{return z(e.lifecycleEvents).filter((t)=>Ve.test(t)).sort()}catch{return[]}}function V(e){try{let t=JSON.parse(Y(e,"utf8"));return te(t)?t:null}catch{return null}}function $e(e,t=ee,n=Date.now()){let r;try{r=z(e.lifecycleEvents)}catch{return}for(let i of r){let s=i.match(Ue);if(!s)continue;let o=c(e.lifecycleEvents,i),d=c(e.lifecycleEvents,s[1]),l=!t(Number(s[2]));if(!l)try{l=n-K(o).mtimeMs>=Fe}catch{continue}if(!l)continue;try{_(o,d)}catch(m){let u=m.code;if(u==="EEXIST")M(o);else if(u!=="ENOENT")throw m}}}function Ge(e){let n=ne(e).flatMap((i)=>{try{return[{name:i,size:K(c(e.lifecycleEvents,i)).size}]}catch{return[]}}),r=n.reduce((i,s)=>i+s.size,0);while(n.length>ye||r>ve){let i=n.shift();if(!i)break;try{M(c(e.lifecycleEvents,i.name)),r-=i.size}catch(s){if(s.code!=="ENOENT")throw s}}}function xs(e,t,n={}){let r={schema_version:j,event_id:n.eventId?.()??f(),occurred_at:(n.now?.()??new Date).toISOString(),...t};if(!te(r))throw new ft("invalid_lifecycle_event","Managed runtime lifecycle event is invalid.");return k(e.lifecycleEvents),Re(c(e.lifecycleEvents,Be(r)),`${JSON.stringify(r)}
|
|
5
5
|
`),Ge(e),r}async function ks(e,t,n){$e(e);let r=0;for(let i of ne(e)){let s=c(e.lifecycleEvents,i);if(n){let l=V(s);if(!l||!n(l))continue}let o=`${s}.sending-${process.pid}-${f()}`;try{_(s,o)}catch(l){if(l.code==="ENOENT")continue;throw l}let d=V(o);if(!d){M(o);continue}try{await t(d),M(o),r+=1}catch{try{_(o,s)}catch(l){if(l.code!=="ENOENT")throw l}break}}return r}export{ys,bs,vs,Ss,Es,xs,ks};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{H}from"./vm-hands-entry-lite-38g65s5x.js";import{D,R,b}from"./vm-hands-entry-lite-3gztfxwt.js";import{je,hr,fr,wn,bn,st}from"./vm-hands-entry-lite-
|
|
2
|
+
import{H}from"./vm-hands-entry-lite-38g65s5x.js";import{D,R,b}from"./vm-hands-entry-lite-3gztfxwt.js";import{je,hr,fr,wn,bn,st}from"./vm-hands-entry-lite-3qvd7zm7.js";import{Lr}from"./vm-hands-entry-lite-gc7550c0.js";import{p,ct,xn,_e,we}from"./vm-hands-entry-lite-psywfz8m.js";import{v,h}from"./vm-hands-entry-lite-f69t48dj.js";import{a,tr,Mo}from"./vm-hands-entry-lite-swrymqj9.js";import{nn,y,t,k,o,d,os,Oe,Ni,u,i,W,g,ee,s,n,on}from"./vm-hands-entry-lite-a1xa7s06.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{se,A}from"./vm-hands-entry-lite-87vmbt38.js";import{randomUUID as Q}from"crypto";import{spawn as Le}from"child_process";import{existsSync as Z,lstatSync as me,mkdirSync as We,readFileSync as Ne,realpathSync as G,rmSync as Ve,writeFileSync as He}from"fs";import{dirname as Ue,join as j,relative as qe,sep as Je}from"path";var Se=["process.run.v1","process.full.v1"],xe=600000,Pe=1800000,Ee=20000,ne="process.cancel.v1",ie=i({action:n("start"),request_id:t().uuid(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),cwd:t().min(1).max(4096).refine((e)=>!e.includes("\x00")&&!e.startsWith("/")&&!e.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:s(["host","confined"]).default("host"),timeout_ms:o().int().min(1000).max(Pe).default(xe).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),K={device_id:t().uuid(),root_id:t().uuid()},Re=g("action",[ie.extend(K),i({...K,action:n("inspect"),process_id:t().uuid(),after:o().int().min(0).default(0),wait_ms:o().int().min(0).max(Ee).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),i({...K,action:n("cancel"),process_id:t().uuid()}).strict()]),Fe=nn(Re,{io:"input"}),Ke=ie.extend({process_brain_fence:t().uuid(),process_expires_at:y.datetime()}).strict(),J=i({version:n(1),process_id:t().uuid(),state:s(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:o().int().nullable(),first_cursor:o().int().min(0),next_cursor:o().int().min(0),truncated:d(),observed_at:y.datetime(),output:u(i({cursor:o().int().min(1),stream:s(["stdout","stderr"]),text:t().max(32768)}).strict()).max(128)}).strict().refine((e)=>{if(Buffer.byteLength(JSON.stringify(e))>1e5||e.next_cursor<e.first_cursor-1)return!1;if((e.state==="starting"||e.state==="running"||e.state==="uncertain")&&e.exit_code!==null)return!1;if(e.state==="exited"&&(e.exit_code===null||e.exit_code<0||e.exit_code>255))return!1;if(e.state==="cancelled"&&e.exit_code!==130||e.state==="expired"&&e.exit_code!==124)return!1;let _=e.first_cursor-1;for(let l of e.output){if(l.cursor<=_||l.cursor>e.next_cursor)return!1;_=l.cursor}return!0});function ae(e){return Se.includes(e)}var Xe=i({operation_constraints:ee(t(),Oe())}),Ye=i({ready:n(!0),version:n(1),execution_mode:s(["host","confined"]),max_timeout_ms:o().int().min(1000).optional()});var Ie=i({version:n(1),process_id:t().uuid(),state:s(["queued","cancelled_before_start","not_started"]),exit_code:os(),output:u(Ni()).length(0),first_cursor:n(0),next_cursor:n(0),truncated:n(!1),cancellation_requested:n(!1),reason_code:s(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),De=i({...J.shape,state:s(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:y.datetime().optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:d(),reason_code:t().nullable().optional(),execution_authority:n("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:i({cause:n("brain_generation_changed"),terminal_confirmed:d(),next_step:s(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:J.shape.state.or(n("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),$e=nn(De),Qe=W([J,Ie.refine((e)=>e.state==="cancelled_before_start")]),X=i({version:n(1),process_id:t().uuid(),state:s(["exited","cancelled","expired"]),exit_code:o().int().min(0).max(255),observed_at:y.datetime()}).strict().refine((e)=>(e.state!=="cancelled"||e.exit_code===130)&&(e.state!=="expired"||e.exit_code===124)),Ze=i({process_terminal_observation:X}).strict();var Wi="preview.serve.v1",Vi=43200000;var ce="preview.open.v1",de=1,fn="gid_proxy_v1",Gi="egress",mn=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,Ce=i({version:n(fn),allowed_domains:u(t().max(260).regex(mn)).max(1024)}).strict(),Ae=on((e)=>H(e)!==null,"invalid workspace"),ke=i({version:n(1),request_id:k(),session_id:k(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),port:o().int().min(1024).max(65535),workspace:Ae,egress:Ce.optional()}).strict(),Ki=ke.extend({expires_at:y.datetime()}).strict();var Me=4,Te=5000;function Y(e,c,_){let l=null;try{l=ct(e)}catch{}xn({deviceRelayUrl:l?.deviceRelayUrl??"",binding:l?.binding??null,jobId:c,port:l?.binding.port??0,reason:l?_:"binding_invalid"})}function le(e){let c=new Map;return{open(_){let l=(x)=>Y(_,e.claim.operation_id,x),C;try{C=ct(_)}catch{return l("binding_invalid")}let{binding:w,deviceRelayUrl:z}=C,E=e.claim.owner;if(!E||w.organizationId!==E.organization_id||w.userId!==E.user_id||w.deviceId!==E.device_id||w.rootId!==e.claim.root_id||w.jobId!==e.claim.operation_id||w.fenceId!==e.claim.operation_id||w.generation!==de||w.expiresAtMs>Math.min(Date.now()+p.lifetimeMs+Te,e.expiresAtMs))return l("binding_mismatch");if(w.expiresAtMs<=Date.now())return l("binding_expired");if(c.get(w.port)?.abort(),c.delete(w.port),c.size>=Me)return l("preview_capacity");let L=new AbortController;c.set(w.port,L);let P=we({binding:w,deniedPorts:e.deniedPorts,readCurrentJob:async()=>{if(L.signal.aborted)return null;let x=await e.inspect();return x?{binding:w,executorLaunchId:e.executorLaunchId,job:x}:null}});_e({binding:w,deviceRelayUrl:z,port:P,signal:L.signal}).then((x)=>x.closed,(x)=>{let I=x instanceof Error?x.message:"preview_failed";if(I!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:w.jobId,port:w.port,reason_code:I})}
|
|
3
3
|
`)}).finally(()=>{if(c.get(w.port)===L)c.delete(w.port)})},dispose(){for(let _ of c.values())_.abort();c.clear()}}}class it extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var fe=256,B=new Map,he="preview.serve.v1",V=new Map;function be(e){let c=V.get(e.operation_id);if(c){if(c.claim!==e)throw M("process_authority_lost");return c}if(V.size>=fe)throw M("process_journal_capacity");let _={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return V.set(e.operation_id,_),_}function pe(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ue=(e)=>new Promise((c)=>setTimeout(c,e)),M=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function ze(e=a(),c=Ge()){let _=Ue(Lr({},e)),l=qe(tr(e),_),[C,...w]=l.split(Je);return{directory:j(c,l,"processes"),previous:[j(_,"processes"),...C==="reason"?[j(c,"ara",...w,"processes")]:[]]}}function Ge(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=Mo();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function dr(e){if(!e.claim.owner||e.signal.aborted||e.expiresAtMs<=Date.now())throw M("process_authority_lost");let c=be(e.claim);if(c.executing)throw M("process_busy");if(c.executing=!0,c.cancelRequested)return c.phase="settling",pe(e.claim.operation_id);c.phase="starting";let _=e.journals??ze();We(_.directory,{recursive:!0,mode:448});let l=hr({runtimeDirectory:G(_.directory),previousRuntimeDirectories:(_.previous??[]).filter((m)=>Z(m)).map((m)=>G(m)),root:e.root,runId:JSON.stringify([e.claim.owner,e.claim.run_id,e.claim.root_id,e.claim.operation_id]),maxScopes:fe});try{for(let m of[e.root,e.cwd])if(!je(G(m),l.journalDirectory))throw new r("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(m){throw l.disposeSocket(),m}let C=me(l.journalDirectory),w=e.claim.capability===he,z=()=>B.set(e.claim.operation_id,{path:l.journalDirectory,ino:C.ino,dev:C.dev,anyCompletion:w}),E=l.launchDirectory,L=j(E,"config.json"),P={url:"",transport:"local_job_ipc",directShell:{mode:e.mode,executable:e.shell,jobId:e.claim.operation_id},workerVersion:D,protocolVersion:2,workerArtifactSha256:b,workerEntrypoint:R,targetGeneration:1,fenceId:Q(),...process.platform==="win32"?{bashExecutable:se()}:{},workRoot:e.root,workspaceAliasPath:e.root,repoPath:e.cwd,jobEnvPath:j(E,"unused.env"),replSocketPath:j(E,"unused.sock"),readyPath:j(E,"ready.json"),directTerminalReceiptPath:j(E,"terminal.json"),launchId:Q(),expiresAtMs:e.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:l.journalDirectory,scopeId:l.scopeId},jobControlSocketPath:l.socketPath,...e.prefix?{bashCommandPrefix:e.prefix}:{},...e.jobsUser?{jobsUser:e.jobsUser}:{}},x;try{He(L,JSON.stringify(P),{mode:384});let m=wn({configPath:L,root:e.cwd,grantedRoot:e.root,workRoot:e.root,temporaryDirectory:E});x=e.spawnWorker?.(L,P)??Le(m.command,m.args,{...m.options,env:e.environment,stdio:[bn,"ignore","ignore"]})}catch(m){throw l.disposeSocket(),m}let I=!1,F=new Promise((m,S)=>{x.once("exit",(f)=>{I=!0,m(f)}),x.once("error",(f)=>{I=!0,S(f)})});F.catch(()=>{});let ge={root:e.root,runId:e.claim.run_id,scopeId:l.scopeId,socketPath:l.socketPath,generation:1,fenceId:P.fenceId,executorLaunchId:P.launchId,expiresAtMs:P.expiresAtMs},N=async(m)=>{let S=await fr(ge,{type:"job",version:2,generation:1,id:Q(),jobId:e.claim.operation_id,...m==="start"?{action:m,input:{script:e.command,leaseExpiresAtMs:e.expiresAtMs}}:m==="inspect"?{action:m,input:{after:0}}:m==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:m,input:{}}},new AbortController().signal);if(!S.ok)throw M(S.error);return S.job},U=!1,q=!1,te,re=()=>{U=!0,st(x,"SIGTERM")};e.signal.addEventListener("abort",re,{once:!0});let T,oe=0,ve=async(m)=>{let S=[...m.output],f={version:1,process_id:e.claim.operation_id,state:m.state,exit_code:m.exitCode,first_cursor:m.firstCursor,next_cursor:m.nextCursor,truncated:m.truncated,output:S,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(f))>90000&&S.length)S.shift(),f.truncated=!0,f.first_cursor=S[0]?.cursor??f.next_cursor+1;T=J.parse(f),await e.emit(T),oe=Date.now()};try{let m=Math.min(Date.now()+1e4,e.expiresAtMs);while(!Z(P.readyPath)){if(I)throw new r("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if(e.signal.aborted||Date.now()>=m)throw M("process_start_unconfirmed");await ue(25)}let S=JSON.parse(Ne(P.readyPath,"utf8"));if(S.launchId!==P.launchId||S.fenceId!==P.fenceId||S.workerArtifactSha256!==b)throw M();if(e.signal.throwIfAborted(),c.cancelRequested)return pe(e.claim.operation_id);let f;try{q=!0,f=await N("start")}catch(O){if(!(O instanceof r)||O.code!=="hands_job_result_unknown")throw O;f=await N("inspect")}if(c.phase="running",c.cancel=async()=>{await N("cancel")},w&&e.preview)c.tunnels=le({claim:e.claim,executorLaunchId:P.launchId,expiresAtMs:e.expiresAtMs,deniedPorts:e.preview.deniedPorts,inspect:async()=>c.phase==="running"&&!I?await N("probe"):null});if(c.cancelRequested)await c.cancel(),f=await N("inspect");for(;;){if(!["starting","running"].includes(f.state))c.phase="settling",c.cancel=void 0;if(!T||T.state!==f.state||T.next_cursor!==f.nextCursor&&Date.now()-oe>=5000)await ve(f);if(!["starting","running"].includes(f.state))break;if(e.signal.aborted||I)throw M();await ue(1000);try{f=await N("inspect"),te=void 0}catch(O){if(!(O instanceof r)||O.code!=="hands_job_result_unknown"||e.signal.aborted||I||Date.now()-(te??=Date.now())>120000)throw O}}if(!T||T.state==="uncertain")throw M();return T}finally{if(c.phase="settling",c.cancel=void 0,c.tunnels?.dispose(),c.tunnels=void 0,await c.cancelInFlight?.catch(()=>{}),e.signal.removeEventListener("abort",re),!I&&!U)st(x,"SIGTERM");let m,S=await Promise.race([F.then((f)=>({code:f})),new Promise((f)=>{m=setTimeout(()=>f(null),6000)})]).finally(()=>{clearTimeout(m)});if(!S){try{st(x,"SIGKILL")}catch{}try{await F}finally{if(I)l.disposeSocket()}throw M("process_cleanup_unconfirmed")}try{if((U||e.signal.aborted)&&S.code===0&&q){v(E);let f=JSON.parse(h(P.directTerminalReceiptPath)),O=X.safeParse(f.observation);if(Object.keys(f).length===4&&f.launch_id===P.launchId&&f.fence_id===P.fenceId&&f.scope_id===l.scopeId&&O.success&&O.data.process_id===e.claim.operation_id){if(w)z();throw new it(O.data)}}}catch(f){if(f instanceof it)throw f}finally{if(I)l.disposeSocket()}if(S.code!==0&&!U&&q)throw M("process_cleanup_unconfirmed");if(!U&&S.code===0&&(T&&["exited","cancelled","expired"].includes(T.state)||!q&&c.cancelRequested)||w&&S.code===0&&!q)z()}}async function Rs(e,c){if(c.kind===ce&&e.capability===he){let C=V.get(e.operation_id);if(C?.claim===e&&C.tunnels)C.tunnels.open(c.payload);else Y(c.payload,e.operation_id,"server_not_running");return!0}if(c.kind!==ne||!ae(e.capability)||!e.owner||c.payload.process_id!==e.operation_id)return!1;let _=V.get(e.operation_id);if(_&&_.claim!==e)return!1;let l=be(e);if(l.cancelRequested=!0,l.phase==="running"&&l.cancel)l.cancelInFlight??=l.cancel(),await l.cancelInFlight;return!0}function Os(e,c){V.delete(e);let _=B.get(e);if(!_||c!=="succeeded"&&!_.anyCompletion)return B.delete(e),!1;try{let l=me(_.path);if(!l.isDirectory()||l.isSymbolicLink()||l.ino!==_.ino||l.dev!==_.dev||!A(l)||G(_.path)!==_.path||Z(j(_.path,"owner.lock")))return!1;return Ve(_.path,{recursive:!0}),B.delete(e),!0}catch{return!1}}
|
|
4
4
|
export{Wi,Vi,fn,Gi,mn,Ki,it,dr,Rs,Os};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ge,dt}from"./vm-hands-entry-lite-w0pegc58.js";import{Qe}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ge,dt}from"./vm-hands-entry-lite-w0pegc58.js";import{Qe}from"./vm-hands-entry-lite-02wn6p6x.js";import{To,le,Gr,mt,Ro}from"./vm-hands-entry-lite-jcjrhjnp.js";import{E}from"./vm-hands-entry-lite-txd50spx.js";import{a,tr}from"./vm-hands-entry-lite-swrymqj9.js";import{spawnSync as H}from"child_process";import{dirname as w}from"path";import{spawn as A}from"child_process";import{accessSync as _,constants as v}from"fs";import{basename as C,join as O}from"path";var l=null;function S(e){if(l===e)l=null;if(e.exitCode===null&&e.signalCode===null)e.kill("SIGTERM")}var Rr=(e,t)=>{if(l)S(l);let s=O(e,To);try{_(s,v.X_OK)}catch{return()=>{}}let n;try{n=A(s,["--app",e,"--name",C(e,".app"),"--permission",t==="screen"?"screen_recording":"accessibility"],{detached:!0,stdio:"ignore"})}catch{return()=>{}}return n.on("error",()=>{if(l===n)l=null}),n.once("exit",()=>{if(l===n)l=null}),n.unref(),l=n,()=>S(n)};import{chmodSync as ne,existsSync as se,mkdirSync as re,readFileSync as D,realpathSync as ie,renameSync as oe,statSync as j,writeFileSync as ae}from"fs";import{dirname as de,isAbsolute as G,join as N,resolve as T,sep as b}from"path";function F(e=a()){return N(tr(e),"reason","protected-path-grants.json")}var f=null;function L(e){let t=JSON.parse(e);if(!Array.isArray(t?.grants))return[];return t.grants.flatMap((s)=>{let n=s;return n&&typeof n.path==="string"&&G(n.path)&&(n.kind==="file"||n.kind==="folder")&&typeof n.grantedAt==="number"?[{path:n.path,kind:n.kind,grantedAt:n.grantedAt}]:[]})}function y(e=F()){try{let{mtimeMs:t}=j(e);if(f&&f.file===e&&f.mtimeMs===t)return f.grants;let s=L(D(e,"utf8"));return f={file:e,mtimeMs:t,grants:s},s}catch{return[]}}function W(e,t){return e.kind==="file"?t===e.path:t===e.path||t.startsWith(`${e.path}${b}`)}function U(e,t){let s=T(e);return y(t).some((n)=>W(n,s))}function fo(e,t){return E(e)&&!U(e,t)}function mo(e,t,s){let n=t?"file-read* file-write*":"file-read*";return y(s).filter((r)=>r.path===e||r.path.startsWith(`${e}${b}`)).map((r)=>`(allow ${n} (${r.kind==="file"?"literal":"subpath"} ${JSON.stringify(r.path)}))`)}var P="x-apple.systempreferences:com.apple.preference.security",J="curl -fsSL https://reasonmachines.com/install.sh | bash",q=180000,B=2000;var k={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${P}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${P}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${P}?Privacy_AllFiles`}};function R(e){return e.executable}function K(e,t){if(e==="computer_use_identity_missing")return`Reason's background identity is not installed (${e}); reinstall Reason: ${J}`;if(e==="computer_use_identity_outdated")return`Reason's background identity is outdated (${Gr(t)??"unknown"}; this CLI is ${Qe}) (${e}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${e}); run the installed \`reason\``}function es(e=a()){let t=mt(e);if(t.length>0)return{state:"ready",path:w(w(w(t[0]))),prefix:t};let s=Ro(t,e)??"computer_use_identity_unavailable";return{state:s,path:le(e),detail:K(s,e)}}function V(){return{identity:()=>es(),grants:(e)=>Ge(e),request:(e,t)=>dt(e,t),worker:async()=>(await import("./status-sk609adw.js")).connectionMacState(),open:(e)=>{H("/usr/bin/open",e,{stdio:"ignore",timeout:1e4})},tile:Rr,restartConnection:async()=>(await import("./connect-cli-f7mc1dsg.js")).restartConnection(),sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now()}}function M(e,t,s){if(e.state!=="ready"||!t)return"unknown";return t[s]?"granted":"missing"}async function ts(e){let t=e.identity(),s=t.state==="ready"?await e.grants(t.prefix):null,n=await e.worker(),r=n?R(n):null,i=!r||n?.full_disk_access==="unknown"?"unknown":n?.full_disk_access==="granted"?"granted":"missing",c=(u,d,o)=>{let{label:p,purpose:h,level:m}=k[u];return{id:u,label:p,purpose:h,level:m,state:d,holder:o}};return{identity:{state:t.state,path:t.path,detail:t.state==="ready"?null:t.detail},worker_detail:r?null:"Full Disk Access is read from this computer's running worker; `reason connect` starts it.",permissions:[c("screen",M(t,s,"screen"),t.path),c("accessibility",M(t,s,"accessibility"),t.path),c("disk",i,r)]}}function $s(e){let t=e.identity.state==="ready"?null:e.identity.state,s=e.permissions.filter((i)=>i.state==="granted").length,n=[...t?[t]:[],...e.permissions.filter((i)=>i.state!=="granted"&&!(t&&i.id!=="disk")).map((i)=>`${i.label} ${i.state}`)],r=!t&&e.permissions.some((i)=>i.state==="missing");return`Permissions: ${s} of ${e.permissions.length}${n.length>0?` (${n.join(", ")})`:""}`+(r?" \u2014 reason permissions allow":n.length>0?" \u2014 reason permissions":"")}async function x(e,t){let s=t.now()+q;for(;;){if(await e())return!0;if(t.now()>=s)return!1;await t.sleep(B)}}async function Bs(e,t){let s=t.host??V(),{io:n}=t,r=await ts(s),i=r.permissions.filter((o)=>e.includes(o.id)&&o.state!=="granted");if(i.length===0)return n.stdout.write(`Reason permissions: ${e.map((o)=>k[o].label).join(", ")} already allowed.
|
|
3
3
|
`),0;let c=!1,u=!1,d=s.identity();for(let o of i){let{label:p,pane:h}=k[o.id];if(o.id!=="disk"){if(d.state!=="ready"){if(!c)n.stderr.write(`Reason permissions: ${d.detail}
|
|
4
4
|
`);c=!0;continue}let g=o.id;await s.request(d.prefix,g),s.open([h]);let I=s.tile(d.path,g);if(n.stdout.write(`Allow Reason in System Settings > Privacy & Security > ${p}.
|
|
5
5
|
`),!t.wait)continue;if(n.stdout.write(`Waiting for it (Ctrl-C to stop)\u2026
|
|
@@ -1,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.498",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,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-rp77m9ya.js";import{t,o,d,u,i,ss,W,g,s,n}from"./vm-hands-entry-lite-a1xa7s06.js";var z=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function S(e){let r=typeof e==="string"?z.exec(e):null;return r?{major:Number(r[1]),minor:Number(r[2])}:null}var j=25,E=i({day:t().regex(/^\d{4}-\d{2}-\d{2}$/),sent:o().int().min(0).max(1e9),received:o().int().min(0).max(1e9)}),ve=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(j).optional(),message_counts:u(E).max(14).optional()}),L=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()})]),k=i({job:L.nullable(),retry_after_seconds:o().optional()}),D=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()}),N=i({person:t(),machine:t(),online:d()}),H=i({team:t().nullable(),sessions:u(D).max(2000),machines:u(N).max(500),all:d().optional()}),B=i({address:t().max(300),state:t().max(40),note:t().max(500)}),Pe=W([i({who:H}),i({sent:i({ids:u(t().max(100)).max(500),recipients:u(t().max(300)).max(500),from:t().max(300),deliveries:u(B).max(500).optional()})}),i({error:t().min(1).max(2000)})]),F=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()}),xe=i({messages:u(F).max(100),team:t().min(1).max(200).optional(),team_id:t().min(1).max(200).optional(),workspace:d().optional()});var v=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var Ne=v.filter((e)=>e!=="network:read"&&e!=="network:write");class b extends Error{oauthCode;constructor(e,r=null){super(e);this.oauthCode=r;this.name="LoginError"}}function J(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 b(l,a)}async function G(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 J(m,`OAuth token request failed (${c.status})`);return m}var Q=1e4;async function K(e,r={}){let a=r.fetchImpl??fetch,l=await G(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),a,AbortSignal.timeout(Q)).catch((m)=>{if(m instanceof Error&&m.name==="TimeoutError")throw new b("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 b("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 R=new Map,V=2000,Y=100;function P(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=R.get(m);if(p)return P(p,e.signal);let f;return f=K(a,{fetchImpl:e.fetchImpl,path:r}).catch(async(y)=>{if(!(y instanceof b)||y.oauthCode!=="invalid_grant"&&y.oauthCode!=="invalid_client")throw y;let w=(_)=>_!==null&&(y.oauthCode==="invalid_client"?_.clientId!==a.clientId:_.refreshToken!==a.refreshToken),O=Date.now()+V;while(!w(Tt(r))&&Date.now()<O)await new Promise((_)=>setTimeout(_,Y));if(w(Tt(r)))return Pt({fetchImpl:e.fetchImpl,path:r});return cn(r),null}).finally(()=>{if(R.get(m)===f)R.delete(m)}),R.set(m,f),P(f,e.signal)}var Z=i({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:d().nullable()}),X=i({groups:u(i({selectable:d().optional(),accounts:u(i({source_id:t().min(1),model_ids:u(t().min(1)).optional()}))}))});function ee(e){let r=X.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 ne=["minimal","low","medium","high","xhigh","max"],te=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()}))}),se=i({devices:u(te),end_cursor:t().nullish(),has_next_page:d().optional()}),oe=i({id:t().min(1),name:t()}),re=i({items:u(oe)}),ie=i({id:t().min(1),name:t(),main:d(),mine:d(),session_id:t().nullish(),appearance:i({color:t().nullish()}).nullish().catch(null)}),ae=i({items:u(ie)}),le=i({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:u(t()).default([]),is_enabled:d().default(!0)}),ce=i({items:u(le).default([])}),de=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()}),C=i({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:d(),triggers:u(de).default([])}),me=i({items:u(C).default([]),end_cursor:t().nullish(),has_next_page:d().optional()}),ue=i({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:d()}),ge=i({items:u(ue).default([])}),he=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()}),x=i({tags:u(t()).default([])}),pe=s(["linux","macos"]),A=i({id:t().min(1),name:t().min(1),platform:pe.nullable(),workers:i({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:i({queued:o().int(),running:o().int()})}),fe=i({machines:u(A)}),ye=i({machine:A}),_e=i({deleted:n(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),be=i({token:i({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),U=ss({machine_id:t().min(1),machine_name:t().min(1)}),Re=U.extend({organization_id:t().min(1)}),We=i({id:t().min(1),name:t().min(1),state:s(["waiting","placed"]),queue_position:o().int().nullable()});var Ve=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 we=i({error:i({type:t(),message:t()})});function q(e,r,a){let l=we.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 _s(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 q(r.status,a,r.headers.get("retry-after"));return h(Re,a,"invalid_machine_ticket")}class Go{options;credentials;constructor(e,r={}){this.options=r;this.credentials=e}trackEvent(e,r={}){}async request(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},body:r.raw?r.raw.bytes:r.body===void 0?void 0:JSON.stringify(r.body),signal:r.signal,redirect:"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.request(e,r,!0)}if(!c.ok)throw q(c.status,m,c.headers.get("retry-after"));return 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(fe,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(ye,r,"invalid_machine").machine}async deleteMachine(e){let r=await this.request(this.machinePath(e),{method:"DELETE"});return h(_e,r,"invalid_machine_deletion")}async createMachineToken(e){let r=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return h(be,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(U,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(k,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=re.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(ae,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(ce,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=se.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:ne.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 S(r.reason_version)?r.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=Z.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let r;try{r=ee(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 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(x,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(x,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(he,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(me,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(C,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(ge,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-02wn6p6x.js";import{t,o,d,u,i,ss,W,g,s,n}from"./vm-hands-entry-lite-a1xa7s06.js";var z=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function S(e){let r=typeof e==="string"?z.exec(e):null;return r?{major:Number(r[1]),minor:Number(r[2])}:null}var j=25,E=i({day:t().regex(/^\d{4}-\d{2}-\d{2}$/),sent:o().int().min(0).max(1e9),received:o().int().min(0).max(1e9)}),ve=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(j).optional(),message_counts:u(E).max(14).optional()}),L=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()})]),k=i({job:L.nullable(),retry_after_seconds:o().optional()}),D=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()}),N=i({person:t(),machine:t(),online:d()}),H=i({team:t().nullable(),sessions:u(D).max(2000),machines:u(N).max(500),all:d().optional()}),B=i({address:t().max(300),state:t().max(40),note:t().max(500)}),Pe=W([i({who:H}),i({sent:i({ids:u(t().max(100)).max(500),recipients:u(t().max(300)).max(500),from:t().max(300),deliveries:u(B).max(500).optional()})}),i({error:t().min(1).max(2000)})]),F=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()}),xe=i({messages:u(F).max(100),team:t().min(1).max(200).optional(),team_id:t().min(1).max(200).optional(),workspace:d().optional()});var v=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var Ne=v.filter((e)=>e!=="network:read"&&e!=="network:write");class b extends Error{oauthCode;constructor(e,r=null){super(e);this.oauthCode=r;this.name="LoginError"}}function J(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 b(l,a)}async function G(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 J(m,`OAuth token request failed (${c.status})`);return m}var Q=1e4;async function K(e,r={}){let a=r.fetchImpl??fetch,l=await G(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),a,AbortSignal.timeout(Q)).catch((m)=>{if(m instanceof Error&&m.name==="TimeoutError")throw new b("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 b("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 R=new Map,V=2000,Y=100;function P(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=R.get(m);if(p)return P(p,e.signal);let f;return f=K(a,{fetchImpl:e.fetchImpl,path:r}).catch(async(y)=>{if(!(y instanceof b)||y.oauthCode!=="invalid_grant"&&y.oauthCode!=="invalid_client")throw y;let w=(_)=>_!==null&&(y.oauthCode==="invalid_client"?_.clientId!==a.clientId:_.refreshToken!==a.refreshToken),O=Date.now()+V;while(!w(Tt(r))&&Date.now()<O)await new Promise((_)=>setTimeout(_,Y));if(w(Tt(r)))return Pt({fetchImpl:e.fetchImpl,path:r});return cn(r),null}).finally(()=>{if(R.get(m)===f)R.delete(m)}),R.set(m,f),P(f,e.signal)}var Z=i({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:d().nullable()}),X=i({groups:u(i({selectable:d().optional(),accounts:u(i({source_id:t().min(1),model_ids:u(t().min(1)).optional()}))}))});function ee(e){let r=X.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 ne=["minimal","low","medium","high","xhigh","max"],te=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()}))}),se=i({devices:u(te),end_cursor:t().nullish(),has_next_page:d().optional()}),oe=i({id:t().min(1),name:t()}),re=i({items:u(oe)}),ie=i({id:t().min(1),name:t(),main:d(),mine:d(),session_id:t().nullish(),appearance:i({color:t().nullish()}).nullish().catch(null)}),ae=i({items:u(ie)}),le=i({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:u(t()).default([]),is_enabled:d().default(!0)}),ce=i({items:u(le).default([])}),de=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()}),C=i({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:d(),triggers:u(de).default([])}),me=i({items:u(C).default([]),end_cursor:t().nullish(),has_next_page:d().optional()}),ue=i({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:d()}),ge=i({items:u(ue).default([])}),he=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()}),x=i({tags:u(t()).default([])}),pe=s(["linux","macos"]),A=i({id:t().min(1),name:t().min(1),platform:pe.nullable(),workers:i({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:i({queued:o().int(),running:o().int()})}),fe=i({machines:u(A)}),ye=i({machine:A}),_e=i({deleted:n(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),be=i({token:i({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),U=ss({machine_id:t().min(1),machine_name:t().min(1)}),Re=U.extend({organization_id:t().min(1)}),We=i({id:t().min(1),name:t().min(1),state:s(["waiting","placed"]),queue_position:o().int().nullable()});var Ve=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 we=i({error:i({type:t(),message:t()})});function q(e,r,a){let l=we.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 _s(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 q(r.status,a,r.headers.get("retry-after"));return h(Re,a,"invalid_machine_ticket")}class Go{options;credentials;constructor(e,r={}){this.options=r;this.credentials=e}trackEvent(e,r={}){}async request(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},body:r.raw?r.raw.bytes:r.body===void 0?void 0:JSON.stringify(r.body),signal:r.signal,redirect:"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.request(e,r,!0)}if(!c.ok)throw q(c.status,m,c.headers.get("retry-after"));return 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(fe,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(ye,r,"invalid_machine").machine}async deleteMachine(e){let r=await this.request(this.machinePath(e),{method:"DELETE"});return h(_e,r,"invalid_machine_deletion")}async createMachineToken(e){let r=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return h(be,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(U,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(k,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=re.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(ae,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(ce,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=se.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:ne.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 S(r.reason_version)?r.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=Z.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let r;try{r=ee(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 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(x,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(x,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(he,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(me,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(C,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(ge,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,_s,Go};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{ii,bt,si,ai,ci,Oi}from"./vm-hands-entry-lite-9wa2y4x0.js";import{createHash as H,randomBytes as he}from"crypto";import{closeSync as Ae,fsyncSync as xe,mkdirSync as Xe,openSync as Oe,renameSync as Qe,rmSync as Ze,statSync as De,writeSync as Me,constants as W}from"fs";import{join as se}from"path";var en=1;var oe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function pe(e){if(e.environment!==void 0||e.payload.environment!==void 0)throw new l("vm_hands_bind_invalid","bind carries a plaintext environment");if(e.payload.vm_hands_env_deferred===!0&&e.environment_sealed!==void 0)throw new l("vm_hands_bind_invalid","split bind carries an environment");return e.environment_sealed!==void 0}function Te(e,n){let{payload:i,authority:r}=e;if(!i||typeof i!=="object"||Array.isArray(i)||!r||typeof r!=="object"||Array.isArray(r)||!n.deviceId||!n.rootId||i.run_id!==n.runId||i.device_id!==n.deviceId||r.device_id!==n.deviceId||i.root_id!==n.rootId||n.snapshotId!==void 0&&i.snapshot_id!==n.snapshotId)throw new l("vm_hands_env_invalid","environment does not match this Hands");return i}function ve(e){if(e.capability!=="hands.connect")throw new l("vm_hands_bind_invalid","not a hands.connect claim");let n=e.payload;return{kind:"vm_hands.bind",v:1,bind_id:e.attempt_id,attempt_id:e.attempt_id,attempt_token:e.attempt_token,run_id:e.run_id,session_id:typeof n.workspace_id==="string"&&oe.test(n.workspace_id)?n.workspace_id:e.run_id,brain_generation:n.target_generation,fence_id:n.target_fence_id,lease_until:e.lease_until,policy:{agent_profile:"",confinement_key:String(n.hands_confinement??""),browser_egress:n.browser_egress??null,policy_digest:n.vm_hands_policy_digest},cwd:typeof n.cwd==="string"?n.cwd:"",claim:e,env:pe(e)?e.environment_sealed:null,workspace_deferred:nn(e)}}function nn(e){let n=e.payload[si];if(n===void 0)return!1;if(n!==!0||e.payload.vm_hands_env_deferred!==!0||e.environment_sealed!==void 0)throw new l("vm_hands_bind_invalid","a pre-bind must be environment-less");return!0}class l extends Error{code;constructor(e,n){super(n);this.code=e}}function Re(e,n){if(e instanceof l)return e;let i=e&&typeof e==="object"&&"code"in e&&typeof e.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(e.code)?e.code:"vm_hands_bind_failed";return new l(i,n)}var G=(e)=>Buffer.from(e instanceof Uint8Array?e:new Uint8Array(e)).toString("base64url"),K=(e)=>new Uint8Array(Buffer.from(e,"base64url"));function V(e){if(e===null||typeof e!=="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(V).join(",")}]`;return`{${Object.keys(e).sort().map((n)=>`${JSON.stringify(n)}:${V(e[n])}`).join(",")}}`}async function Fi(e){let n=await crypto.subtle.importKey("pkcs8",K(e.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),i=K(e.device_key.spki),r=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),h=new Uint8Array(await crypto.subtle.exportKey("spki",r.publicKey)),m=H("sha256").update(i).digest("base64url");return{signing:{privateKey:n},agreement:r,signingSpki:i,agreementSpki:h,fingerprint:m}}var tn=16;class ln{init;keys;hooks;options;identity="identity_free";lastBrainGeneration=new Map;rebindableGeneration=new Map;bound=new Map;binding=new Map;unbinding=new Set;servedRun=!1;bootKillPending=!1;unverified=new Set;unverifiedTeardowns=new Map;grants=new Map;structural=Promise.resolve();exclusive(e){let n=this.structural.then(e,e);return this.structural=n.catch(()=>{return}),n}constructor(e,n,i,r){this.init=e;this.keys=n;this.hooks=i;this.options=r;if(!oe.test(e.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(e.workspace_id))throw new l("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(e.instance_generation)||e.instance_generation<1)throw new l("vm_hands_layout_invalid","bad generation")}get phase(){if(this.identity==="identity_free")return"identity_free";if(this.unbinding.size)return"unbinding";return this.bound.size||this.binding.size?"bound":"registered"}isBoundRun(e){for(let n of this.bound.values())if(n.runId===e)return!0;return!1}bindIdForRun(e){for(let n of this.bound.values())if(n.runId===e)return n.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}get liveSessionIds(){return[...new Set([...this.bound.values()].map((e)=>e.sessionId.toLowerCase()))]}get settingUp(){return this.binding.size>0}async environmentInstalled(e,n,i){for(let r=Date.now()+n;;){let h=this.bound.get(e);if(!h)return!1;if(h.envInstalled)return!0;if(Date.now()>=r||i?.aborted)return!1;await new Promise((m)=>setTimeout(m,25))}}canSpawn(e){for(let n of this.bound.values())if(n.runId===e)return n.envInstalled;return!1}async registerFrame(e){if(this.identity!=="identity_free")throw new l("vm_hands_register_twice","already registered");if(typeof e!=="string"||e.length<16||e.length>256)throw new l("vm_hands_challenge_invalid","bad register challenge");let n={challenge:e,t:"register",v:en,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:G(this.keys.signingSpki),env_public_key:G(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:G(he(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},i=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(V(n)));return{...n,device_signature:G(i)}}async helloFrame(e,n){if(this.identity==="identity_free")throw new l("vm_hands_not_registered","hello before register");let i=String((this.options.now??Date.now)()),r=G(he(32)),h=Oi({method:"GET",pathAndQuery:ii,timestamp:i,nonce:r,challenge:e,bodySha256:H("sha256").update("").digest("hex")}),m=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(h)));return{t:"hello",timestamp:i,nonce:r,signature:G(rn(m)),...n?{vm_hands_previous_connection:n}:{}}}registered(){if(this.identity!=="identity_free")throw new l("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(e){if(this.identity!=="registered")throw new l("vm_hands_not_registered","bind before register");if(e.kind!=="vm_hands.bind"||e.v!==1)throw new l("vm_hands_bind_invalid","bad bind");for(let r of[e.bind_id,e.attempt_id,e.run_id,e.session_id,e.fence_id])if(!oe.test(r))throw new l("vm_hands_bind_invalid","bad id");let n=this.lastBrainGeneration.get(e.run_id)??0;if(!Number.isSafeInteger(e.brain_generation)||e.brain_generation<n||e.brain_generation===n&&this.rebindableGeneration.get(e.run_id)!==n)throw new l("vm_hands_generation_stale","brain generation not strictly higher");if(e.env&&(e.env.aad!==e.bind_id||e.env.alg!=="ECDH-P256+A256GCM"))throw new l("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(e.policy.policy_digest))throw new l("vm_hands_bind_invalid","bad policy or nonce");if(H("sha256").update(V({hands_confinement:e.policy.confinement_key||null,browser_egress:e.policy.browser_egress??null})).digest("hex")!==e.policy.policy_digest)throw new l("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(e.bind_id)||[...this.bound.values()].some((r)=>r.runId===e.run_id)||[...this.binding.values()].includes(e.run_id))throw new l("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=tn)throw new l("vm_hands_busy","every bind slot is held");if([...this.grants.values()].some((r)=>r.sessionId===e.session_id))throw new l("vm_hands_busy","a bind of this Session waits for its workspace beside the setup");if(this.lastBrainGeneration.set(e.run_id,e.brain_generation),this.rebindableGeneration.delete(e.run_id),this.binding.set(e.bind_id,e.run_id),e.workspace_deferred){let r,h,m=new Promise((_,k)=>{r=_,h=k});return m.catch(()=>{return}),this.grants.set(e.bind_id,{sessionId:e.session_id,promise:m,resolve:r,reject:h}),this.setUpDeferred(e)}return this.exclusive(()=>this.setUp(e))}liveCgroupBindsBut(e){return[...new Set([...this.bound.keys(),...this.binding.keys()])].filter((n)=>n!==e)}async setUpDeferred(e){let n=this.grants.get(e.bind_id);try{await this.exclusive(()=>this.prepareBind(e))}catch(v){throw this.binding.delete(e.bind_id),this.grants.delete(e.bind_id),this.rebindableGeneration.set(e.run_id,e.brain_generation),Re(v,"the bind's kill-verify failed")}let i,r=new Promise((v)=>{i=v}),h=!1,m=!1,_=()=>{m=!0,i()},k=n.promise.then(()=>new Promise((v,I)=>{this.exclusive(async()=>{if(m){I(new l("vm_hands_bind_lost","the pre-bind ended before its turn"));return}h=!0;try{if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({keep:[...this.liveCgroupBindsBut(e.bind_id),e.bind_id]}),this.unverified.clear();v()}catch(w){I(w)}await r})}));k.catch(()=>{return});try{return await this.setUp(e,{workspaceGrant:k,inTurn:()=>h,leave:_})}finally{_()}}async prepareBind(e){if(this.bootKillPending&&!this.servedRun){try{await this.hooks.killProbe()}catch{throw new l("vm_hands_kill_unverified","the boot's scoped kill did not verify")}this.bootKillPending=!1}let n=this.liveCgroupBindsBut(e.bind_id);if(this.unverified.size>0)await this.hooks.killAndVerifyPayload(n.length?{keep:n}:void 0),this.unverified.clear();this.servedRun=!0}async setUp(e,n){let i=null,r=!1;try{if(!n)await this.prepareBind(e);r=!0;let{launchId:h,applied:m,readyData:_}=await this.hooks.startExecutor({bindId:e.bind_id,sessionId:e.session_id,policyDigest:e.policy.policy_digest,confinementKey:e.policy.confinement_key,browserEgress:e.policy.browser_egress,cwd:e.cwd,claim:e.claim,...n?{workspaceGrant:n.workspaceGrant}:{}}),k=this.hooks.restatLayout(e.session_id);this.hooks.verifyMounts?.(e.session_id);let v=null,I=null;if(e.env){let w=e.claim?.owner??{},E=Te(await this.openSealed(e.env,e.bind_id),{runId:e.run_id,deviceId:typeof w.device_id==="string"?w.device_id:"",rootId:e.claim?.root_id??""});v=this.hooks.installEnvironment(e.bind_id,E),I=typeof E.snapshot_id==="string"&&E.snapshot_id?E.snapshot_id:null,i=this.writeJobEnvRootOnly(e.bind_id,E)}if(this.unbinding.has(e.bind_id))throw new l("vm_hands_bind_lost","unbound while binding");return this.bound.set(e.bind_id,{bindId:e.bind_id,runId:e.run_id,sessionId:e.session_id,brainGeneration:e.brain_generation,policyDigest:e.policy.policy_digest,launchId:h,envInstalled:v!==null,rootId:e.claim?.root_id??"",envDirectory:i}),this.binding.delete(e.bind_id),this.grants.delete(e.bind_id),{bind_id:e.bind_id,attempt_id:e.attempt_id,attempt_token:e.attempt_token,launch_id:h,snapshot_revision:v,snapshot_id:I,layout:k,..._?{ready_data:_}:{},policy_digest:H("sha256").update(V({hands_confinement:m.hands_confinement??null,browser_egress:m.browser_egress??null})).digest("hex")}}catch(h){if(i)fe(i);if(r){let m=()=>this.hooks.killAndVerifyPayload({bindId:e.bind_id,keep:this.liveCgroupBindsBut(e.bind_id),own:!0}).catch(()=>{this.unverified.add(e.bind_id)});if(n&&!n.inTurn())n.leave(),await this.exclusive(m);else await m()}throw this.binding.delete(e.bind_id),this.grants.delete(e.bind_id),this.rebindableGeneration.set(e.run_id,e.brain_generation),Re(h,"executor refused the bind")}}grantWorkspace(e){let n=this.grants.get(e);if(!n)throw new l("vm_hands_not_binding","no pre-bind waits for a workspace grant");n.resolve()}abandonWorkspaceGrant(e){this.grants.get(e)?.reject(new l("vm_hands_bind_lost","the pre-bind ended before its workspace grant"))}async deliverEnvironment(e){let n=this.bound.get(e.attemptId);if(!n||this.unbinding.has(e.attemptId))throw new l("vm_hands_not_bound","environment delivered while not bound");if(!oe.test(e.attemptId)||typeof e.snapshotId!=="string"||!e.snapshotId||e.snapshotId.length>128||e.snapshotId.includes("/"))throw new l("vm_hands_env_invalid","bad snapshot id");let i=`${e.attemptId}/${e.snapshotId}`;if(e.sealed?.alg!=="ECDH-P256+A256GCM"||e.sealed.aad!==i)throw new l("vm_hands_env_invalid","bad env envelope");let r=Te(await this.openSealed(e.sealed,i),{runId:n.runId,deviceId:e.deviceId,rootId:n.rootId,snapshotId:e.snapshotId}),h=this.hooks.installEnvironment(n.bindId,r);if(n.envInstalled=!0,n.envDirectory)fe(n.envDirectory);return n.envDirectory=null,n.envDirectory=this.writeJobEnvRootOnly(`${n.bindId}-r${h}`,r),{snapshot_id:e.snapshotId,installed_revision:h,installed:!0}}async attestFrame(e,n){if(this.identity==="identity_free")throw new l("vm_hands_not_registered","attest before register");if(!e||e.length>65536)throw new l("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new l("vm_hands_attest_invalid","attest beside a bind");let i=await this.hooks.runProbe({nonce:n,script:e});try{await this.hooks.killProbe()}catch{this.bootKillPending=!0}return{t:"attest",nonce:n,exit_code:i.exitCode,markers:i.markers,proof_dir_inode:i.proofDirInode,script_sha256:H("sha256").update(e).digest("hex")}})}executorExited(e){return this.hooks.executorExited?.(e)??new Promise(()=>{})}async boundRefused(e){await this.unbind(e)}async unbind(e){let n=this.bound.get(e)??null;if(this.unbinding.add(e),this.bound.delete(e),this.abandonWorkspaceGrant(e),n)try{this.hooks.freezeBind?.(e)}catch{}return this.exclusive(()=>this.tearDown(e,n))}async retryUnbind(e){if(!this.unverifiedTeardowns.has(e))throw new l("vm_hands_unbind_unknown","no unverified unbind of this bind");return this.exclusive(async()=>{if(!this.unverifiedTeardowns.has(e))throw new l("vm_hands_unbind_unknown","no unverified unbind of this bind");return this.tearDown(e,this.unverifiedTeardowns.get(e)??null,!0)})}async tearDown(e,n,i=!1){try{this.bound.delete(e);let r=this.liveCgroupBindsBut(e);try{await this.hooks.killAndVerifyPayload({bindId:e,keep:r})}catch(h){if(this.unverified.add(e),!this.unverifiedTeardowns.has(e))this.unverifiedTeardowns.set(e,n);throw h}if(this.unverified.delete(e),!r.length&&!i)this.unverified.clear();if(n?.envDirectory)fe(n.envDirectory);if(this.unverifiedTeardowns.delete(e),n&&this.lastBrainGeneration.get(n.runId)===n.brainGeneration)this.rebindableGeneration.set(n.runId,n.brainGeneration);return{bind_id:n?e:null,killed_verified:!0,shredded:!0,srt_fallbacks:r.length||i?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(e)}}async openSealed(e,n){let i=()=>{throw new l("vm_hands_env_invalid","env did not decrypt")},r=await crypto.subtle.importKey("spki",K(e.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(i),h=await crypto.subtle.deriveKey({name:"ECDH",public:r},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),m=await crypto.subtle.decrypt({name:"AES-GCM",iv:K(e.iv),additionalData:new TextEncoder().encode(n)},h,K(e.ct)).catch(i),_=JSON.parse(new TextDecoder().decode(m));if(!_||typeof _!=="object"||Array.isArray(_))throw new l("vm_hands_env_invalid","env not an object");return _}writeJobEnvRootOnly(e,n){let i=se(this.options.envRoot,`bind-${e}`);Xe(i,{mode:448});let r=De(i);if(!r.isDirectory()||(r.mode&63)!==0||r.uid!==(process.getuid?.()??-1))throw new l("vm_hands_env_dir_unsafe","env directory is not root's 0700");let h=n.variables&&typeof n.variables==="object"?n.variables:{},m=Object.entries(h).filter(([v,I])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(v)&&typeof I==="string").map(([v,I])=>`export ${v}='${String(I).replaceAll("'","'\\''")}'`).join(`
|
|
3
3
|
`)+`
|
|
4
|
-
`,_=se(i,`.job.env.${he(8).toString("hex")}`),k=Oe(_,W.O_WRONLY|W.O_CREAT|W.O_EXCL|W.O_NOFOLLOW,384);try{Me(k,m),xe(k)}finally{Ae(k)}return Qe(_,se(i,"job.env")),i}}function fe(e){try{let n=se(e,"job.env"),i=De(n).size,r=Oe(n,W.O_WRONLY|W.O_NOFOLLOW);try{Me(r,Buffer.alloc(i)),xe(r)}finally{Ae(r)}}catch{}Ze(e,{recursive:!0,force:!0})}function rn(e){if(e.length!==64)throw new l("vm_hands_signature_invalid","unexpected ECDSA signature length");let n=(h)=>{let m=0;while(m<h.length-1&&h[m]===0)m++;let _=h.subarray(m),k=_[0]&128?Uint8Array.of(0,..._):_;return Uint8Array.of(2,k.length,...k)},i=n(e.subarray(0,32)),r=n(e.subarray(32));return Uint8Array.of(48,i.length+r.length,...i,...r)}import{randomUUID as sn}from"crypto";var on="/app/local-runtime/session?register=vm_hands_v1",an="/app/local-runtime",Ce=25000,we=20000,dn=1e4,Ue=5000,cn=new Set(["pty.start","jobs.control","tunnel.open","tunnel.close"]),un="preview.serve.v1",_n=60000,ye=75000,mn=2000,gn=1e4,hn=new Set(["vm_hands_no_register","vm_hands_register_failed"]),fn=3,pn=20000,vn=250,wn=2000;function $e(e){let n=Math.min(vn*2**(e-1),wn);return Math.round(n/2+Math.random()*n/2)}var yn=5000;function bn(e){return e>=500||e===408||e===429}var ae=20000;function Be(e,n){return typeof e==="string"&&/^[A-Za-z0-9._:-]{1,160}$/.test(e)?e:n}class D extends Error{}var kn=64,qe=[1000,2000,4000,8000,15000,30000,60000,120000];function je(e){let n=e&&typeof e==="object"&&"code"in e?e.code:null;return typeof n==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(n)?n:"vm_hands_unbind_failed"}function Sn(e,n,i,r,h){let m=i.turn.claim.attempt_id,_=e.healing??=new Set;if(_.has(m))return;_.add(m);let k=i.turn.claim.operation_id;(async()=>{for(let[v,I]of qe.entries()){if(r.aborted)return;if(await new Promise((w)=>{let E=setTimeout(w,I);E.unref?.(),r.addEventListener("abort",()=>{clearTimeout(E),w()},{once:!0})}),r.aborted)return;try{let w=await n.retryUnbind(m);h("vm_hands.unbind_healed",{operation_id:k,attempt:v+1}),e.receipts.push({...i,unbound:w}),e.flushReceipts?.();return}catch(w){let E=je(w);if(h("vm_hands.unbind_unverified",{operation_id:k,code:E,attempt:v+1}),E==="vm_hands_unbind_unknown")return}}h("vm_hands.unbind_heal_exhausted",{operation_id:k,attempts:qe.length})})().finally(()=>_.delete(m))}async function Ge(e,n){let i=[...e.modelOps.get(n)??[]];for(let r of i)r.abort.abort();await Promise.race([Promise.all(i.map((r)=>r.settled)),new Promise((r)=>setTimeout(r,Ue))])}async function In(e,n){let i=[...e.personTerminals].filter((r)=>r.session===null||r.session===n);for(let r of i)r.abort.abort();if(i.length)await Promise.race([Promise.all(i.map((r)=>r.settled)),new Promise((r)=>setTimeout(r,Ue))]);return i.length}function Pn(e){let n=e.payload,i=n?.workspace?.kind==="managed"?n.workspace.workspaceId:void 0;return typeof i==="string"&&/^[0-9a-f-]{36}$/i.test(i)?i.toLowerCase():null}async function L(e,n,i){return await Ge(e,i),n.unbind(i)}function de(e){for(let n of e.outbox?.splice(0)??[])n.reject(Error("vm_hands_attempt_ended"))}var Ne=15000,En=1e4,Tn=1000;async function ji(e){let n=Date.now(),i={deviceId:null,connection:null,turns:new Map,lostAt:0,receipts:[],attest:"pending",attestWaiters:[],modelOps:new Map,personTerminals:new Set,bindsStarting:new Map},r=e.log??(()=>{}),h=async(k)=>{for(let[v,I]of[...i.turns]){i.turns.delete(v),e.onTurn?.(v,null),de(I);let w=await L(i,e.agent,v).catch(()=>null);if(w)i.receipts.push({turn:I,failure:"vm_hands_bind_lost",unbound:w});r("vm_hands.bound_dropped",{reason:k})}},m=0,_=0;try{for(let k=0;!e.signal.aborted;k++){let v=await Rn(e,i).catch((w)=>{if(w instanceof l&&i.deviceId===null&&w.code==="vm_hands_no_session"&&Date.now()-n<gn)return{closeCode:0,closeReason:"vm_hands_no_session"};if(w instanceof l&&i.deviceId===null&&hn.has(w.code)&&m<fn&&Date.now()-n<pn)return m++,_=$e(m),r("vm_hands.register_retry",{attempt:m,code:w.code,delay_ms:_}),{closeCode:0,closeReason:"vm_hands_register_retry"};if(w instanceof l&&i.deviceId===null)throw w;return{closeCode:0,closeReason:w instanceof Error?w.message:String(w)}});if(r("vm_hands.session_closed",{close_code:v.closeCode,reason:v.closeReason.slice(0,120),registered:i.deviceId!==null}),v.closeCode===4401||i.attest==="refused")return;if(e.signal.aborted)return;if(i.turns.size&&Date.now()-i.lostAt>=ye)await h("reconnect_deadline");if(i.served)i.served=!1,k=0;let I=v.closeReason==="drain_reconnect"?0:v.closeReason==="vm_hands_register_retry"?_:v.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(k,5),2000):i.turns.size?Math.min(250*2**Math.min(k,5),5000,Math.max(0,i.lostAt+ye-Date.now())):Math.min(500*2**k,30000);if(await new Promise((w)=>setTimeout(w,I)),i.turns.size&&Date.now()-i.lostAt>=ye)await h("reconnect_deadline")}}finally{await h("session_ended")}}async function Rn(e,n){let i=n.deviceId,r=e.log??(()=>{}),h=i?`/app/local-runtime/session?device_id=${encodeURIComponent(i)}`:on,m=`${e.apiOrigin.replace(/^http/,"ws")}${h}`,_=new WebSocket(m),k=0,v="",I=new Map,w=[],E=null,ce=new Promise((t)=>{_.onclose=(o)=>{k=o.code,v=o.reason;for(let s of I.values())s.reject(new D(`session closed ${o.code}`));for(let s of n.attestWaiters.splice(0))s(!1);I.clear(),t()}});_.onmessage=(t)=>{let o;try{o=JSON.parse(String(t.data))}catch{_.close(4400);return}if(o.t==="res"){let s=o;I.get(s.id)?.resolve({status:s.status,body:s.body}),I.delete(s.id);return}if(o.t==="reconnect"){let s=Math.max(0,Math.min(Number(o.after_ms)||0,Tn));r("vm_hands.drain_reconnect",{after_ms:s}),setTimeout(()=>{try{_.close(4001,"drain_reconnect")}catch{}},s).unref?.();return}if(!E?.(o))w.push(o)};let J=(t,o)=>new Promise((s,a)=>{let u=w.findIndex((p)=>t.includes(p.t));if(u>=0){s(w.splice(u,1)[0]);return}let f=setTimeout(()=>{E=null,a(new l("vm_hands_no_register",`no ${t.join("/")} in ${o} ms`))},o);E=(p)=>{if(!t.includes(p.t))return!1;return clearTimeout(f),E=null,s(p),!0}}),Y=(t)=>_.send(JSON.stringify(t)),q=(t,o)=>new Promise((s,a)=>{if(_.readyState!==WebSocket.OPEN){a(new D("session closed"));return}let u=sn(),f=typeof o.wait_ms==="number"?o.wait_ms:0,p=setTimeout(()=>{if(!I.delete(u))return;a(new D(`no answer to ${t.split("/").pop()} in ${f+Ne} ms`)),_.close(4000,"request_timeout")},f+Ne);I.set(u,{reject:(c)=>{clearTimeout(p),a(c)},resolve:({status:c,body:d})=>{clearTimeout(p);let g=null;try{g=d?JSON.parse(d):null}catch{}s({status:c,json:g})}}),Y({t:"req",id:u,path:`${an}${t}`,body:JSON.stringify(o)})}),be=()=>_.close(1001,"stopping");e.signal.addEventListener("abort",be,{once:!0});let le,X=new Map,Q=new Map,ue=!1,_e=new Set,me=Promise.resolve(),ke=()=>{ne().catch(()=>{return})},Z=!1;try{await new Promise((c,d)=>{let g=setTimeout(()=>d(Error("session open timeout")),En);_.onopen=()=>{clearTimeout(g),r("vm_hands.ws_open",{}),c()},_.onerror=()=>{clearTimeout(g),d(Error("session socket error"))}});let t=await J(["challenge"],5000);r("vm_hands.challenge",{});let o=[],s=null,a;if(i){Y(await e.agent.helloFrame(t.challenge,n.connection));let c=await J(["ready"],1e4);if(typeof c.vm_hands_connection==="string")n.connection=c.vm_hands_connection;if(a={device_id:i,...c.cadence?{cadence:c.cadence}:{}},typeof c.vm_hands_probe_script==="string"){if(s=c.vm_hands_probe_script,Z=!0,e.agent.phase==="registered"&&!n.turns.size)n.attest="pending"}n.served=!0,r("vm_hands.reconnected",{device_id:i});let d=Array.isArray(c.vm_hands_binds)?c.vm_hands_binds:c.vm_hands_bind?[c.vm_hands_bind]:[];for(let[g,S]of[...n.turns]){if(d.some((T)=>T&&T.operation_id===S.claim.operation_id&&T.attempt_id===S.claim.attempt_id)){o.push(S),r("vm_hands.bound_resumed",{operation_id:S.claim.operation_id});continue}n.turns.delete(g),e.onTurn?.(g,null),de(S);let P=await L(n,e.agent,g).catch((T)=>ee(T,S,"vm_hands_bind_lost"));if(P)n.receipts.push({turn:S,failure:"vm_hands_bind_lost",unbound:P});r("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}else{Y(await e.agent.registerFrame(t.challenge)),r("vm_hands.register_sent",{});let c=await Promise.race([J(["registered","register_refused"],1e4),ce.then(()=>{throw new l(v==="register_failed"?"vm_hands_register_failed":"vm_hands_register_closed","session closed before the register was answered")})]);if(c.t==="register_refused")throw new l(c.code,"register refused");e.agent.registered();let d=c;if(a=d,n.deviceId=d.device_id,typeof d.vm_hands_connection==="string")n.connection=d.vm_hands_connection;if(typeof d.vm_hands_probe_script==="string"){if(s=d.vm_hands_probe_script,Z=!0,e.agent.phase==="registered"&&!n.turns.size)n.attest="pending"}n.served=!0,r("vm_hands.registered",{device_id:a.device_id})}let u=async()=>{let c=await q("/heartbeat",await e.heartbeat());if(c.status>=300)throw Error(`heartbeat ${c.status}`)};await u();let f=a.cadence?.presence_interval_ms??30000;if(le=setInterval(()=>{u().catch(()=>_.close())},f),e.onHeartbeatNow?.(()=>{u().catch(()=>_.close())}),n.request=q,ce.then(()=>{if(n.request===q)n.request=null}),s&&n.attest!=="accepted"&&e.agent.phase==="registered"&&!n.turns.size)ze(s,t.challenge);let p=(c,d)=>{Q.set(c,d().catch(async(g)=>{if(await Se(g,c),g instanceof D)_.close();else await ne().catch(()=>{return})}).finally(()=>{Q.delete(c)}))};n.flushReceipts=ke;try{await ne();for(let c of o)c.flush=()=>Ie(c),c.flush(),p(c.claim.attempt_id,()=>Pe(c));while(!e.signal.aborted&&_.readyState===WebSocket.OPEN){let c=await q("/operations/claim",{wait_ms:Math.min(a.cadence?.claim_wait_ms??Ce,Ce)});if(c.status===204||!c.json)continue;if(c.status>=300)throw Error(`claim ${c.status}`);let d=c.json;if(d.capability==="hands.connect"){if(Q.has(d.attempt_id)){O({claim:d,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}p(d.attempt_id,()=>Fe(d))}else Ke(d).catch(()=>{return})}}catch(c){await Se(c,null)}}finally{if(le)clearInterval(le);e.signal.removeEventListener("abort",be);for(let t of n.turns.values())t.flush=null;if(n.flushReceipts===ke)n.flushReceipts=null;_.close(),await ce,await Promise.all([...Q.values()]);for(let t of e.agent.liveBindIds){if(n.turns.has(t))continue;let o=X.get(t),s=o?{...o,eventSeq:o.eventSeq+1}:null,a=await L(n,e.agent,t).catch((u)=>s?ee(u,s,"vm_hands_bind_lost"):null);if(a&&s)n.receipts.push({turn:s,failure:"vm_hands_bind_lost",unbound:a});r("vm_hands.bound_dropped",{reason:"bound_after_loss"})}}return{closeCode:k,closeReason:v};async function Se(t,o){if(t instanceof D){if(!ue&&n.turns.size)n.lostAt=Date.now();ue=!0}else{let s=o!==null?[o]:[...new Set([...n.turns.keys(),...e.agent.liveBindIds])];if(o===null)ue=!0;for(let a of s){let u=n.turns.get(a);if(n.turns.delete(a),u)de(u),e.onTurn?.(a,null);if(e.agent.liveBindIds.includes(a)){let f=X.get(a)??u,p=f?{...f,eventSeq:f.eventSeq+1}:null,c=await L(n,e.agent,a).catch((d)=>p?ee(d,p,"vm_hands_bind_lost"):null);if(c&&p)n.receipts.push({turn:p,failure:"vm_hands_bind_lost",unbound:c})}}}r("vm_hands.session_lost",{error:t instanceof Error?t.message:String(t),bound_kept:n.turns.size})}function O(t,o=q){let s=o,a=t.claim,u={attempt_id:a.attempt_id,attempt_token:a.attempt_token},f=encodeURIComponent(a.operation_id);return{fence:u,op:f,complete:(c,d={})=>s(`/operations/${f}/complete`,{...u,status:c,...d}),emit:(c,d)=>{let g=(t.chain??Promise.resolve()).catch(()=>{return}).then(()=>p(c,d));return t.chain=g,g}};async function p(c,d){let g=t.eventSeq,S=(R)=>s(`/operations/${f}/events`,{...u,event_seq_start:R,events:[{kind:c,payload:{sequence:R,capability:String(a.capability??"hands.connect"),data:d}}]}),P=g,T=await S(P),M=T.status===409?T.json?.expected_event_seq:void 0;if(typeof M==="number"&&M>=0&&M!==g)P=M,T=await S(P);if(T.status<300)t.eventSeq=P+1;return T}}function We(t){return(o,s)=>new Promise((a,u)=>{if(n.turns.get(t.claim.attempt_id)!==t){u(Error("vm_hands_attempt_ended"));return}if(t.outbox??=[],t.outbox.length>=kn){u(Error("vm_hands_outbox_full"));return}t.outbox.push({kind:o,data:s,resolve:a,reject:u}),t.flush?.()})}function Ie(t){if(_e.has(t))return;_e.add(t),(async()=>{try{while(t.outbox?.length&&n.turns.get(t.claim.attempt_id)===t&&_.readyState===WebSocket.OPEN){let o=t.outbox[0],s;try{s=await O(t).emit(o.kind,o.data)}catch(a){if(a instanceof D)return;s={status:500}}if(t.outbox.shift(),s.status<300)o.resolve();else o.reject(Error(`${o.kind} refused ${s.status}`))}}finally{_e.delete(t)}})()}async function ze(t,o){try{let s=await e.agent.attestFrame(t,o);if(_.readyState!==WebSocket.OPEN)return;Y(s);let a=await J(["attested","attest_refused"],15000);n.attest=a.t==="attested"?"accepted":"refused";for(let u of n.attestWaiters.splice(0))u(n.attest==="accepted");if(r("vm_hands.attest",{result:n.attest,exit_code:s.exit_code,...a.t==="attest_refused"?{code:String(a.code??"")}:{}}),n.attest==="refused")_.close(4401,"attest_refused")}catch(s){r("vm_hands.attest_failed",{code:s instanceof l?s.code:"probe_error"});for(let a of n.attestWaiters.splice(0))a(!1);if(n.attest!=="accepted")_.close(4000,"attest_unanswered")}}async function Fe(t){let o=Z&&n.attest==="pending",s=t.vm_hands_attest,a=s;if(n.attest==="refused"){r("vm_hands.claim_attest_refused",{said:typeof s==="string"?s.slice(0,16):typeof s,local:n.attest}),await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(a==="accepted"){if(!o&&n.attest!=="accepted"){n.attest="accepted";for(let b of n.attestWaiters.splice(0))b(!0)}}else if(a!=="pending"||!o&&n.attest!=="accepted"){r("vm_hands.claim_attest_refused",{said:typeof s==="string"?s.slice(0,16):typeof s,local:n.attest}),await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(n.attest!=="accepted"){let b=Date.parse(t.lease_until)-Date.now()-5000,B=Math.max(0,Math.min(ae,Number.isFinite(b)?b:ae));if(!await new Promise((ie)=>{let y=setTimeout(()=>ie(!1),B);n.attestWaiters.push((x)=>{clearTimeout(y),ie(x)})})){await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let u={claim:t,eventSeq:0},{complete:f,emit:p}=O(u),c;try{if(t.capability!=="hands.connect")throw new l("vm_hands_bind_invalid","not hands.connect");c=!pe(t)}catch(b){r("vm_hands.bind_refused",{code:b instanceof l?b.code:"unexpected"}),await f("failed",{error_code:b instanceof l?b.code:"vm_hands_bind_invalid"});return}let d,g=null,S=!1,P=(()=>{try{return ve(t).session_id.toLowerCase()}catch{return String(t.run_id)}})();n.bindsStarting.set(P,(n.bindsStarting.get(P)??0)+1);try{let b=await In(n,P);if(b)r("vm_hands.person_terminals_closed",{count:b});let B=ve(t),j=e.agent.bind(B);if(B.workspace_deferred)S=!0,g=He(u,()=>S);d=await j}catch(b){r("vm_hands.bind_refused",{code:b instanceof l?b.code:"unexpected"}),await f("failed",{error_code:b instanceof l?b.code:"vm_hands_bind_failed"});return}finally{S=!1;let b=(n.bindsStarting.get(P)??1)-1;if(b>0)n.bindsStarting.set(P,b);else n.bindsStarting.delete(P)}let T=g?await g:-1,M={...d.ready_data??e.readyData({launchId:d.launch_id,claim:t})};if(c)delete M.environment_installed;let R=!c&&d.snapshot_revision!==null&&d.snapshot_id!==null?{environment_installed:{snapshot_id:d.snapshot_id,installed_revision:d.snapshot_revision}}:{};X.set(t.attempt_id,{claim:t,launchId:d.launch_id,readyData:M,eventSeq:u.eventSeq,ackSeq:-1});let F={...M,...R,vm_hands:{layout:d.layout,policy_digest:d.policy_digest,launch_id:d.launch_id}},te=Date.now()+yn,U=1,N=await p("hands.ready",F);while(bn(N.status)&&!e.signal.aborted){let b=$e(U);if(Date.now()+b>=te)break;await new Promise((B)=>setTimeout(B,b)),U++,N=await p("hands.ready",F)}if(U>1)r("vm_hands.ready_retried",{attempts:U,status_class:`${Math.floor(N.status/100)}xx`});if(X.delete(t.attempt_id),N.status>=300){await Ge(n,t.attempt_id),await e.agent.boundRefused(t.attempt_id),await f("failed",{error_code:Be(N.json?.error,"vm_hands_probe_failed")});return}let C={claim:t,launchId:d.launch_id,readyData:M,eventSeq:u.eventSeq,ackSeq:T};n.turns.set(t.attempt_id,C),C.flush=()=>Ie(C),e.onTurn?.(t.attempt_id,We(C)),await Pe(C)}async function He(t,o){let{fence:s,op:a}=O(t),u=t.claim.attempt_id,f=-1;try{for(;;){let p=await q(`/operations/${a}/heartbeat`,{...s,control_ack_seq:f,wait_ms:we});if(!o())return f;if(p.status>=300)return e.agent.abandonWorkspaceGrant(u),f;let c=(p.json?.controls??[]).slice().sort((d,g)=>d.seq-g.seq);for(let d of c){if(d.seq<=f)continue;if(f=d.seq,d.kind===ai)return r("vm_hands.workspace_granted",{}),e.agent.grantWorkspace(u),f;return r("vm_hands.workspace_grant_abandoned",{control:/^[a-z][a-z0-9._-]{0,63}$/.test(d.kind)?d.kind:"other"}),e.agent.abandonWorkspaceGrant(u),f}}}catch{return e.agent.abandonWorkspaceGrant(u),f}}async function Pe(t){let{fence:o,op:s}=O(t),a=null,u=null,f=e.agent.executorExited(t.claim.attempt_id).then((p)=>(u=p,null));e:for(;;){let p=await Promise.race([f,q(`/operations/${s}/heartbeat`,{...o,control_ack_seq:t.ackSeq,wait_ms:we})]);if(!p){a="vm_hands_executor_exited",r("vm_hands.executor_exited",{reason:u});break}if(p.status>=300)break;let c=(p.json?.controls??[]).slice().sort((d,g)=>d.seq-g.seq);for(let d of c){if(d.seq<=t.ackSeq)continue;if(d.kind==="operation.cancel"||d.kind==="cancel"){t.ackSeq=d.seq;break e}if(d.kind===bt)try{await Le(t,d.payload??{})}catch(g){if(g instanceof D)throw g;a=g instanceof l?g.code:"environment_unavailable";let S=g&&typeof g==="object"&&"code"in g&&typeof g.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(g.code)?g.code:null;r("vm_hands.environment_refused",{code:a,cause:S});break e}t.ackSeq=d.seq}}await Ve(t,a)}async function ge(t,o){let s=Date.now()+_n;for(;;){let a=n.request;if(a)try{return await a(t,o)}catch(u){if(!(u instanceof D))throw u}if(Date.now()>=s||e.signal.aborted)throw new D("kept operation has no live session");await new Promise((u)=>setTimeout(u,500))}}async function Ke(t){let o=t,s={claim:o,eventSeq:0},a=String(t.capability??""),u=a===un,{complete:f,emit:p,fence:c,op:d}={...O(s,ge)},g=t.vm_hands_origin==="person"?"person":"model";if(!e.executeOp){await f("failed",{error_code:"vm_hands_op_unsupported"});return}if(t.vm_hands_attest==="accepted"&&n.attest==="pending"&&!(Z&&n.attest==="pending")){n.attest="accepted";for(let y of n.attestWaiters.splice(0))y(!0)}if(n.attest!=="accepted"){let y=Date.parse(String(t.lease_until??""))-Date.now()-5000,x=n.attest==="refused"?0:Math.max(0,Math.min(ae,Number.isFinite(y)?y:ae));if(!(x>0&&await new Promise((re)=>{let Je=setTimeout(()=>re(!1),x);n.attestWaiters.push((Ye)=>{clearTimeout(Je),re(Ye)})}))){await f("failed",{error_code:"vm_hands_unattested"});return}}let S=e.agent.bindIdForRun(o.run_id);if(g==="model"&&S===null){await f("failed",{error_code:"vm_hands_not_bound"});return}let P=a==="pty.start"&&g==="person"&&!t.authority,T=P?Pn(t):null;if(P&&((y)=>y===null?e.agent.liveBindIds.length>0||n.bindsStarting.size>0:e.agent.liveSessionIds.includes(y)||n.bindsStarting.has(y))(T)){await f("failed",{error_code:"vm_hands_bound"});return}if(cn.has(a)&&!P&&e.agent.liveBindIds.length===0){await f("failed",{error_code:"vm_hands_not_bound"});return}let R=new AbortController,F=()=>R.abort();e.signal.addEventListener("abort",F,{once:!0});let te,U=new Promise((y)=>{te=y}),N={abort:R,settled:U},C=P?{...N,session:T}:null;if(C)n.personTerminals.add(C);if(g==="model"&&S&&a!=="preview.serve.v1"){let y=n.modelOps.get(S)??new Set;y.add(N),n.modelOps.set(S,y),await e.agent.environmentInstalled(S,mn,R.signal)}let b=-1,B=!1,j=!1,ie=u?void 0:setInterval(()=>{if(j)return;j=!0,ge(`/operations/${d}/heartbeat`,{...c,control_ack_seq:b,wait_ms:0}).then((y)=>{if(y.status>=300){R.abort();return}let x=y.json?.controls??[];for(let A of x)if(b=Math.max(b,A.seq),A.kind==="operation.cancel"||A.kind==="cancel")R.abort()},()=>R.abort()).finally(()=>{j=!1})},dn);if(u)(async()=>{while(!B&&!R.signal.aborted){let y;try{y=await ge(`/operations/${d}/heartbeat`,{...c,control_ack_seq:b,wait_ms:we})}catch{R.abort();return}if(B)return;if(y.status>=300){R.abort();return}let x=(y.json?.controls??[]).slice().sort((A,re)=>A.seq-re.seq);for(let A of x){if(A.seq<=b)continue;if(A.kind==="operation.cancel"||A.kind==="cancel")R.abort();else await e.controlOp?.({claim:t,control:A}).catch(()=>!1);b=A.seq}}})();try{let y=await e.executeOp({kind:g,claim:t,...g==="model"&&S?{bindId:S}:{},signal:R.signal,emit:async(A)=>{await p(A.kind,A.data??{})}}),x=await f(y.status,{...y.result?{result:y.result}:{},...y.error_code?{error_code:Be(y.error_code,"vm_hands_op_failed")}:{}});e.opCompleted?.({claim:t,status:y.status,acknowledged:x.status<300}),r("vm_hands.op",{capability:a,kind:g,status:y.status,code:y.error_code??null,...x.status>=300?{complete_status:x.status,complete_error:String(x.json?.error??"").slice(0,64)}:{}})}finally{if(B=!0,clearInterval(ie),e.signal.removeEventListener("abort",F),S)n.modelOps.get(S)?.delete(N);if(C)n.personTerminals.delete(C);te()}}async function Ve(t,o){let s=t.claim.attempt_id;if(n.turns.get(s)===t)n.turns.delete(s);e.onTurn?.(s,null),de(t);let a=await L(n,e.agent,s).catch((u)=>ee(u,t,o));if(!a)return;n.receipts.push({turn:t,failure:o,unbound:a}),await ne()}function ee(t,o,s){let a=je(t);return r("vm_hands.unbind_unverified",{operation_id:o.claim.operation_id,code:a,attempt:0}),O(o).emit(ci,{code:a}).catch(()=>{return}),Sn(n,e.agent,{turn:o,failure:s},e.signal,r),null}function ne(){return me=me.then(Ee,Ee),me}async function Ee(){while(n.receipts.length){let{turn:t,failure:o,unbound:s}=n.receipts[0],{complete:a,emit:u}=O(t);try{if(await u("hands.stopped",{...t.readyData,reason_code:o?"failed":"cancelled",killed_verified:s.killed_verified,shredded:s.shredded,...s.srt_fallbacks?{vm_hands_srt_fallbacks:s.srt_fallbacks}:{}}),o)await a("failed",{error_code:o});else await a("cancelled",{error_code:"driver_stopped"})}catch(f){if(f instanceof D)return}n.receipts.shift()}}async function Le(t,o){let{fence:s,op:a}=O(t),u=o.snapshot_id;if(o.version!==1||typeof u!=="string"||Object.keys(o).length!==2)throw new l("vm_hands_env_invalid","invalid environment delivery");let f=await q(`/operations/${a}/environment`,{...s,snapshot_id:u}),p=f.json?.environment_sealed;if(f.status!==200||!p||f.json?.payload!==void 0)throw new l("vm_hands_env_invalid","environment not delivered sealed");let c=await e.agent.deliverEnvironment({attemptId:t.claim.attempt_id,snapshotId:u,deviceId:n.deviceId??"",sealed:p});if((await q(`/operations/${a}/environment-ack`,{...s,...c})).status>=300)throw new l("vm_hands_env_ack_refused","environment ack refused")}}import{readFileSync as xn}from"fs";var An=performance.now();delete process.env.BUN_BE_BUN;var z=(e,n={})=>console.log(JSON.stringify({stage:e,ms:Math.round(performance.now()),...n}));async function On(){if(process.argv.includes("--vm-hands-op-runner")){let{runVmHandsOpRunner:m}=await import("./vm-hands-op-runner-b46k10sj.js");await m();return}z("parsed",{t0:Math.round(An)});let e="";try{e=xn(3,"utf8")}catch{}z("fd3_read",{bytes:e.length});let n=null;if(e.trim())try{n=JSON.parse(e)}catch{n=null}if(!n||typeof n!=="object"||Array.isArray(n))z(e.trim()?"identity_invalid":"identity_free"),await new Promise(()=>{setInterval(()=>{return},1073741824)});let{parseVmHandsInit:i,runVmHands:r}=await import("./vm-hands-runtime-0xpt9a97.js"),h=i(n);if(!h)z("identity_invalid"),await new Promise(()=>{setInterval(()=>{return},1073741824)});try{await r(h,z)}catch(m){let _=m&&typeof m==="object"&&"code"in m&&typeof m.code==="string"?m.code:"error";throw z("failed",{code:_}),m}process.exit(0)}On();export{Fi,ln,ji};
|
|
4
|
+
`,_=se(i,`.job.env.${he(8).toString("hex")}`),k=Oe(_,W.O_WRONLY|W.O_CREAT|W.O_EXCL|W.O_NOFOLLOW,384);try{Me(k,m),xe(k)}finally{Ae(k)}return Qe(_,se(i,"job.env")),i}}function fe(e){try{let n=se(e,"job.env"),i=De(n).size,r=Oe(n,W.O_WRONLY|W.O_NOFOLLOW);try{Me(r,Buffer.alloc(i)),xe(r)}finally{Ae(r)}}catch{}Ze(e,{recursive:!0,force:!0})}function rn(e){if(e.length!==64)throw new l("vm_hands_signature_invalid","unexpected ECDSA signature length");let n=(h)=>{let m=0;while(m<h.length-1&&h[m]===0)m++;let _=h.subarray(m),k=_[0]&128?Uint8Array.of(0,..._):_;return Uint8Array.of(2,k.length,...k)},i=n(e.subarray(0,32)),r=n(e.subarray(32));return Uint8Array.of(48,i.length+r.length,...i,...r)}import{randomUUID as sn}from"crypto";var on="/app/local-runtime/session?register=vm_hands_v1",an="/app/local-runtime",Ce=25000,we=20000,dn=1e4,Ue=5000,cn=new Set(["pty.start","jobs.control","tunnel.open","tunnel.close"]),un="preview.serve.v1",_n=60000,ye=75000,mn=2000,gn=1e4,hn=new Set(["vm_hands_no_register","vm_hands_register_failed"]),fn=3,pn=20000,vn=250,wn=2000;function $e(e){let n=Math.min(vn*2**(e-1),wn);return Math.round(n/2+Math.random()*n/2)}var yn=5000;function bn(e){return e>=500||e===408||e===429}var ae=20000;function Be(e,n){return typeof e==="string"&&/^[A-Za-z0-9._:-]{1,160}$/.test(e)?e:n}class D extends Error{}var kn=64,qe=[1000,2000,4000,8000,15000,30000,60000,120000];function je(e){let n=e&&typeof e==="object"&&"code"in e?e.code:null;return typeof n==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(n)?n:"vm_hands_unbind_failed"}function Sn(e,n,i,r,h){let m=i.turn.claim.attempt_id,_=e.healing??=new Set;if(_.has(m))return;_.add(m);let k=i.turn.claim.operation_id;(async()=>{for(let[v,I]of qe.entries()){if(r.aborted)return;if(await new Promise((w)=>{let E=setTimeout(w,I);E.unref?.(),r.addEventListener("abort",()=>{clearTimeout(E),w()},{once:!0})}),r.aborted)return;try{let w=await n.retryUnbind(m);h("vm_hands.unbind_healed",{operation_id:k,attempt:v+1}),e.receipts.push({...i,unbound:w}),e.flushReceipts?.();return}catch(w){let E=je(w);if(h("vm_hands.unbind_unverified",{operation_id:k,code:E,attempt:v+1}),E==="vm_hands_unbind_unknown")return}}h("vm_hands.unbind_heal_exhausted",{operation_id:k,attempts:qe.length})})().finally(()=>_.delete(m))}async function Ge(e,n){let i=[...e.modelOps.get(n)??[]];for(let r of i)r.abort.abort();await Promise.race([Promise.all(i.map((r)=>r.settled)),new Promise((r)=>setTimeout(r,Ue))])}async function In(e,n){let i=[...e.personTerminals].filter((r)=>r.session===null||r.session===n);for(let r of i)r.abort.abort();if(i.length)await Promise.race([Promise.all(i.map((r)=>r.settled)),new Promise((r)=>setTimeout(r,Ue))]);return i.length}function Pn(e){let n=e.payload,i=n?.workspace?.kind==="managed"?n.workspace.workspaceId:void 0;return typeof i==="string"&&/^[0-9a-f-]{36}$/i.test(i)?i.toLowerCase():null}async function L(e,n,i){return await Ge(e,i),n.unbind(i)}function de(e){for(let n of e.outbox?.splice(0)??[])n.reject(Error("vm_hands_attempt_ended"))}var Ne=15000,En=1e4,Tn=1000;async function ji(e){let n=Date.now(),i={deviceId:null,connection:null,turns:new Map,lostAt:0,receipts:[],attest:"pending",attestWaiters:[],modelOps:new Map,personTerminals:new Set,bindsStarting:new Map},r=e.log??(()=>{}),h=async(k)=>{for(let[v,I]of[...i.turns]){i.turns.delete(v),e.onTurn?.(v,null),de(I);let w=await L(i,e.agent,v).catch(()=>null);if(w)i.receipts.push({turn:I,failure:"vm_hands_bind_lost",unbound:w});r("vm_hands.bound_dropped",{reason:k})}},m=0,_=0;try{for(let k=0;!e.signal.aborted;k++){let v=await Rn(e,i).catch((w)=>{if(w instanceof l&&i.deviceId===null&&w.code==="vm_hands_no_session"&&Date.now()-n<gn)return{closeCode:0,closeReason:"vm_hands_no_session"};if(w instanceof l&&i.deviceId===null&&hn.has(w.code)&&m<fn&&Date.now()-n<pn)return m++,_=$e(m),r("vm_hands.register_retry",{attempt:m,code:w.code,delay_ms:_}),{closeCode:0,closeReason:"vm_hands_register_retry"};if(w instanceof l&&i.deviceId===null)throw w;return{closeCode:0,closeReason:w instanceof Error?w.message:String(w)}});if(r("vm_hands.session_closed",{close_code:v.closeCode,reason:v.closeReason.slice(0,120),registered:i.deviceId!==null}),v.closeCode===4401||i.attest==="refused")return;if(e.signal.aborted)return;if(i.turns.size&&Date.now()-i.lostAt>=ye)await h("reconnect_deadline");if(i.served)i.served=!1,k=0;let I=v.closeReason==="drain_reconnect"?0:v.closeReason==="vm_hands_register_retry"?_:v.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(k,5),2000):i.turns.size?Math.min(250*2**Math.min(k,5),5000,Math.max(0,i.lostAt+ye-Date.now())):Math.min(500*2**k,30000);if(await new Promise((w)=>setTimeout(w,I)),i.turns.size&&Date.now()-i.lostAt>=ye)await h("reconnect_deadline")}}finally{await h("session_ended")}}async function Rn(e,n){let i=n.deviceId,r=e.log??(()=>{}),h=i?`/app/local-runtime/session?device_id=${encodeURIComponent(i)}`:on,m=`${e.apiOrigin.replace(/^http/,"ws")}${h}`,_=new WebSocket(m),k=0,v="",I=new Map,w=[],E=null,ce=new Promise((t)=>{_.onclose=(o)=>{k=o.code,v=o.reason;for(let s of I.values())s.reject(new D(`session closed ${o.code}`));for(let s of n.attestWaiters.splice(0))s(!1);I.clear(),t()}});_.onmessage=(t)=>{let o;try{o=JSON.parse(String(t.data))}catch{_.close(4400);return}if(o.t==="res"){let s=o;I.get(s.id)?.resolve({status:s.status,body:s.body}),I.delete(s.id);return}if(o.t==="reconnect"){let s=Math.max(0,Math.min(Number(o.after_ms)||0,Tn));r("vm_hands.drain_reconnect",{after_ms:s}),setTimeout(()=>{try{_.close(4001,"drain_reconnect")}catch{}},s).unref?.();return}if(!E?.(o))w.push(o)};let J=(t,o)=>new Promise((s,a)=>{let u=w.findIndex((p)=>t.includes(p.t));if(u>=0){s(w.splice(u,1)[0]);return}let f=setTimeout(()=>{E=null,a(new l("vm_hands_no_register",`no ${t.join("/")} in ${o} ms`))},o);E=(p)=>{if(!t.includes(p.t))return!1;return clearTimeout(f),E=null,s(p),!0}}),Y=(t)=>_.send(JSON.stringify(t)),q=(t,o)=>new Promise((s,a)=>{if(_.readyState!==WebSocket.OPEN){a(new D("session closed"));return}let u=sn(),f=typeof o.wait_ms==="number"?o.wait_ms:0,p=setTimeout(()=>{if(!I.delete(u))return;a(new D(`no answer to ${t.split("/").pop()} in ${f+Ne} ms`)),_.close(4000,"request_timeout")},f+Ne);I.set(u,{reject:(c)=>{clearTimeout(p),a(c)},resolve:({status:c,body:d})=>{clearTimeout(p);let g=null;try{g=d?JSON.parse(d):null}catch{}s({status:c,json:g})}}),Y({t:"req",id:u,path:`${an}${t}`,body:JSON.stringify(o)})}),be=()=>_.close(1001,"stopping");e.signal.addEventListener("abort",be,{once:!0});let le,X=new Map,Q=new Map,ue=!1,_e=new Set,me=Promise.resolve(),ke=()=>{ne().catch(()=>{return})},Z=!1;try{await new Promise((c,d)=>{let g=setTimeout(()=>d(Error("session open timeout")),En);_.onopen=()=>{clearTimeout(g),r("vm_hands.ws_open",{}),c()},_.onerror=()=>{clearTimeout(g),d(Error("session socket error"))}});let t=await J(["challenge"],5000);r("vm_hands.challenge",{});let o=[],s=null,a;if(i){Y(await e.agent.helloFrame(t.challenge,n.connection));let c=await J(["ready"],1e4);if(typeof c.vm_hands_connection==="string")n.connection=c.vm_hands_connection;if(a={device_id:i,...c.cadence?{cadence:c.cadence}:{}},typeof c.vm_hands_probe_script==="string"){if(s=c.vm_hands_probe_script,Z=!0,e.agent.phase==="registered"&&!n.turns.size)n.attest="pending"}n.served=!0,r("vm_hands.reconnected",{device_id:i});let d=Array.isArray(c.vm_hands_binds)?c.vm_hands_binds:c.vm_hands_bind?[c.vm_hands_bind]:[];for(let[g,S]of[...n.turns]){if(d.some((T)=>T&&T.operation_id===S.claim.operation_id&&T.attempt_id===S.claim.attempt_id)){o.push(S),r("vm_hands.bound_resumed",{operation_id:S.claim.operation_id});continue}n.turns.delete(g),e.onTurn?.(g,null),de(S);let P=await L(n,e.agent,g).catch((T)=>ee(T,S,"vm_hands_bind_lost"));if(P)n.receipts.push({turn:S,failure:"vm_hands_bind_lost",unbound:P});r("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}else{Y(await e.agent.registerFrame(t.challenge)),r("vm_hands.register_sent",{});let c=await Promise.race([J(["registered","register_refused"],1e4),ce.then(()=>{throw new l(v==="register_failed"?"vm_hands_register_failed":"vm_hands_register_closed","session closed before the register was answered")})]);if(c.t==="register_refused")throw new l(c.code,"register refused");e.agent.registered();let d=c;if(a=d,n.deviceId=d.device_id,typeof d.vm_hands_connection==="string")n.connection=d.vm_hands_connection;if(typeof d.vm_hands_probe_script==="string"){if(s=d.vm_hands_probe_script,Z=!0,e.agent.phase==="registered"&&!n.turns.size)n.attest="pending"}n.served=!0,r("vm_hands.registered",{device_id:a.device_id})}let u=async()=>{let c=await q("/heartbeat",await e.heartbeat());if(c.status>=300)throw Error(`heartbeat ${c.status}`)};await u();let f=a.cadence?.presence_interval_ms??30000;if(le=setInterval(()=>{u().catch(()=>_.close())},f),e.onHeartbeatNow?.(()=>{u().catch(()=>_.close())}),n.request=q,ce.then(()=>{if(n.request===q)n.request=null}),s&&n.attest!=="accepted"&&e.agent.phase==="registered"&&!n.turns.size)ze(s,t.challenge);let p=(c,d)=>{Q.set(c,d().catch(async(g)=>{if(await Se(g,c),g instanceof D)_.close();else await ne().catch(()=>{return})}).finally(()=>{Q.delete(c)}))};n.flushReceipts=ke;try{await ne();for(let c of o)c.flush=()=>Ie(c),c.flush(),p(c.claim.attempt_id,()=>Pe(c));while(!e.signal.aborted&&_.readyState===WebSocket.OPEN){let c=await q("/operations/claim",{wait_ms:Math.min(a.cadence?.claim_wait_ms??Ce,Ce)});if(c.status===204||!c.json)continue;if(c.status>=300)throw Error(`claim ${c.status}`);let d=c.json;if(d.capability==="hands.connect"){if(Q.has(d.attempt_id)){O({claim:d,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}p(d.attempt_id,()=>Fe(d))}else Ke(d).catch(()=>{return})}}catch(c){await Se(c,null)}}finally{if(le)clearInterval(le);e.signal.removeEventListener("abort",be);for(let t of n.turns.values())t.flush=null;if(n.flushReceipts===ke)n.flushReceipts=null;_.close(),await ce,await Promise.all([...Q.values()]);for(let t of e.agent.liveBindIds){if(n.turns.has(t))continue;let o=X.get(t),s=o?{...o,eventSeq:o.eventSeq+1}:null,a=await L(n,e.agent,t).catch((u)=>s?ee(u,s,"vm_hands_bind_lost"):null);if(a&&s)n.receipts.push({turn:s,failure:"vm_hands_bind_lost",unbound:a});r("vm_hands.bound_dropped",{reason:"bound_after_loss"})}}return{closeCode:k,closeReason:v};async function Se(t,o){if(t instanceof D){if(!ue&&n.turns.size)n.lostAt=Date.now();ue=!0}else{let s=o!==null?[o]:[...new Set([...n.turns.keys(),...e.agent.liveBindIds])];if(o===null)ue=!0;for(let a of s){let u=n.turns.get(a);if(n.turns.delete(a),u)de(u),e.onTurn?.(a,null);if(e.agent.liveBindIds.includes(a)){let f=X.get(a)??u,p=f?{...f,eventSeq:f.eventSeq+1}:null,c=await L(n,e.agent,a).catch((d)=>p?ee(d,p,"vm_hands_bind_lost"):null);if(c&&p)n.receipts.push({turn:p,failure:"vm_hands_bind_lost",unbound:c})}}}r("vm_hands.session_lost",{error:t instanceof Error?t.message:String(t),bound_kept:n.turns.size})}function O(t,o=q){let s=o,a=t.claim,u={attempt_id:a.attempt_id,attempt_token:a.attempt_token},f=encodeURIComponent(a.operation_id);return{fence:u,op:f,complete:(c,d={})=>s(`/operations/${f}/complete`,{...u,status:c,...d}),emit:(c,d)=>{let g=(t.chain??Promise.resolve()).catch(()=>{return}).then(()=>p(c,d));return t.chain=g,g}};async function p(c,d){let g=t.eventSeq,S=(R)=>s(`/operations/${f}/events`,{...u,event_seq_start:R,events:[{kind:c,payload:{sequence:R,capability:String(a.capability??"hands.connect"),data:d}}]}),P=g,T=await S(P),M=T.status===409?T.json?.expected_event_seq:void 0;if(typeof M==="number"&&M>=0&&M!==g)P=M,T=await S(P);if(T.status<300)t.eventSeq=P+1;return T}}function We(t){return(o,s)=>new Promise((a,u)=>{if(n.turns.get(t.claim.attempt_id)!==t){u(Error("vm_hands_attempt_ended"));return}if(t.outbox??=[],t.outbox.length>=kn){u(Error("vm_hands_outbox_full"));return}t.outbox.push({kind:o,data:s,resolve:a,reject:u}),t.flush?.()})}function Ie(t){if(_e.has(t))return;_e.add(t),(async()=>{try{while(t.outbox?.length&&n.turns.get(t.claim.attempt_id)===t&&_.readyState===WebSocket.OPEN){let o=t.outbox[0],s;try{s=await O(t).emit(o.kind,o.data)}catch(a){if(a instanceof D)return;s={status:500}}if(t.outbox.shift(),s.status<300)o.resolve();else o.reject(Error(`${o.kind} refused ${s.status}`))}}finally{_e.delete(t)}})()}async function ze(t,o){try{let s=await e.agent.attestFrame(t,o);if(_.readyState!==WebSocket.OPEN)return;Y(s);let a=await J(["attested","attest_refused"],15000);n.attest=a.t==="attested"?"accepted":"refused";for(let u of n.attestWaiters.splice(0))u(n.attest==="accepted");if(r("vm_hands.attest",{result:n.attest,exit_code:s.exit_code,...a.t==="attest_refused"?{code:String(a.code??"")}:{}}),n.attest==="refused")_.close(4401,"attest_refused")}catch(s){r("vm_hands.attest_failed",{code:s instanceof l?s.code:"probe_error"});for(let a of n.attestWaiters.splice(0))a(!1);if(n.attest!=="accepted")_.close(4000,"attest_unanswered")}}async function Fe(t){let o=Z&&n.attest==="pending",s=t.vm_hands_attest,a=s;if(n.attest==="refused"){r("vm_hands.claim_attest_refused",{said:typeof s==="string"?s.slice(0,16):typeof s,local:n.attest}),await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(a==="accepted"){if(!o&&n.attest!=="accepted"){n.attest="accepted";for(let b of n.attestWaiters.splice(0))b(!0)}}else if(a!=="pending"||!o&&n.attest!=="accepted"){r("vm_hands.claim_attest_refused",{said:typeof s==="string"?s.slice(0,16):typeof s,local:n.attest}),await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(n.attest!=="accepted"){let b=Date.parse(t.lease_until)-Date.now()-5000,B=Math.max(0,Math.min(ae,Number.isFinite(b)?b:ae));if(!await new Promise((ie)=>{let y=setTimeout(()=>ie(!1),B);n.attestWaiters.push((x)=>{clearTimeout(y),ie(x)})})){await O({claim:t,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let u={claim:t,eventSeq:0},{complete:f,emit:p}=O(u),c;try{if(t.capability!=="hands.connect")throw new l("vm_hands_bind_invalid","not hands.connect");c=!pe(t)}catch(b){r("vm_hands.bind_refused",{code:b instanceof l?b.code:"unexpected"}),await f("failed",{error_code:b instanceof l?b.code:"vm_hands_bind_invalid"});return}let d,g=null,S=!1,P=(()=>{try{return ve(t).session_id.toLowerCase()}catch{return String(t.run_id)}})();n.bindsStarting.set(P,(n.bindsStarting.get(P)??0)+1);try{let b=await In(n,P);if(b)r("vm_hands.person_terminals_closed",{count:b});let B=ve(t),j=e.agent.bind(B);if(B.workspace_deferred)S=!0,g=He(u,()=>S);d=await j}catch(b){r("vm_hands.bind_refused",{code:b instanceof l?b.code:"unexpected"}),await f("failed",{error_code:b instanceof l?b.code:"vm_hands_bind_failed"});return}finally{S=!1;let b=(n.bindsStarting.get(P)??1)-1;if(b>0)n.bindsStarting.set(P,b);else n.bindsStarting.delete(P)}let T=g?await g:-1,M={...d.ready_data??e.readyData({launchId:d.launch_id,claim:t})};if(c)delete M.environment_installed;let R=!c&&d.snapshot_revision!==null&&d.snapshot_id!==null?{environment_installed:{snapshot_id:d.snapshot_id,installed_revision:d.snapshot_revision}}:{};X.set(t.attempt_id,{claim:t,launchId:d.launch_id,readyData:M,eventSeq:u.eventSeq,ackSeq:-1});let F={...M,...R,vm_hands:{layout:d.layout,policy_digest:d.policy_digest,launch_id:d.launch_id}},te=Date.now()+yn,U=1,N=await p("hands.ready",F);while(bn(N.status)&&!e.signal.aborted){let b=$e(U);if(Date.now()+b>=te)break;await new Promise((B)=>setTimeout(B,b)),U++,N=await p("hands.ready",F)}if(U>1)r("vm_hands.ready_retried",{attempts:U,status_class:`${Math.floor(N.status/100)}xx`});if(X.delete(t.attempt_id),N.status>=300){await Ge(n,t.attempt_id),await e.agent.boundRefused(t.attempt_id),await f("failed",{error_code:Be(N.json?.error,"vm_hands_probe_failed")});return}let C={claim:t,launchId:d.launch_id,readyData:M,eventSeq:u.eventSeq,ackSeq:T};n.turns.set(t.attempt_id,C),C.flush=()=>Ie(C),e.onTurn?.(t.attempt_id,We(C)),await Pe(C)}async function He(t,o){let{fence:s,op:a}=O(t),u=t.claim.attempt_id,f=-1;try{for(;;){let p=await q(`/operations/${a}/heartbeat`,{...s,control_ack_seq:f,wait_ms:we});if(!o())return f;if(p.status>=300)return e.agent.abandonWorkspaceGrant(u),f;let c=(p.json?.controls??[]).slice().sort((d,g)=>d.seq-g.seq);for(let d of c){if(d.seq<=f)continue;if(f=d.seq,d.kind===ai)return r("vm_hands.workspace_granted",{}),e.agent.grantWorkspace(u),f;return r("vm_hands.workspace_grant_abandoned",{control:/^[a-z][a-z0-9._-]{0,63}$/.test(d.kind)?d.kind:"other"}),e.agent.abandonWorkspaceGrant(u),f}}}catch{return e.agent.abandonWorkspaceGrant(u),f}}async function Pe(t){let{fence:o,op:s}=O(t),a=null,u=null,f=e.agent.executorExited(t.claim.attempt_id).then((p)=>(u=p,null));e:for(;;){let p=await Promise.race([f,q(`/operations/${s}/heartbeat`,{...o,control_ack_seq:t.ackSeq,wait_ms:we})]);if(!p){a="vm_hands_executor_exited",r("vm_hands.executor_exited",{reason:u});break}if(p.status>=300)break;let c=(p.json?.controls??[]).slice().sort((d,g)=>d.seq-g.seq);for(let d of c){if(d.seq<=t.ackSeq)continue;if(d.kind==="operation.cancel"||d.kind==="cancel"){t.ackSeq=d.seq;break e}if(d.kind===bt)try{await Le(t,d.payload??{})}catch(g){if(g instanceof D)throw g;a=g instanceof l?g.code:"environment_unavailable";let S=g&&typeof g==="object"&&"code"in g&&typeof g.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(g.code)?g.code:null;r("vm_hands.environment_refused",{code:a,cause:S});break e}t.ackSeq=d.seq}}await Ve(t,a)}async function ge(t,o){let s=Date.now()+_n;for(;;){let a=n.request;if(a)try{return await a(t,o)}catch(u){if(!(u instanceof D))throw u}if(Date.now()>=s||e.signal.aborted)throw new D("kept operation has no live session");await new Promise((u)=>setTimeout(u,500))}}async function Ke(t){let o=t,s={claim:o,eventSeq:0},a=String(t.capability??""),u=a===un,{complete:f,emit:p,fence:c,op:d}={...O(s,ge)},g=t.vm_hands_origin==="person"?"person":"model";if(!e.executeOp){await f("failed",{error_code:"vm_hands_op_unsupported"});return}if(t.vm_hands_attest==="accepted"&&n.attest==="pending"&&!(Z&&n.attest==="pending")){n.attest="accepted";for(let y of n.attestWaiters.splice(0))y(!0)}if(n.attest!=="accepted"){let y=Date.parse(String(t.lease_until??""))-Date.now()-5000,x=n.attest==="refused"?0:Math.max(0,Math.min(ae,Number.isFinite(y)?y:ae));if(!(x>0&&await new Promise((re)=>{let Je=setTimeout(()=>re(!1),x);n.attestWaiters.push((Ye)=>{clearTimeout(Je),re(Ye)})}))){await f("failed",{error_code:"vm_hands_unattested"});return}}let S=e.agent.bindIdForRun(o.run_id);if(g==="model"&&S===null){await f("failed",{error_code:"vm_hands_not_bound"});return}let P=a==="pty.start"&&g==="person"&&!t.authority,T=P?Pn(t):null;if(P&&((y)=>y===null?e.agent.liveBindIds.length>0||n.bindsStarting.size>0:e.agent.liveSessionIds.includes(y)||n.bindsStarting.has(y))(T)){await f("failed",{error_code:"vm_hands_bound"});return}if(cn.has(a)&&!P&&e.agent.liveBindIds.length===0){await f("failed",{error_code:"vm_hands_not_bound"});return}let R=new AbortController,F=()=>R.abort();e.signal.addEventListener("abort",F,{once:!0});let te,U=new Promise((y)=>{te=y}),N={abort:R,settled:U},C=P?{...N,session:T}:null;if(C)n.personTerminals.add(C);if(g==="model"&&S&&a!=="preview.serve.v1"){let y=n.modelOps.get(S)??new Set;y.add(N),n.modelOps.set(S,y),await e.agent.environmentInstalled(S,mn,R.signal)}let b=-1,B=!1,j=!1,ie=u?void 0:setInterval(()=>{if(j)return;j=!0,ge(`/operations/${d}/heartbeat`,{...c,control_ack_seq:b,wait_ms:0}).then((y)=>{if(y.status>=300){R.abort();return}let x=y.json?.controls??[];for(let A of x)if(b=Math.max(b,A.seq),A.kind==="operation.cancel"||A.kind==="cancel")R.abort()},()=>R.abort()).finally(()=>{j=!1})},dn);if(u)(async()=>{while(!B&&!R.signal.aborted){let y;try{y=await ge(`/operations/${d}/heartbeat`,{...c,control_ack_seq:b,wait_ms:we})}catch{R.abort();return}if(B)return;if(y.status>=300){R.abort();return}let x=(y.json?.controls??[]).slice().sort((A,re)=>A.seq-re.seq);for(let A of x){if(A.seq<=b)continue;if(A.kind==="operation.cancel"||A.kind==="cancel")R.abort();else await e.controlOp?.({claim:t,control:A}).catch(()=>!1);b=A.seq}}})();try{let y=await e.executeOp({kind:g,claim:t,...g==="model"&&S?{bindId:S}:{},signal:R.signal,emit:async(A)=>{await p(A.kind,A.data??{})}}),x=await f(y.status,{...y.result?{result:y.result}:{},...y.error_code?{error_code:Be(y.error_code,"vm_hands_op_failed")}:{}});e.opCompleted?.({claim:t,status:y.status,acknowledged:x.status<300}),r("vm_hands.op",{capability:a,kind:g,status:y.status,code:y.error_code??null,...x.status>=300?{complete_status:x.status,complete_error:String(x.json?.error??"").slice(0,64)}:{}})}finally{if(B=!0,clearInterval(ie),e.signal.removeEventListener("abort",F),S)n.modelOps.get(S)?.delete(N);if(C)n.personTerminals.delete(C);te()}}async function Ve(t,o){let s=t.claim.attempt_id;if(n.turns.get(s)===t)n.turns.delete(s);e.onTurn?.(s,null),de(t);let a=await L(n,e.agent,s).catch((u)=>ee(u,t,o));if(!a)return;n.receipts.push({turn:t,failure:o,unbound:a}),await ne()}function ee(t,o,s){let a=je(t);return r("vm_hands.unbind_unverified",{operation_id:o.claim.operation_id,code:a,attempt:0}),O(o).emit(ci,{code:a}).catch(()=>{return}),Sn(n,e.agent,{turn:o,failure:s},e.signal,r),null}function ne(){return me=me.then(Ee,Ee),me}async function Ee(){while(n.receipts.length){let{turn:t,failure:o,unbound:s}=n.receipts[0],{complete:a,emit:u}=O(t);try{if(await u("hands.stopped",{...t.readyData,reason_code:o?"failed":"cancelled",killed_verified:s.killed_verified,shredded:s.shredded,...s.srt_fallbacks?{vm_hands_srt_fallbacks:s.srt_fallbacks}:{}}),o)await a("failed",{error_code:o});else await a("cancelled",{error_code:"driver_stopped"})}catch(f){if(f instanceof D)return}n.receipts.shift()}}async function Le(t,o){let{fence:s,op:a}=O(t),u=o.snapshot_id;if(o.version!==1||typeof u!=="string"||Object.keys(o).length!==2)throw new l("vm_hands_env_invalid","invalid environment delivery");let f=await q(`/operations/${a}/environment`,{...s,snapshot_id:u}),p=f.json?.environment_sealed;if(f.status!==200||!p||f.json?.payload!==void 0)throw new l("vm_hands_env_invalid","environment not delivered sealed");let c=await e.agent.deliverEnvironment({attemptId:t.claim.attempt_id,snapshotId:u,deviceId:n.deviceId??"",sealed:p});if((await q(`/operations/${a}/environment-ack`,{...s,...c})).status>=300)throw new l("vm_hands_env_ack_refused","environment ack refused")}}import{readFileSync as xn}from"fs";var An=performance.now();delete process.env.BUN_BE_BUN;var z=(e,n={})=>console.log(JSON.stringify({stage:e,ms:Math.round(performance.now()),...n}));async function On(){if(process.argv.includes("--vm-hands-op-runner")){let{runVmHandsOpRunner:m}=await import("./vm-hands-op-runner-4bvnr7gn.js");await m();return}z("parsed",{t0:Math.round(An)});let e="";try{e=xn(3,"utf8")}catch{}z("fd3_read",{bytes:e.length});let n=null;if(e.trim())try{n=JSON.parse(e)}catch{n=null}if(!n||typeof n!=="object"||Array.isArray(n))z(e.trim()?"identity_invalid":"identity_free"),await new Promise(()=>{setInterval(()=>{return},1073741824)});let{parseVmHandsInit:i,runVmHands:r}=await import("./vm-hands-runtime-b84m3a8j.js"),h=i(n);if(!h)z("identity_invalid"),await new Promise(()=>{setInterval(()=>{return},1073741824)});try{await r(h,z)}catch(m){let _=m&&typeof m==="object"&&"code"in m&&typeof m.code==="string"?m.code:"error";throw z("failed",{code:_}),m}process.exit(0)}On();export{Fi,ln,ji};
|