@reason-machines/cli-linux-x64 0.2.560 → 0.2.561
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/reason +1 -1
- package/bin/vm-hands/{agent-network-j5f603sy.js → agent-network-kk36zca7.js} +1 -1
- package/bin/vm-hands/{api-credentials-7rhpwe7n.js → api-credentials-mtfdk175.js} +1 -1
- package/bin/vm-hands/{api-vkgf7wma.js → api-w6w7vfp3.js} +1 -1
- package/bin/vm-hands/{ask-relay-2vf6fa2t.js → ask-relay-xx0rzpch.js} +2 -2
- package/bin/vm-hands/{connect-cli-06x1wfgv.js → connect-cli-dmwph620.js} +1 -1
- package/bin/vm-hands/{local-automation-8b1znx0p.js → local-automation-vvt9d9xb.js} +1 -1
- package/bin/vm-hands/{local-capabilities-m6pzcc94.js → local-capabilities-pwv76ns5.js} +1 -1
- package/bin/vm-hands/{local-display-session-zyd8s6n6.js → local-display-session-axh9mfdk.js} +1 -1
- package/bin/vm-hands/local-display-video-pxhztqk7.js +2 -0
- package/bin/vm-hands/{local-managed-process-w26jhyfg.js → local-managed-process-4mgqn7tg.js} +1 -1
- package/bin/vm-hands/{managed-runtime-ykv5nyva.js → managed-runtime-pcagtyfz.js} +1 -1
- package/bin/vm-hands/{network-auto-update-mrjz964a.js → network-auto-update-wkzb91qz.js} +2 -2
- package/bin/vm-hands/{network-sign-in-8yvdx5rm.js → network-sign-in-61gmpmaa.js} +1 -1
- package/bin/vm-hands/{permissions-nmxr8238.js → permissions-348prrcx.js} +1 -1
- package/bin/vm-hands/{serve-service-det934tz.js → serve-service-3dkyznay.js} +1 -1
- package/bin/vm-hands/{status-fr7192eh.js → status-khqk4cjw.js} +3 -3
- package/bin/vm-hands/{version-5d6gbmrd.js → version-c1hen0wn.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-fk2s50nc.js → vm-hands-entry-lite-2dak7e1h.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-0ex2twm5.js → vm-hands-entry-lite-5y4phfv1.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-q3er9m6y.js → vm-hands-entry-lite-6jxshhps.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-4jgykvd3.js → vm-hands-entry-lite-7pfhwxn5.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-jhsa4av7.js → vm-hands-entry-lite-9yfmkd1f.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-qegwyvyz.js → vm-hands-entry-lite-bj3w2ven.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-8w0ah5j9.js → vm-hands-entry-lite-gxpw14jv.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-cspd38hc.js → vm-hands-entry-lite-h7nk2848.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-bnpdn6fw.js → vm-hands-entry-lite-hn9pq7zj.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-0as6nsks.js → vm-hands-entry-lite-ht6hzkgj.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-fhx46jny.js → vm-hands-entry-lite-jgk5z8zc.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-8pcs85ak.js → vm-hands-entry-lite-m1we91g4.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-f8p11q6h.js → vm-hands-entry-lite-vkhacd00.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-rhx6adbr.js → vm-hands-entry-lite-wcgm41jq.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-f95mg81d.js → vm-hands-entry-lite-xvccy3z4.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-y4df9n3f.js → vm-hands-entry-lite-y3nz20wb.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-tvnfm4xg.js → vm-hands-entry-lite-z213y4pj.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-qny3mx8f.js → vm-hands-executor-csdtg7kj.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-5q01rhkc.js → vm-hands-op-runner-z7tsd84c.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-gjjm5fzd.js → vm-hands-runtime-1qxf96z7.js} +3 -3
- package/package.json +1 -1
- package/bin/vm-hands/local-display-video-rk680vwg.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{rr,Dr,Bn,qi,Or,Nr,na,Wi,ia,oa,Lr}from"./vm-hands-entry-lite-57ajjwmh.js";import{xt,Ln,ds,Ar,Fc,Ke,jc,Hc,Qt,Je,M,Ct,fs,$n,ms,Rr,bs,vs,Ss,Es,ks,xs,Cs,As,Ps,Rs,Ts,Is,Ds,at,Le,At,xe,Os,Ns,Ls,$s,Ms,Bs,Fs,js,Tr,Hs,Ir,zs,zi,qs,Ws,Vs,Gs,Ks,Js,Xs,Ys,Zs,Qs,ea,ta,ra}from"./vm-hands-entry-lite-71ebge0c.js";import{st,Oe,X,te}from"./vm-hands-entry-lite-9g52kxyj.js";import{F,pn}from"./vm-hands-entry-lite-jpvmkce5.js";import{ei,Ma,Ba,Ze,Fa,ja,Xr,Ha,Ua,za,ri,ii,oi,wo,bo,si,Ka,vo,ai,Pe,J,Qr,ci,ui,Qe}from"./vm-hands-entry-lite-
|
|
2
|
+
import{rr,Dr,Bn,qi,Or,Nr,na,Wi,ia,oa,Lr}from"./vm-hands-entry-lite-57ajjwmh.js";import{xt,Ln,ds,Ar,Fc,Ke,jc,Hc,Qt,Je,M,Ct,fs,$n,ms,Rr,bs,vs,Ss,Es,ks,xs,Cs,As,Ps,Rs,Ts,Is,Ds,at,Le,At,xe,Os,Ns,Ls,$s,Ms,Bs,Fs,js,Tr,Hs,Ir,zs,zi,qs,Ws,Vs,Gs,Ks,Js,Xs,Ys,Zs,Qs,ea,ta,ra}from"./vm-hands-entry-lite-71ebge0c.js";import{st,Oe,X,te}from"./vm-hands-entry-lite-9g52kxyj.js";import{F,pn}from"./vm-hands-entry-lite-jpvmkce5.js";import{ei,Ma,Ba,Ze,Fa,ja,Xr,Ha,Ua,za,ri,ii,oi,wo,bo,si,Ka,vo,ai,Pe,J,Qr,ci,ui,Qe}from"./vm-hands-entry-lite-vkhacd00.js";import{U,H,R}from"./vm-hands-entry-lite-v4hr9x9h.js";import{Ta,Ia,fo,Oa,mo,Na,lr,Xn}from"./vm-hands-entry-lite-5y4phfv1.js";import{ue}from"./vm-hands-entry-lite-q9djb28r.js";import{je}from"./vm-hands-entry-lite-weqam12f.js";import{Se}from"./vm-hands-entry-lite-pxtycfdv.js";import{Gn,Kn,Pa}from"./vm-hands-entry-lite-52qz0n30.js";import{vc,Sc,Sr,Ec,kc,xc,Cc,Ac,Pc,Rc}from"./vm-hands-entry-lite-j10cw3d9.js";import{mi,an,gi,Lo,$o}from"./vm-hands-entry-lite-hxfxs7r9.js";import{on,Ft,sn}from"./vm-hands-entry-lite-z213y4pj.js";import{Go,T,dc}from"./vm-hands-entry-lite-hn9pq7zj.js";import{yc,wc}from"./vm-hands-entry-lite-wcgm41jq.js";import{nn,hr,Oo}from"./vm-hands-entry-lite-2dak7e1h.js";import{et,Za,Qa}from"./vm-hands-entry-lite-0wb1n769.js";import{rn}from"./vm-hands-entry-lite-tcmye5ny.js";import{q}from"./vm-hands-entry-lite-a6ss0ges.js";import{bt,Cn,An,Pn,L}from"./vm-hands-entry-lite-ptycjmkc.js";import{s,Ve}from"./vm-hands-entry-lite-zawytz09.js";import{t,V,o,_,d,n,we,A,$e,c,i,qc}from"./vm-hands-entry-lite-k5ytpgzz.js";import{Y,Me,It,Be,Ki}from"./vm-hands-entry-lite-8xv6c0rm.js";import{Dt}from"./vm-hands-entry-lite-ab1pq3xg.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{request as ic}from"http";import{request as sc}from"https";import{lookup as ac}from"dns/promises";import{isIP as lc}from"net";async function cc(e){let a=new URL(e.url);return await new Promise((l,u)=>{let p=(a.protocol==="https:"?sc:ic)(a,{method:"POST",headers:{...e.headers,"accept-encoding":"identity"},signal:e.signal,timeout:na},(m)=>l({response:m,close:()=>{m.destroy(),p.destroy(),m.socket?.destroy()}}));p.once("error",u),p.once("timeout",()=>p.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),p.end(e.body)})}var hi=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),uc=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function _i(e,a=0){if(!e||typeof e!=="object"||a>3)return null;let l=e.code;if(typeof l==="string"){if(hi.has(l))return"custom_endpoint_host_not_found";if(uc.has(l))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(l))return"custom_endpoint_tls_failed"}for(let u of[...e instanceof AggregateError?e.errors:[],e.cause]){let p=_i(u,a+1);if(p)return p}return null}async function pc(e,a){let l=_i(e),u=new URL(a).hostname.replace(/^\[|\]$/g,"");if(l!==null&&l!=="custom_endpoint_connection_failed"||lc(u)!==0)return l;let p;return await Promise.race([ac(u).then(()=>!0,(f)=>!hi.has(String(f?.code))),new Promise((f)=>{p=setTimeout(()=>f(!0),5000)})]).finally(()=>clearTimeout(p))?l:"custom_endpoint_host_not_found"}function mc(e){for(let a=42;;a++){if(a===127)a=256;let l=String.fromCodePoint(a);if(!e.includes(l))return l}}function fc(e,a){let l=Buffer.from(e),u=Buffer.from(a),p=new Uint32Array(l.length);for(let f=1,g=0;f<l.length;f++){while(g&&l[f]!==l[g])g=p[g-1];if(l[f]===l[g])g++;p[f]=g}let m=0;return(f,g=!1)=>{let b=Buffer.allocUnsafe(f.length*u.length+m),y=0;for(let h of f){while(m&&l[m]!==h){let w=p[m-1];y+=l.copy(b,y,0,m-w),m=w}if(l[m]===h){if(m++,m===l.length)y+=u.copy(b,y),m=0}else b[y++]=h}if(g)y+=l.copy(b,y,0,m),m=0;return b.subarray(0,y)}}async function yi(e){e.signal.throwIfAborted();let a=ia.safeParse(e.payload);if(!a.success)throw new r("custom_endpoint_invalid_request","Invalid local model request.");let l=a.data,u=oa.parse(await e.credential(e.signal));if(!Wi(l,{baseUrl:l.baseUrl,api:u.api,execution:"device"}))throw new r("custom_endpoint_invalid_request","The request does not match the configured API.");e.signal.throwIfAborted();let p,m,f=0,g=0,b=0,y=mc(u.apiKey),h=fc(u.apiKey,y),w=async(v,x)=>{e.signal.throwIfAborted(),await new Promise((I,E)=>{let C=()=>{e.signal.removeEventListener("abort",C),E(e.signal.reason)};if(e.signal.addEventListener("abort",C,{once:!0}),e.signal.aborted){C();return}Promise.resolve().then(()=>(e.signal.throwIfAborted(),e.emit(v,x))).then(()=>{e.signal.removeEventListener("abort",C),I()},(O)=>{e.signal.removeEventListener("abort",C),E(O)})})},S=async(v)=>{if(f+=v.length,f>Bn)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let x=0;x<v.length;x+=Dr){if(b>=qi)throw new r("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await w(`custom_endpoint.chunk.${b++}`,{eof:!1,data:v.subarray(x,x+Dr).toString("base64")})}};try{let v=await cc({url:l.url,body:l.body,signal:e.signal,headers:{...l.headers,...u.api==="anthropic-messages"?{"x-api-key":u.apiKey}:{authorization:`Bearer ${u.apiKey}`}}});p=v.response,m=v.close;let x=p.statusCode??500;if(x>=300&&x<400)throw new r("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(p.headers["content-encoding"]&&p.headers["content-encoding"]!=="identity")throw new r("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let I={};for(let E of["content-type","retry-after","x-request-id","request-id"]){let C=p.headers[E];if(typeof C==="string")I[E]=C.replaceAll(u.apiKey,y).slice(0,4096)}await w("custom_endpoint.headers",{status:x,statusText:(p.statusMessage??"").replaceAll(u.apiKey,y).slice(0,256),headers:I});for await(let E of p){e.signal.throwIfAborted();let C=Buffer.isBuffer(E)?E:Buffer.from(E);if(g+=C.length,g>Bn)throw new r("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await S(h(C))}return await S(h(Buffer.alloc(0),!0)),await w(`custom_endpoint.chunk.${b}`,{eof:!0}),{bytes:f,chunks:b}}catch(v){if(e.signal.throwIfAborted(),v instanceof r)throw v;throw new r((p?null:await pc(v,l.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{m?.()}}import{join as bi}from"path";function hc(e,a){return e===bi(a,".ara","workspace")||e===bi(a,".reason","workspace")}function wi(e,a){let l=e.filter((u)=>hc(u.path,a));return l.length===1?l[0].path:null}var gc=/^[a-f0-9]{64}$/;var Jr=32,_c=/^\/[^\x00-\x1f\x7f\\]*$/;function tr(e){if(typeof e!=="string"||e.length>4096||!_c.test(e))return!1;if(e==="/")return!0;return e.split("/").slice(1).every((a)=>a!==""&&a!=="."&&a!=="..")}function nr(e,a){let l=a==="win32"?/^([A-Za-z]):[\\/]*(.*)$/.exec(e):null;if(!l)return e;let u=l[2].split(/[\\/]+/).filter(Boolean).join("/");return`/${l[1].toUpperCase()}:${u?`/${u}`:""}`}function ir(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let a=e;if(!tr(a.home)||!Array.isArray(a.roots)||a.roots.length>Jr)return;let l=[];for(let u of a.roots){if(!u||typeof u!=="object"||Array.isArray(u))return;let{path_fingerprint:p,path:m}=u;if(typeof p!=="string"||!gc.test(p)||!tr(m))return;l.push({path_fingerprint:p,path:m})}return{home:a.home,roots:l}}function bc(e){let a=/^Reason contributor (rc_[0-9a-f]{32})$/.exec(e.name)?.[1];return e.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&a?a:void 0}function Oc(e){return bc(e)??e.email.toLowerCase()}function Zr(e){let a=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec(e.trim());return a?Oc({name:a[1],email:a[2]}):e.trim().toLowerCase()}var Lt=(e)=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(a)=>`[${a.toLowerCase()}${a.toUpperCase()}]`),Ic=[...bt.map((e)=>`/(${e.map(Lt).join("/")})(/|$)`),...Cn.map((e)=>`/(${e.map(Lt).join("/")})(/|$)`),...[...An].map((e)=>`/(${Lt(e)})$`),`/${Lt(".env.")}[^/]*$`,...Pn.map((e)=>`/[^/]*${Lt(e)}$`)],Si=`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{O,Rn,ns,Xt,is,os}from"./vm-hands-entry-lite-j10cw3d9.js";import{ls}from"./vm-hands-entry-lite-
|
|
2
|
+
import{O,Rn,ns,Xt,is,os}from"./vm-hands-entry-lite-j10cw3d9.js";import{ls}from"./vm-hands-entry-lite-6jxshhps.js";import{Ko}from"./vm-hands-entry-lite-q9djb28r.js";import{s}from"./vm-hands-entry-lite-zawytz09.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as _s,spawn as qe}from"child_process";import{existsSync as ks}from"fs";import{connect as vs}from"net";function gn(){let e=new Set,t=null,n=(i)=>({holder:t?.viewer??null,you:t===i,same_user:Boolean(t?.viewer&&i.viewer&&t.viewer.user_id===i.viewer.user_id)}),o=()=>{for(let i of e)i.notify(n(i))};return{join(i){return e.add(i),i.notify(n(i)),()=>{if(!e.delete(i))return;if(t!==i)return;t=null,o()}},claim(i){if(t===i||!e.has(i))return;t=i,o()}}}var ut=gn();import{createHash as vt}from"crypto";import{once as Pn}from"events";import{createWriteStream as Cn,existsSync as Mn,mkdirSync as Tn,mkdtempSync as hr,readFileSync as de,readdirSync as br,renameSync as On,realpathSync as An,rmSync as $n,statSync as Ue,writeFileSync as Ln}from"fs";import{delimiter as wr,dirname as Be,join as y}from"path";import{finished as Nn}from"stream/promises";var Gt="omljlfpmafedpplnpkkahegadhkimdje",lc="https://chromewebstore.google.com/detail/reason/omljlfpmafedpplnpkkahegadhkimdje";var A={ocu:{repository:"https://github.com/iFurySt/open-codex-computer-use.git",revision:"386a260d1ab8b690adbbb27f7471595cf0c2b752",version:"0.3.5"},obu:{repository:"https://github.com/iFurySt/open-browser-use.git",revision:"ac015846df75928fbcf0f3a0f3ba3a210ce1a507",version:"0.1.42"}},F={version:"155.0.8059.84",macArm64Sha256:"13b9e98ce56f5ce18e100a009f455c9285f399e7c9dc8a76fdf2f3a9755bb5f2",linux64Sha256:"cf0f049892dea22e6a6db26d47ed0d7776b7158edcbec4634086633df8bafcbc",win64Sha256:"507f2a031441d10c62b5e3d4e863f09ac1198a571c1419976cbd8387f639afde"};var J={ocu:{url:`https://registry.npmjs.org/open-computer-use/-/open-computer-use-${A.ocu.version}.tgz`,sha256:"7c16a87c8cd357787b02c0ebd040dd5f93880c1fb51c1901caa2e0c05d063130",size_bytes:5844280},obu:{url:`https://registry.npmjs.org/open-browser-use/-/open-browser-use-${A.obu.version}.tgz`,sha256:"9386d8ce0a147b3f55e1807b68edf736836378807541c457c9b5f6ca2cabaa4e",size_bytes:21372018},extension:{url:`https://github.com/iFurySt/open-browser-use/releases/download/v${A.obu.version}/open-browser-use-chrome-extension-${A.obu.version}.zip`,sha256:"c9c07bec1175e12ea6985b0e7784a5ef01fd03f014b958224a1e17dcd838a241",size_bytes:31070}},le="pnbmoicbkopffjjgfgfglopechaiemkp";import{spawn as Te}from"child_process";import{createRequire as hn}from"module";import{join as bn}from"path";var xn=30000,_n=1048576;function Oe(){return process.env.SystemRoot??"C:\\Windows"}function kn(){return bn(Oe(),"System32","WindowsPowerShell","v1.0","powershell.exe")}var vn=String.raw`
|
|
3
3
|
$ErrorActionPreference = "Stop"
|
|
4
4
|
Add-Type -TypeDefinition @"
|
|
5
5
|
using System;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ba}from"./vm-hands-entry-lite-84mc1f7h.js";import{P}from"./vm-hands-entry-lite-2rgf8866.js";import{W}from"./vm-hands-entry-lite-q9s1e2y1.js";import{Q,ro,ve,no}from"./vm-hands-entry-lite-a7bf7xr7.js";import{xr}from"./vm-hands-entry-lite-qegwyvyz.js";import{t,o,_,d,n,rl,we,c,i}from"./vm-hands-entry-lite-k5ytpgzz.js";var E=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function S(e){let s=typeof e==="string"?E.exec(e):null;return s?{major:Number(s[1]),minor:Number(s[2])}:null}import{createHash as q,randomBytes as v}from"crypto";import{createInterface as M}from"readline";var k=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var Ge=k.filter((e)=>e!=="network:read"&&e!=="network:write");class y extends Error{oauthCode;constructor(e,s=null){super(e);this.oauthCode=s;this.name="LoginError"}}function ya(){let e=v(48).toString("base64url"),s=q("sha256").update(e).digest("base64url");return{verifier:e,challenge:s,state:v(32).toString("base64url")}}function z(e,s){let r=typeof e.error==="string"?e.error:null,a=typeof e.error_description==="string"?e.error_description:r?r:s;return new y(a,r)}async function L(e,s,r,a){let l=await r(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:s,signal:a}),u=await l.json().catch(()=>({}));if(!l.ok)throw z(u,`OAuth token request failed (${l.status})`);return u}var j=1e4;async function D(e,s={}){let r=s.fetchImpl??fetch,a=await L(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),r,AbortSignal.timeout(j)).catch((u)=>{if(u instanceof Error&&u.name==="TimeoutError")throw new y("Reason did not answer the login refresh in time. Check the network and retry.");throw u});if(typeof a.access_token!=="string"||typeof a.refresh_token!=="string"||typeof a.expires_in!=="number")throw new y("Reason returned an incomplete refreshed login.");let l={...e,accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:new Date(Date.now()+a.expires_in*1000).toISOString(),scopes:typeof a.scope==="string"?a.scope.split(/\s+/).filter(Boolean):e.scopes};return ro(l,s.path??Q()),l}var R=new Map,N=2000,H=100;function I(e,s){if(!s)return e;if(s.aborted)return Promise.reject(s.reason);return new Promise((r,a)=>{let l=()=>a(s.reason);s.addEventListener("abort",l,{once:!0}),e.then(r,a).finally(()=>s.removeEventListener("abort",l))})}async function be(e={}){let s=e.path??Q(),r=ve(s);if(!r)return null;let a=e.apiOrigin??P(process.env,"REASON_API_URL")?.trim();if(a&&!W(r.apiOrigin,new URL(a).origin))return null;if(!(Date.parse(r.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&r.accessToken!==e.refused))return r;let u=[s,r.apiOrigin,r.clientId,r.refreshToken].join("\x00"),g=R.get(u);if(g)return I(g,e.signal);let h;return h=D(r,{fetchImpl:e.fetchImpl,path:s}).catch(async(p)=>{if(!(p instanceof y)||p.oauthCode!=="invalid_grant"&&p.oauthCode!=="invalid_client")throw p;let b=(f)=>f!==null&&(p.oauthCode==="invalid_client"?f.clientId!==r.clientId:f.refreshToken!==r.refreshToken),O=Date.now()+N;while(!b(ve(s))&&Date.now()<O)await new Promise((f)=>setTimeout(f,H));if(b(ve(s)))return be({fetchImpl:e.fetchImpl,path:s});return no(s),null}).finally(()=>{if(R.get(u)===h)R.delete(u)}),R.set(u,h),I(h,e.signal)}function wa(e,s){return new Promise((r)=>{let a=M({input:e}),l=!1,u=(h)=>{if(l)return;l=!0,s.removeEventListener("abort",g),a.close(),e.pause(),r(h)},g=()=>u(null);s.addEventListener("abort",g,{once:!0}),a.once("line",(h)=>u(h)),a.once("close",()=>u(null))})}var F=n({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:_().nullable()}),B=n({groups:d(n({selectable:_().optional(),accounts:d(n({source_id:t().min(1),model_ids:d(t().min(1)).optional()}))}))});function G(e){let s=B.safeParse(e);if(!s.success)return;return s.data.groups.some((r)=>r.selectable!==!1&&r.accounts.some((a)=>a.model_ids===void 0||a.model_ids.length>0))}class C extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;refusal;constructor(e,s,r,a,l,u,g){super(r);this.status=e;this.code=s;this.suggestedModel=a;this.retryAfterMs=l;this.resolutionReason=u;this.refusal=g;this.name="ApiError"}static rateLimitDelayMs(e,s){if(!(e instanceof C)||e.status!==429)return null;return Math.min(60000,Math.max(s,e.retryAfterMs??0))}}var J=["minimal","low","medium","high","xhigh","max"],K=n({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:_(),compatible:_().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:d(n({id:t().min(1),label:t()}))}),V=n({devices:d(K),end_cursor:t().nullish(),has_next_page:_().optional()}),Y=n({id:t().min(1),name:t()}),Z=n({items:d(Y)}),X=n({id:t().min(1),name:t(),main:_(),mine:_(),session_id:t().nullish(),appearance:n({color:t().nullish()}).nullish().catch(null)}),ee=n({items:d(X)}),ne=n({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:d(t()).default([]),is_enabled:_().default(!0)}),te=n({items:d(ne).default([])}),se=n({id:t().min(1),kind:t(),enabled:_(),schedule:n({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:n({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),A=n({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:_(),triggers:d(se).default([])}),oe=n({items:d(A).default([]),end_cursor:t().nullish(),has_next_page:_().optional()}),re=n({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:_()}),ie=n({items:d(re).default([])}),ae=n({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),x=n({tags:d(t()).default([])}),le=c(["linux","macos"]),T=n({id:t().min(1),name:t().min(1),platform:le.nullable(),workers:n({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:n({queued:o().int(),running:o().int()})}),ce=n({machines:d(T)}),de=n({machine:T}),ue=n({deleted:i(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),ge=n({token:n({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),U=rl({machine_id:t().min(1),machine_name:t().min(1)}),he=U.extend({organization_id:t().min(1)}),tn=n({id:t().min(1),name:t().min(1),state:c(["waiting","placed"]),queue_position:o().int().nullable()});var sn=we([n({kind:i("cloud")}),n({kind:c(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function m(e,s,r){let a=e.safeParse(s);if(!a.success)throw new C(502,r,"Reason returned an unexpected response.");return a.data}var pe=n({error:n({type:t(),message:t()})});function w(e,s,r){let a=pe.safeParse(s),l=typeof s.error==="string"?s.error:a.success?a.data.error.type:`http_${e}`,u=typeof s.detail==="string"?s.detail:typeof s.message==="string"?s.message:a.success?a.data.error.message:`Reason request failed (${e}${typeof s.error==="string"?` ${s.error}`:""})`,g=l==="github_connection_required"&&typeof s.connect_url==="string"&&/^https?:\/\//.test(s.connect_url)?` Connect it at ${s.connect_url}`:"",h=r===null||r.trim()===""?NaN:Number(r);return new C(e,l,`${u}${g}`,typeof s.suggested_model==="string"?s.suggested_model:void 0,Number.isFinite(h)&&h>=0?h*1000:void 0,typeof s.resolution_reason==="string"?s.resolution_reason:void 0,typeof s.code==="string"?{code:s.code,...typeof s.billing_path==="string"&&/^\/(?![/\\])/.test(s.billing_path)?{billingPath:s.billing_path}:{}}:void 0)}async function eo(e){let s=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),r=await s.json().catch(()=>({}));if(!s.ok)throw w(s.status,r,s.headers.get("retry-after"));return m(he,r,"invalid_machine_ticket")}var fe=n({items:d(n({name:t()}))}),_e=n({name:t(),scope:t(),result:c(["created","updated"]).optional(),warning:n({message:t()}).optional()});class me{options;credentials;constructor(e,s={}){this.options=s;this.credentials=e}trackEvent(e,s={}){}async request(e,s={}){let{status:r,headers:a,json:l}=await this.exchange(e,s);if(r<200||r>299)throw w(r,l,a.get("retry-after"));return l}async exchange(e,s={},r=!1){let a=this.options.fetchImpl??fetch;if(!r&&s.retryUnauthorized!==!1)await this.renewBeforeExpiry(a,s.signal);let l=await a(`${this.credentials.apiOrigin}/v3${e}`,{method:s.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":xr,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...s.raw?{"content-type":s.raw.contentType}:s.body===void 0?{}:{"content-type":"application/json"},...s.headers,...s.ifNoneMatch?{"if-none-match":s.ifNoneMatch}:{}},body:s.raw?s.raw.bytes:s.body===void 0?void 0:JSON.stringify(s.body),signal:s.signal,redirect:s.ifNoneMatch?"manual":"error"}),u=await l.json().catch(()=>({}));if(l.status===401&&!r&&s.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let g=await be({fetchImpl:a,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:s.signal});if(g)return this.credentials=g,this.exchange(e,s,!0)}return{status:l.status,headers:l.headers,json:u}}async renewBeforeExpiry(e,s){let r=this.credentials;if(r.credentialKind==="api_key"||!(Date.parse(r.expiresAt)<=Date.now()+60000))return;let a=await be({fetchImpl:e,path:this.options.credentialsPath,signal:s}).catch(()=>null);if(a&&a.apiOrigin===r.apiOrigin&&a.orgId===r.orgId&&a.clientId===r.clientId)this.credentials=a}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(s){if(s instanceof C&&(s.status===404||s.status===405||s.status===403&&s.code==="endpoint_not_available"))return null;throw s}}addDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(s)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,s=""){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?r:`${r}/${encodeURIComponent(e)}${s}`}async listMachines(){return m(ce,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let s=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return m(de,s,"invalid_machine").machine}async deleteMachine(e){let s=await this.request(this.machinePath(e),{method:"DELETE"});return m(ue,s,"invalid_machine_deletion")}async listSecretNames(e){let s=await this.request(`${this.secretsPath()}?scope=${e}`);return m(fe,s,"invalid_secret_list").items.map((r)=>r.name)}async setSecret(e){let s=await this.request(this.secretsPath(),{method:"POST",body:e});return m(_e,s,"invalid_secret_write")}secretsPath(){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/secrets`}async createMachineToken(e){let s=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return m(ge,s,"invalid_machine_token")}async createMachineEnrollmentTicket(e,s){let r=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:s,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return m(U,r,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(e=AbortSignal.timeout(30000)){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:e})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async registerNetworkTeam(e){await this.request("/network/teams",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:s});return m(ba,r,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((s)=>typeof s.email==="string"?[{email:s.email,role:typeof s.role==="string"?s.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,s,r={}){let a=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:r.retryUnauthorized,signal:r.signal,body:{...a,...s?{account_key:s}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((s)=>{let r=typeof s.full_name==="string"?s.full_name:typeof s.repo_full_name==="string"?s.repo_full_name:null;if(!r)return[];return[{repo_id:typeof s.repo_id==="string"?s.repo_id:void 0,full_name:r,provider:s.provider==="gitlab"?"gitlab":"github",default_branch:typeof s.default_branch==="string"?s.default_branch:null,private:typeof s.private==="boolean"?s.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),s=Z.safeParse(e);if(!s.success)throw new C(502,"invalid_project_list","Reason returned an unexpected project list.");return s.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return m(ee,e,"invalid_reason_list").items}async openReasonConversation(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return m(n({session_id:t().min(1)}),s,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return m(te,e,"invalid_skill_list").items}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],s=null;for(let r=0;r<50;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${s?`?after=${encodeURIComponent(s)}`:""}`),l=V.safeParse(a);if(!l.success)throw new C(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...l.data.devices),s=l.data.has_next_page?l.data.end_cursor??null:null,!s)break}return e}async listModels(){try{let s=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((l)=>l.hidden!==!0),r=s.filter((l)=>l.available!==!1).map(({reasoning_efforts:l,hidden:u,available:g,...h})=>({...h,...Array.isArray(l)?{reasoning_efforts:J.filter((p)=>l.includes(p))}:{}})),a=new Set(r.map((l)=>l.detail));return{models:r.length>1&&a.size===1?r.map(({detail:l,...u})=>u):r,runnable:r.length>0||s.length===0}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let s=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return S(s.reason_version)?s.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=F.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let s;try{s=G(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:s}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let s=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)s.set("origin",e.origin);s.set("fields",e.fields.join(","));let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${s.toString()}`,{status:a,headers:l,json:u}=await this.exchange(r,e.etag?{ifNoneMatch:e.etag}:{});if(a===304)return null;if(a<200||a>299)throw w(a,u,l.get("retry-after"));return{items:Array.isArray(u.items)?u.items:[],etag:l.get("etag")}}async listSessions(e=50,s,r={}){let a=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:r.status??"active"});if(s)a.set("project_id",s);if(r.origin)a.set("origin",r.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${a.toString()}`)).items??[]}getSession(e,s){let r=s?.fields.length?`?fields=${encodeURIComponent(s.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`)}async prestartSession(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return s?.status==="starting"||s?.status==="ready"}async createSession(e){let s=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(s||e.runtimeProfile){let l=await this.request("/deployment");if(s&&(!Array.isArray(l.session_modes)||!l.session_modes.includes(e.mode??"standard")||!Array.isArray(l.workspace_ownerships)||!l.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(l.experimental_runtime_profiles)||!l.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),a=await this.getSession(r.session_id);if(s){let l=a.session_policy,u=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!l||l.version!==1||l.mode!==(e.mode??"standard")||l.workspaceOwnership!==(e.workspaceOwnership??"managed")||!l.components||u.some((g)=>l.components[g]!==!0))throw await this.cancelSession(r.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&a.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(r.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return a}async getEvents(e,s=-1,r={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${s}&limit=500${r.waitMs?`&wait_ms=${r.waitMs}`:""}`,r.signal?{signal:r.signal}:{})}catch(a){if(!(a instanceof C)||a.status!==403&&a.status!==404)throw a;return{session:await this.getSession(e),items:[],next_seq:s}}}async getMessages(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${s===void 0?"":`&after_seq=${s}`}`)}async getAttachments(e,s){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${s?`?view=${s}`:""}`)).items??[]}catch(r){if(r instanceof C&&(r.status===403||r.status===404))return[];throw r}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let s=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,r=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,a=[s,r].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${a?` (${a})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,s,r={}){if(r.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:s,...r.attachments?.length?{attachments:r.attachments}:{},...r.model?{model:r.model}:{},...r.reasoningEffort?{reasoning_effort:r.reasoningEffort}:{},...r.target?{target:r.target}:{},...r.delivery?{delivery:r.delivery}:{}}})}async steerQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/queued`,{method:"DELETE"})}async getConversation(e){let s=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${r?`?after=${encodeURIComponent(r)}`:""}`);if(s.push(...l.items??[]),!l.has_next_page||!l.end_cursor)break;r=l.end_cursor}return s}createSharedLink(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:s.url,...s.label?{label:s.label}:{},...s.expiresInSeconds!==void 0?{expires_in_seconds:s.expiresInSeconds}:{}}})}sessionAction(e,s,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${s}`,{method:"POST",body:r})}renameSession(e,s){return this.sessionAction(e,"rename",{title:s||null})}moveSessionToProject(e,s){return this.sessionAction(e,"project",{project_id:s})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,s){return this.sessionAction(e,"rewind",{message_id:s.messageId,content:s.content,request_id:s.requestId})}forkSession(e,s){return this.sessionAction(e,"fork",{...s.message?{message:s.message}:{},client_session_id:s.clientSessionId})}cancelSession(e,s={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:s.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,s=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${s}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return m(x,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,s){let r=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:s}});return m(x,r,"invalid_session_tags").tags}async sessionInsight(e,s=!1){let r=await this.request(this.sessionPath(e,s?"/insights/generate":"/insights"),s?{method:"POST",body:{}}:{});return m(ae,r,"invalid_session_insight")}async listAutomations(){let e=[],s=null;for(let r=0;r<20;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${s?`&after=${encodeURIComponent(s)}`:""}`),l=m(oe,a,"invalid_automation_list");if(e.push(...l.items),s=l.has_next_page?l.end_cursor??null:null,!s)break}return e}async createScheduledAutomation(e,s){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,a=m(A,await this.request(r,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${r}/${encodeURIComponent(a.id)}/triggers`,{method:"POST",body:s})}catch(l){throw await this.deleteAutomation(a.id).catch(()=>{return}),l}return a}async setAutomationEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:s}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:s}});return m(n({transcript:t()}),r,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return m(ie,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:s}})}}
|
|
2
|
+
import{ba}from"./vm-hands-entry-lite-84mc1f7h.js";import{P}from"./vm-hands-entry-lite-2rgf8866.js";import{W}from"./vm-hands-entry-lite-q9s1e2y1.js";import{Q,ro,ve,no}from"./vm-hands-entry-lite-a7bf7xr7.js";import{xr}from"./vm-hands-entry-lite-bj3w2ven.js";import{t,o,_,d,n,rl,we,c,i}from"./vm-hands-entry-lite-k5ytpgzz.js";var E=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function S(e){let s=typeof e==="string"?E.exec(e):null;return s?{major:Number(s[1]),minor:Number(s[2])}:null}import{createHash as q,randomBytes as v}from"crypto";import{createInterface as M}from"readline";var k=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var Ge=k.filter((e)=>e!=="network:read"&&e!=="network:write");class y extends Error{oauthCode;constructor(e,s=null){super(e);this.oauthCode=s;this.name="LoginError"}}function ya(){let e=v(48).toString("base64url"),s=q("sha256").update(e).digest("base64url");return{verifier:e,challenge:s,state:v(32).toString("base64url")}}function z(e,s){let r=typeof e.error==="string"?e.error:null,a=typeof e.error_description==="string"?e.error_description:r?r:s;return new y(a,r)}async function L(e,s,r,a){let l=await r(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:s,signal:a}),u=await l.json().catch(()=>({}));if(!l.ok)throw z(u,`OAuth token request failed (${l.status})`);return u}var j=1e4;async function D(e,s={}){let r=s.fetchImpl??fetch,a=await L(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),r,AbortSignal.timeout(j)).catch((u)=>{if(u instanceof Error&&u.name==="TimeoutError")throw new y("Reason did not answer the login refresh in time. Check the network and retry.");throw u});if(typeof a.access_token!=="string"||typeof a.refresh_token!=="string"||typeof a.expires_in!=="number")throw new y("Reason returned an incomplete refreshed login.");let l={...e,accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:new Date(Date.now()+a.expires_in*1000).toISOString(),scopes:typeof a.scope==="string"?a.scope.split(/\s+/).filter(Boolean):e.scopes};return ro(l,s.path??Q()),l}var R=new Map,N=2000,H=100;function I(e,s){if(!s)return e;if(s.aborted)return Promise.reject(s.reason);return new Promise((r,a)=>{let l=()=>a(s.reason);s.addEventListener("abort",l,{once:!0}),e.then(r,a).finally(()=>s.removeEventListener("abort",l))})}async function be(e={}){let s=e.path??Q(),r=ve(s);if(!r)return null;let a=e.apiOrigin??P(process.env,"REASON_API_URL")?.trim();if(a&&!W(r.apiOrigin,new URL(a).origin))return null;if(!(Date.parse(r.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&r.accessToken!==e.refused))return r;let u=[s,r.apiOrigin,r.clientId,r.refreshToken].join("\x00"),g=R.get(u);if(g)return I(g,e.signal);let h;return h=D(r,{fetchImpl:e.fetchImpl,path:s}).catch(async(p)=>{if(!(p instanceof y)||p.oauthCode!=="invalid_grant"&&p.oauthCode!=="invalid_client")throw p;let b=(f)=>f!==null&&(p.oauthCode==="invalid_client"?f.clientId!==r.clientId:f.refreshToken!==r.refreshToken),O=Date.now()+N;while(!b(ve(s))&&Date.now()<O)await new Promise((f)=>setTimeout(f,H));if(b(ve(s)))return be({fetchImpl:e.fetchImpl,path:s});return no(s),null}).finally(()=>{if(R.get(u)===h)R.delete(u)}),R.set(u,h),I(h,e.signal)}function wa(e,s){return new Promise((r)=>{let a=M({input:e}),l=!1,u=(h)=>{if(l)return;l=!0,s.removeEventListener("abort",g),a.close(),e.pause(),r(h)},g=()=>u(null);s.addEventListener("abort",g,{once:!0}),a.once("line",(h)=>u(h)),a.once("close",()=>u(null))})}var F=n({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:_().nullable()}),B=n({groups:d(n({selectable:_().optional(),accounts:d(n({source_id:t().min(1),model_ids:d(t().min(1)).optional()}))}))});function G(e){let s=B.safeParse(e);if(!s.success)return;return s.data.groups.some((r)=>r.selectable!==!1&&r.accounts.some((a)=>a.model_ids===void 0||a.model_ids.length>0))}class C extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;refusal;constructor(e,s,r,a,l,u,g){super(r);this.status=e;this.code=s;this.suggestedModel=a;this.retryAfterMs=l;this.resolutionReason=u;this.refusal=g;this.name="ApiError"}static rateLimitDelayMs(e,s){if(!(e instanceof C)||e.status!==429)return null;return Math.min(60000,Math.max(s,e.retryAfterMs??0))}}var J=["minimal","low","medium","high","xhigh","max"],K=n({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:_(),compatible:_().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:d(n({id:t().min(1),label:t()}))}),V=n({devices:d(K),end_cursor:t().nullish(),has_next_page:_().optional()}),Y=n({id:t().min(1),name:t()}),Z=n({items:d(Y)}),X=n({id:t().min(1),name:t(),main:_(),mine:_(),session_id:t().nullish(),appearance:n({color:t().nullish()}).nullish().catch(null)}),ee=n({items:d(X)}),ne=n({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:d(t()).default([]),is_enabled:_().default(!0)}),te=n({items:d(ne).default([])}),se=n({id:t().min(1),kind:t(),enabled:_(),schedule:n({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:n({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),A=n({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:_(),triggers:d(se).default([])}),oe=n({items:d(A).default([]),end_cursor:t().nullish(),has_next_page:_().optional()}),re=n({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:_()}),ie=n({items:d(re).default([])}),ae=n({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),x=n({tags:d(t()).default([])}),le=c(["linux","macos"]),T=n({id:t().min(1),name:t().min(1),platform:le.nullable(),workers:n({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:n({queued:o().int(),running:o().int()})}),ce=n({machines:d(T)}),de=n({machine:T}),ue=n({deleted:i(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),ge=n({token:n({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),U=rl({machine_id:t().min(1),machine_name:t().min(1)}),he=U.extend({organization_id:t().min(1)}),tn=n({id:t().min(1),name:t().min(1),state:c(["waiting","placed"]),queue_position:o().int().nullable()});var sn=we([n({kind:i("cloud")}),n({kind:c(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function m(e,s,r){let a=e.safeParse(s);if(!a.success)throw new C(502,r,"Reason returned an unexpected response.");return a.data}var pe=n({error:n({type:t(),message:t()})});function w(e,s,r){let a=pe.safeParse(s),l=typeof s.error==="string"?s.error:a.success?a.data.error.type:`http_${e}`,u=typeof s.detail==="string"?s.detail:typeof s.message==="string"?s.message:a.success?a.data.error.message:`Reason request failed (${e}${typeof s.error==="string"?` ${s.error}`:""})`,g=l==="github_connection_required"&&typeof s.connect_url==="string"&&/^https?:\/\//.test(s.connect_url)?` Connect it at ${s.connect_url}`:"",h=r===null||r.trim()===""?NaN:Number(r);return new C(e,l,`${u}${g}`,typeof s.suggested_model==="string"?s.suggested_model:void 0,Number.isFinite(h)&&h>=0?h*1000:void 0,typeof s.resolution_reason==="string"?s.resolution_reason:void 0,typeof s.code==="string"?{code:s.code,...typeof s.billing_path==="string"&&/^\/(?![/\\])/.test(s.billing_path)?{billingPath:s.billing_path}:{}}:void 0)}async function eo(e){let s=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),r=await s.json().catch(()=>({}));if(!s.ok)throw w(s.status,r,s.headers.get("retry-after"));return m(he,r,"invalid_machine_ticket")}var fe=n({items:d(n({name:t()}))}),_e=n({name:t(),scope:t(),result:c(["created","updated"]).optional(),warning:n({message:t()}).optional()});class me{options;credentials;constructor(e,s={}){this.options=s;this.credentials=e}trackEvent(e,s={}){}async request(e,s={}){let{status:r,headers:a,json:l}=await this.exchange(e,s);if(r<200||r>299)throw w(r,l,a.get("retry-after"));return l}async exchange(e,s={},r=!1){let a=this.options.fetchImpl??fetch;if(!r&&s.retryUnauthorized!==!1)await this.renewBeforeExpiry(a,s.signal);let l=await a(`${this.credentials.apiOrigin}/v3${e}`,{method:s.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":xr,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...s.raw?{"content-type":s.raw.contentType}:s.body===void 0?{}:{"content-type":"application/json"},...s.headers,...s.ifNoneMatch?{"if-none-match":s.ifNoneMatch}:{}},body:s.raw?s.raw.bytes:s.body===void 0?void 0:JSON.stringify(s.body),signal:s.signal,redirect:s.ifNoneMatch?"manual":"error"}),u=await l.json().catch(()=>({}));if(l.status===401&&!r&&s.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let g=await be({fetchImpl:a,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:s.signal});if(g)return this.credentials=g,this.exchange(e,s,!0)}return{status:l.status,headers:l.headers,json:u}}async renewBeforeExpiry(e,s){let r=this.credentials;if(r.credentialKind==="api_key"||!(Date.parse(r.expiresAt)<=Date.now()+60000))return;let a=await be({fetchImpl:e,path:this.options.credentialsPath,signal:s}).catch(()=>null);if(a&&a.apiOrigin===r.apiOrigin&&a.orgId===r.orgId&&a.clientId===r.clientId)this.credentials=a}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(s){if(s instanceof C&&(s.status===404||s.status===405||s.status===403&&s.code==="endpoint_not_available"))return null;throw s}}addDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(s)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,s=""){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?r:`${r}/${encodeURIComponent(e)}${s}`}async listMachines(){return m(ce,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let s=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return m(de,s,"invalid_machine").machine}async deleteMachine(e){let s=await this.request(this.machinePath(e),{method:"DELETE"});return m(ue,s,"invalid_machine_deletion")}async listSecretNames(e){let s=await this.request(`${this.secretsPath()}?scope=${e}`);return m(fe,s,"invalid_secret_list").items.map((r)=>r.name)}async setSecret(e){let s=await this.request(this.secretsPath(),{method:"POST",body:e});return m(_e,s,"invalid_secret_write")}secretsPath(){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/secrets`}async createMachineToken(e){let s=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return m(ge,s,"invalid_machine_token")}async createMachineEnrollmentTicket(e,s){let r=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:s,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return m(U,r,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(e=AbortSignal.timeout(30000)){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:e})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async registerNetworkTeam(e){await this.request("/network/teams",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:s});return m(ba,r,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((s)=>typeof s.email==="string"?[{email:s.email,role:typeof s.role==="string"?s.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,s,r={}){let a=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:r.retryUnauthorized,signal:r.signal,body:{...a,...s?{account_key:s}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((s)=>{let r=typeof s.full_name==="string"?s.full_name:typeof s.repo_full_name==="string"?s.repo_full_name:null;if(!r)return[];return[{repo_id:typeof s.repo_id==="string"?s.repo_id:void 0,full_name:r,provider:s.provider==="gitlab"?"gitlab":"github",default_branch:typeof s.default_branch==="string"?s.default_branch:null,private:typeof s.private==="boolean"?s.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),s=Z.safeParse(e);if(!s.success)throw new C(502,"invalid_project_list","Reason returned an unexpected project list.");return s.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return m(ee,e,"invalid_reason_list").items}async openReasonConversation(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return m(n({session_id:t().min(1)}),s,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return m(te,e,"invalid_skill_list").items}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],s=null;for(let r=0;r<50;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${s?`?after=${encodeURIComponent(s)}`:""}`),l=V.safeParse(a);if(!l.success)throw new C(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...l.data.devices),s=l.data.has_next_page?l.data.end_cursor??null:null,!s)break}return e}async listModels(){try{let s=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((l)=>l.hidden!==!0),r=s.filter((l)=>l.available!==!1).map(({reasoning_efforts:l,hidden:u,available:g,...h})=>({...h,...Array.isArray(l)?{reasoning_efforts:J.filter((p)=>l.includes(p))}:{}})),a=new Set(r.map((l)=>l.detail));return{models:r.length>1&&a.size===1?r.map(({detail:l,...u})=>u):r,runnable:r.length>0||s.length===0}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let s=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return S(s.reason_version)?s.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=F.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let s;try{s=G(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:s}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let s=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)s.set("origin",e.origin);s.set("fields",e.fields.join(","));let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${s.toString()}`,{status:a,headers:l,json:u}=await this.exchange(r,e.etag?{ifNoneMatch:e.etag}:{});if(a===304)return null;if(a<200||a>299)throw w(a,u,l.get("retry-after"));return{items:Array.isArray(u.items)?u.items:[],etag:l.get("etag")}}async listSessions(e=50,s,r={}){let a=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:r.status??"active"});if(s)a.set("project_id",s);if(r.origin)a.set("origin",r.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${a.toString()}`)).items??[]}getSession(e,s){let r=s?.fields.length?`?fields=${encodeURIComponent(s.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`)}async prestartSession(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return s?.status==="starting"||s?.status==="ready"}async createSession(e){let s=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(s||e.runtimeProfile){let l=await this.request("/deployment");if(s&&(!Array.isArray(l.session_modes)||!l.session_modes.includes(e.mode??"standard")||!Array.isArray(l.workspace_ownerships)||!l.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(l.experimental_runtime_profiles)||!l.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),a=await this.getSession(r.session_id);if(s){let l=a.session_policy,u=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!l||l.version!==1||l.mode!==(e.mode??"standard")||l.workspaceOwnership!==(e.workspaceOwnership??"managed")||!l.components||u.some((g)=>l.components[g]!==!0))throw await this.cancelSession(r.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&a.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(r.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return a}async getEvents(e,s=-1,r={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${s}&limit=500${r.waitMs?`&wait_ms=${r.waitMs}`:""}`,r.signal?{signal:r.signal}:{})}catch(a){if(!(a instanceof C)||a.status!==403&&a.status!==404)throw a;return{session:await this.getSession(e),items:[],next_seq:s}}}async getMessages(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${s===void 0?"":`&after_seq=${s}`}`)}async getAttachments(e,s){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${s?`?view=${s}`:""}`)).items??[]}catch(r){if(r instanceof C&&(r.status===403||r.status===404))return[];throw r}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let s=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,r=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,a=[s,r].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${a?` (${a})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,s,r={}){if(r.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:s,...r.attachments?.length?{attachments:r.attachments}:{},...r.model?{model:r.model}:{},...r.reasoningEffort?{reasoning_effort:r.reasoningEffort}:{},...r.target?{target:r.target}:{},...r.delivery?{delivery:r.delivery}:{}}})}async steerQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/queued`,{method:"DELETE"})}async getConversation(e){let s=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${r?`?after=${encodeURIComponent(r)}`:""}`);if(s.push(...l.items??[]),!l.has_next_page||!l.end_cursor)break;r=l.end_cursor}return s}createSharedLink(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:s.url,...s.label?{label:s.label}:{},...s.expiresInSeconds!==void 0?{expires_in_seconds:s.expiresInSeconds}:{}}})}sessionAction(e,s,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${s}`,{method:"POST",body:r})}renameSession(e,s){return this.sessionAction(e,"rename",{title:s||null})}moveSessionToProject(e,s){return this.sessionAction(e,"project",{project_id:s})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,s){return this.sessionAction(e,"rewind",{message_id:s.messageId,content:s.content,request_id:s.requestId})}forkSession(e,s){return this.sessionAction(e,"fork",{...s.message?{message:s.message}:{},client_session_id:s.clientSessionId})}cancelSession(e,s={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:s.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,s=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${s}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return m(x,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,s){let r=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:s}});return m(x,r,"invalid_session_tags").tags}async sessionInsight(e,s=!1){let r=await this.request(this.sessionPath(e,s?"/insights/generate":"/insights"),s?{method:"POST",body:{}}:{});return m(ae,r,"invalid_session_insight")}async listAutomations(){let e=[],s=null;for(let r=0;r<20;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${s?`&after=${encodeURIComponent(s)}`:""}`),l=m(oe,a,"invalid_automation_list");if(e.push(...l.items),s=l.has_next_page?l.end_cursor??null:null,!s)break}return e}async createScheduledAutomation(e,s){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,a=m(A,await this.request(r,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${r}/${encodeURIComponent(a.id)}/triggers`,{method:"POST",body:s})}catch(l){throw await this.deleteAutomation(a.id).catch(()=>{return}),l}return a}async setAutomationEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:s}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:s}});return m(n({transcript:t()}),r,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return m(ie,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:s}})}}
|
|
3
3
|
export{ya,be,wa,C,eo,me};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{to}from"./vm-hands-entry-lite-84mc1f7h.js";import{spawnSync as p}from"child_process";import{createHash as de}from"crypto";import{chmodSync as ge,closeSync as pe,existsSync as w,linkSync as fe,lstatSync as me,mkdirSync as Q,mkdtempSync as he,openSync as we,readdirSync as ye,readFileSync as Ee,readSync as ke,realpathSync as Ne,renameSync as E,rmSync as k,statSync as Y,symlinkSync as W,writeFileSync as I}from"fs";import{connect as Se}from"net";import{homedir as m}from"os";import{basename as Z,dirname as R,join as u}from"path";import{inflateRawSync as be}from"zlib";var oe=new Set(["<","\u02C2","\u1438","\u2039","\u3008","\u276C","\u276E","\u2770","\u16B2","\u2D66","\uD800\uDF2D","\uD81A\uDEEC","\uD834\uDE36","\u27E8","\u27EA","\u29FC","\u3008","\u300A","\uFE64","\uFF1C"]),D=(e)=>e===" "||e==="\t"||e===`
|
|
3
3
|
`||e==="\f"||e==="\r",ie=(e)=>e.length===1&&e>="!"&&e<="~",G=(e)=>e.length===1&&/[A-Za-z]/.test(e);function J(e){let n=Array.from(e),t=(r)=>{let s=r+Math.min(n.length-r,64),o=r;while(o<s&&(D(n[o])||n[o]==="/"))o+=1;let i=o-r,a=[];while(o<s&&!D(n[o])&&n[o]!==">"&&n[o]!=="\uFF1E")a.push(n[o++]);return i+a.length===s-r&&n.length-r>64||!a.every(ie)||ae(a)};return n.map((r,s)=>oe.has(r)&&t(s+1)?"[":r).join("")}function ae(e){let n=1;for(let t of e){let r=t==="0"?"o":t==="3"?"e":t==="4"||t==="@"?"a":t==="5"||t==="$"?"s":G(t)?t.toLowerCase():t,s="reason".indexOf(r),o=s<0?0:1<<s;if(n=1|(G(t)?0:n)|(n&o)<<1,n&64)return!0}return!1}var ce=/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g;function U(e){return J(e.replace(ce," ").replace(/[\u2028\u2029]/g," "))}var le=["CLAUDECODE","CLAUDE_CODE_SESSION_ID","CODEX_THREAD_ID","CODEX_SESSION_ID","GROK_SESSION_ID","GROK_WORKSPACE_ROOT","GEMINI_CLI","CURSOR_AGENT","OPENCODE","COPILOT_CLI","COPILOT_AGENT_SESSION_ID","AI_AGENT"];function ue(e=process.env,n=Boolean(process.stderr.isTTY)){let t=le.some((r)=>e[r]!==void 0)||Object.keys(e).some((r)=>r.startsWith("CODEX_SANDBOX"))||Boolean(e.REASON_NETWORK_AGENT)||Boolean(e.TINCAN_AGENT);return n&&!t}function Fe(e,n=ue()){return n?e:U(e)}class Ce extends Error{}var f="reason-network",g="0.12.10",_e={"aarch64-apple-darwin":"fd3e6eccf76aa3f3cdcbe516bb2e0885bc9416e89378d858c5d96e58a37a2996","x86_64-apple-darwin":"68a224c4e51ec91c4754fdda2724de0e72ba3f27b687b2466a7c7d5e492ad72c","aarch64-unknown-linux-musl":"ca6177ba2ac3fc2d1ca0a06953cb33ee09ab6d83f5b957bee54339b41b6672b4","x86_64-unknown-linux-musl":"d872f3e96066ed717cc775f9c580a2ab68feace60e06427ff216cec985f2115a","aarch64-pc-windows-msvc":"67b4f3f9c3f7e69e285eef863009fa014195b1c91a4e8b1abca81f1a085e55ed","x86_64-pc-windows-msvc":"9fad0c86fdc56e7b837b7c98960f685dd63721f4e6be5a172f8198eee82e5869"},Re="https://reasonmachines.com/cli/engine",N="REASON_AGENT_NETWORK_BIN";function ve(e=process.platform,n=process.arch){let t=n==="arm64"?"aarch64":n==="x64"?"x86_64":null,r=e==="darwin"?"apple-darwin":e==="linux"?"unknown-linux-musl":e==="win32"?"pc-windows-msvc":null;return t&&r?`${t}-${r}`:null}function ee(e){return`${f}-${e}${e.endsWith("-windows-msvc")?".zip":".tar.gz"}`}function xe(e){let n=_e[e];return n?{url:`${Re}/${g}/${ee(e)}`,sha256:n}:null}function A(e){let n=p(e,["--version"],{encoding:"utf8",timeout:5000}),[t,r]=n.status===0?n.stdout.trim().split(/\s+/):[];return t===f?r??null:null}function _(e,n){let t=e.split(".").map(Number),r=n.split(".").map(Number);for(let s=0;s<3;s+=1)if((t[s]??0)!==(r[s]??0))return(t[s]??0)>(r[s]??0);return!0}function S(e=m(),n=process.platform){return u(e,".reason","bin",`${f}${n==="win32"?".exe":""}`)}var v=process.platform==="win32"?`~\\.local\\bin\\${f}.exe`:`~/.local/bin/${f}`;async function Te(e=process.env,n=()=>{}){if(e[N])return e[N];let t=S(),r=T(),s=r?.path===t&&y(t)===r.fingerprint?r:null,o=s?.kept,i=M(e)?null:$e(o);if(s?.version===g&&!i)return t;let a=w(t)?A(t):null;if(i){let c=A(i.path),d=a&&_(a,g)?a:g;if(!c||!_(d,c)){if(c)n(`Reason Network: ${v} (${c}) is newer than the version \`reason network\` keeps up to date (${d}), so it was left as it is.`);o=i.fingerprint,i=null}}if(s?.version===g&&!i)return F(t,o);if(!a||!_(a,g))await ne(t);let l=p(t,["setup",...M(e)?["--no-service"]:[]],{env:await C(e),encoding:"utf8",timeout:60000});if(l.status!==0){let c=b((l.stderr||l.stdout||"").trim().split(`
|
|
4
|
-
`).pop()??"");if(s)return B(m(),{...s,fingerprint:y(t)??s.fingerprint,...o?{kept:o}:{}}),n(i?`Reason Network: couldn't move your agents off ${v}${c?` (${c})`:""}; they keep using it. Run reason network to try again.`:`Reason Network: couldn't finish setting up on this computer${c?` (${c})`:""}. Run reason network to try again.`),t;throw new Ce(`Couldn't connect this computer's agents to the network${c?` (${c})`:""}. Run reason network to try again.`)}if(i)o=Pe(i,t,n);return F(t,o),p(t,["stop"],{env:e,stdio:"ignore",timeout:15000}),t}function $e(e){let n=u(m(),".local","bin",Z(S())),t;try{t=me(n)}catch{return null}let r=`${t.size}:${t.mtimeMs}:${t.ino}`;if(!t.isFile()||r===e)return null;try{let s=Y(S());if(s.ino===t.ino&&s.dev===t.dev)return null}catch{}try{let s=Buffer.alloc(2),o=we(n,"r");try{ke(o,s,0,2,0)}finally{pe(o)}if(s.toString("latin1")==="#!")return null}catch{return null}return{path:n,fingerprint:r}}function Pe(e,n,t){let r=`${e.path}.reason-${process.pid}`;try{if(k(r,{force:!0}),process.platform==="win32"){try{W(n,r,"file")}catch{fe(n,r)}te(r,e.path,"win32")}else W(n,r),E(r,e.path);t(`Reason Network: your agents on this computer now use the version \`reason network\` keeps up to date (${v} points to it). Restart a running agent to pick it up.`);return}catch(s){return k(r,{force:!0}),t(`Reason Network: your agents on this computer now use the version \`reason network\` keeps up to date, but ${v} couldn't be pointed to it (${s instanceof Error?s.message:String(s)}). Remove that copy so it can't take them back.`),e.fingerprint}}async function al(e={}){let n=e.env??process.env,t=e.home??m(),r=S(t),s=T(t);if(n[N]||s?.path!==r||y(r)!==s.fingerprint)return!1;if(s.version===g)return!1;let o=A(r);if(o&&_(o,g))return!1;return await ne(r),B(t,{...s,fingerprint:y(r)??""}),e.beforeRestart?.(),p(r,["stop"],{env:n,stdio:"ignore",timeout:15000}),!0}async function C(e){if(e[j])return e;try{let{defaultWorkerServiceHost:n,workerServiceLauncher:t}=await import("./serve-service-
|
|
4
|
+
`).pop()??"");if(s)return B(m(),{...s,fingerprint:y(t)??s.fingerprint,...o?{kept:o}:{}}),n(i?`Reason Network: couldn't move your agents off ${v}${c?` (${c})`:""}; they keep using it. Run reason network to try again.`:`Reason Network: couldn't finish setting up on this computer${c?` (${c})`:""}. Run reason network to try again.`),t;throw new Ce(`Couldn't connect this computer's agents to the network${c?` (${c})`:""}. Run reason network to try again.`)}if(i)o=Pe(i,t,n);return F(t,o),p(t,["stop"],{env:e,stdio:"ignore",timeout:15000}),t}function $e(e){let n=u(m(),".local","bin",Z(S())),t;try{t=me(n)}catch{return null}let r=`${t.size}:${t.mtimeMs}:${t.ino}`;if(!t.isFile()||r===e)return null;try{let s=Y(S());if(s.ino===t.ino&&s.dev===t.dev)return null}catch{}try{let s=Buffer.alloc(2),o=we(n,"r");try{ke(o,s,0,2,0)}finally{pe(o)}if(s.toString("latin1")==="#!")return null}catch{return null}return{path:n,fingerprint:r}}function Pe(e,n,t){let r=`${e.path}.reason-${process.pid}`;try{if(k(r,{force:!0}),process.platform==="win32"){try{W(n,r,"file")}catch{fe(n,r)}te(r,e.path,"win32")}else W(n,r),E(r,e.path);t(`Reason Network: your agents on this computer now use the version \`reason network\` keeps up to date (${v} points to it). Restart a running agent to pick it up.`);return}catch(s){return k(r,{force:!0}),t(`Reason Network: your agents on this computer now use the version \`reason network\` keeps up to date, but ${v} couldn't be pointed to it (${s instanceof Error?s.message:String(s)}). Remove that copy so it can't take them back.`),e.fingerprint}}async function al(e={}){let n=e.env??process.env,t=e.home??m(),r=S(t),s=T(t);if(n[N]||s?.path!==r||y(r)!==s.fingerprint)return!1;if(s.version===g)return!1;let o=A(r);if(o&&_(o,g))return!1;return await ne(r),B(t,{...s,fingerprint:y(r)??""}),e.beforeRestart?.(),p(r,["stop"],{env:n,stdio:"ignore",timeout:15000}),!0}async function C(e){if(e[j])return e;try{let{defaultWorkerServiceHost:n,workerServiceLauncher:t}=await import("./serve-service-3dkyznay.js");return{...e,[j]:t(n(m()),e)}}catch{return e}}var j="REASON_NETWORK_REASON_BIN";function M(e=process.env){return Boolean(e.REASON_NETWORK_NO_SERVICE||e.TINCAN_NO_SERVICE)}var L=(e)=>u(e,".reason","ask-engine.json");function y(e){try{let n=Y(e);return`${n.size}:${n.mtimeMs}:${n.ino}`}catch{return null}}function cl(e=m()){return T(e)?.version??null}function T(e=m()){try{let n=JSON.parse(Ee(L(e),"utf8"));if(typeof n.path!=="string"||typeof n.fingerprint!=="string"||typeof n.version!=="string")return null;return{path:n.path,fingerprint:n.fingerprint,version:n.version,...typeof n.kept==="string"?{kept:n.kept}:{}}}catch{return null}}function B(e,n){Q(R(L(e)),{recursive:!0}),I(L(e),JSON.stringify(n))}function F(e,n){let t=y(e);if(t)B(m(),{path:e,fingerprint:t,version:g,...n?{kept:n}:{}});return e}async function ne(e){let n=ve(),t=n?xe(n):null;if(!n||!t)throw new Ce(`Reason Network runs on macOS, Linux and Windows (arm64 or x64); this is ${process.platform} ${process.arch}.`);let{url:r,sha256:s}=t,o;try{let a=await fetch(r,{signal:AbortSignal.timeout(120000)});if(!a.ok)throw Error(`HTTP ${a.status}`);o=Buffer.from(await a.arrayBuffer())}catch(a){let l=a instanceof Error&&a.name==="TimeoutError"?"no download within 2 minutes":a instanceof Error?a.message.replace(/\.$/,""):String(a);throw new Ce(`Couldn't download Reason Network from ${new URL(r).host} (${l}). Check the connection and run reason network again.`)}if(de("sha256").update(o).digest("hex")!==s)throw new Ce("The Reason Network download didn't match its checksum, so it wasn't installed.");Oe(o,n,e)}var H="Couldn't unpack the Reason Network download.";function Oe(e,n,t,r=process.platform){Q(R(t),{recursive:!0});let s=he(u(R(t),".reason-engine-"));try{let o=u(s,f);if(ee(n).endsWith(".zip"))o=u(s,`${f}.exe`),I(o,Ie(e,`${f}.exe`));else{I(u(s,"engine.tar.gz"),e);let i=p("tar",["--no-same-owner","-xzf",u(s,"engine.tar.gz"),"-C",s],{encoding:"utf8"});if(i.status!==0||!w(o)){let a=(i.stderr??"").trim().split(`
|
|
5
5
|
`).slice(-3).join("; "),l=i.error?`tar failed: ${i.error.message}`:i.signal?`tar was stopped by ${i.signal}`:i.status!==0?`tar exited ${i.status}${a?`: ${a}`:""}`:`no ${f} in it`;throw new Ce(`Couldn't unpack the Reason Network download (${l}).`)}}ge(o,493),te(o,t,r)}finally{k(s,{recursive:!0,force:!0})}}function Ie(e,n){let t=e.lastIndexOf(Buffer.from("PK\x05\x06","latin1"));if(t<0||t+22>e.length)throw new Ce(H);let r=e.readUInt32LE(t+16);for(let s=e.readUInt16LE(t+10);s>0;s-=1){if(r+46>e.length||e.readUInt32LE(r)!==33639248)break;let o=e.readUInt16LE(r+28);if(e.toString("utf8",r+46,r+46+o)===n){let i=e.readUInt16LE(r+10),a=e.readUInt32LE(r+20),l=e.readUInt32LE(r+24),c=e.readUInt32LE(r+42);if(c+30>e.length||e.readUInt32LE(c)!==67324752)break;let d=c+30+e.readUInt16LE(c+26)+e.readUInt16LE(c+28);if(d+a>e.length)break;let h=e.subarray(d,d+a),P;try{P=i===0?Buffer.from(h):i===8?be(h):Buffer.alloc(0)}catch{break}if(i!==0&&i!==8||P.length!==l)break;return P}r+=46+o+e.readUInt16LE(r+30)+e.readUInt16LE(r+32)}throw new Ce(H)}function te(e,n,t){if(t!=="win32"||!w(n)){E(e,n);return}let r=R(n),s=(i)=>i.startsWith(`${Z(n)}.`)&&i.endsWith(".old");for(let i of ye(r).filter(s))try{k(u(r,i),{force:!0})}catch{}let o=`${n}.${process.pid}-${Date.now()}.old`;E(n,o);try{E(e,n)}catch(i){throw E(o,n),i}try{k(o,{force:!0})}catch{}}function Ae(e=process.env,n=m()){let t=e.REASON_NETWORK_HOME?.trim()||e.TINCAN_HOME?.trim();if(t)return t;let r=u(n,".reason","network"),s=u(n,".tincan");return!K(r)&&K(s)?s:r}var K=(e)=>w(u(e,"network.db"))||w(u(e,"tincan.db"));function Me(e,n=process.platform,t=Ne.native){let r=w(u(e,"network.db"))||!w(u(e,"tincan.db"));if(n==="win32"){let o=e;try{o=t(e),o=o.startsWith("\\\\?\\")?o.slice(4):o.startsWith("\\\\")?`UNC\\${o.slice(2)}`:o}catch{}return`\\\\.\\pipe\\${r?"reason-network":"tincan"}-${z(o)}`}let s=u(e,r?"network.sock":"tincan.sock");if(Buffer.byteLength(s)<100)return s;return u("/tmp",`${r?"reason-network":"tincan"}-${process.getuid?.()??0}`,`${z(s)}.sock`)}function z(e){let n=0xcbf29ce484222325n;for(let t of Buffer.from(e))n=BigInt.asUintN(64,(n^BigInt(t))*0x100000001b3n);return n.toString(16).padStart(16,"0")}class qr extends Error{code;constructor(e,n){super(e);this.code=n}}function Ji(e){return e instanceof qr&&/isn't registered/.test(e.message)}var re="not_in_team",se=15000,Le=new Set(["who","team","inbox","unread","held"]),Be=90000,De="Reason Network on this computer closed the connection";class x{socket;nextId=1;buffer="";pending=new Map;closed=null;hungUp=!1;constructor(e){this.socket=e;e.setEncoding("utf8"),e.on("data",(t)=>this.read(t));let n=(t)=>{this.closed=t;for(let r of this.pending.values())r.reject(t);this.pending.clear()};e.on("error",(t)=>n(t)),e.on("close",()=>n(Error(this.hungUp?"the connection to Reason Network on this computer was closed here":De)))}static open(e){return new Promise((n,t)=>{let r=Se(e);r.once("connect",()=>n(new x(r))),r.once("error",t)})}read(e){this.buffer+=e;let n=this.buffer.indexOf(`
|
|
6
6
|
`);while(n>=0){let t=this.buffer.slice(0,n);if(this.buffer=this.buffer.slice(n+1),n=this.buffer.indexOf(`
|
|
7
7
|
`),!t.trim())continue;let r;try{r=JSON.parse(t)}catch{continue}if(typeof r.id!=="number")continue;let s=this.pending.get(r.id);if(!s)continue;if(this.pending.delete(r.id),r.ok){s.resolve(r.result);continue}let o=r.error??"Reason Network on this computer refused the request",i=typeof r.code==="string"?r.code:/not (in|connected to) a team/i.test(o)?re:null;s.reject(new qr(b(o),i))}}call(e,n={},t=se){if(this.closed)return Promise.reject(this.closed);let r=this.nextId++;return this.socket.write(`${JSON.stringify({id:r,op:e,...n})}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{P}from"./vm-hands-entry-lite-2rgf8866.js";import{w}from"./vm-hands-entry-lite-q9s1e2y1.js";import{it,Qo,Oi,qe}from"./vm-hands-entry-lite-sy7dcccg.js";import{ss,Dn,Oc}from"./vm-hands-entry-lite-
|
|
2
|
+
import{P}from"./vm-hands-entry-lite-2rgf8866.js";import{w}from"./vm-hands-entry-lite-q9s1e2y1.js";import{it,Qo,Oi,qe}from"./vm-hands-entry-lite-sy7dcccg.js";import{ss,Dn,Oc}from"./vm-hands-entry-lite-6jxshhps.js";import{B}from"./vm-hands-entry-lite-8xv6c0rm.js";import{spawnSync as v}from"child_process";import{createHash as Se,randomUUID as we}from"crypto";import{chmodSync as $e,existsSync as T,mkdirSync as ye,readdirSync as Fe,readFileSync as p,renameSync as ve,rmSync as u,statSync as be,writeFileSync as We}from"fs";import{dirname as Ae,isAbsolute as q,join as g}from"path";import{spawnSync as ue}from"child_process";import{readFileSync as me}from"fs";import{userInfo as O}from"os";import{join as fe}from"path";var ge="REASON_SCHEDULED_TASK";function Ti(r){return fe(r,"AppData","Local","Reason","Tasks")}function S(r){if(/[\0-\x1f\x7f"%]/.test(r))throw Error(`A background task cannot use a value with a double quote, percent sign or control character: ${r}`);return`'${r.replace(/['\u2018\u2019\u201a\u201b]/g,"$&$&")}'`}function D(r){if(!/^[A-Za-z0-9._-]+$/.test(r))throw Error(`Invalid Windows Scheduled Task name: ${r}`);return`$env:${ge}=${S(r)};`}function H(r){let e=Object.entries(r.environment).map(([t,i])=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw Error(`Invalid Windows Scheduled Task environment name: ${t}`);return`$env:${t}=${S(i)};`}),n=`$global:LASTEXITCODE=1; & ${[r.program,...r.args].map(S).join(" ")} 2>&1 | ForEach-Object { Add-Content -LiteralPath ${S(r.log)} -Value $_.ToString() -Encoding UTF8 }; $c=$LASTEXITCODE;`;return[D(r.name),...e,"$ErrorActionPreference='Continue';",r.keepAlive?`do { ${n} if ($c) { Start-Sleep -Seconds 10 } } while ($c)`:`${n} exit $c`].join(" ")}function I(r){return r.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function pe(){let r=process.env.USERDOMAIN?.trim();return r?`${r}\\${O().username}`:O().username}function M(r){let e=I(r.user??pe()),n=r.schedule==="logon",t=r.schedule==="logon"?`<LogonTrigger><Enabled>true</Enabled><UserId>${e}</UserId></LogonTrigger>`:`<TimeTrigger><Repetition><Interval>PT${r.schedule.everyMinutes}M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition><StartBoundary>2026-01-01T00:00:00</StartBoundary><Enabled>true</Enabled></TimeTrigger>`,i=`-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -Command "${r.script}"`;return`<?xml version="1.0" encoding="UTF-16"?>
|
|
3
3
|
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
4
4
|
<RegistrationInfo>
|
|
5
5
|
<Description>${I(r.description)}</Description>
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{mt,gr,Se}from"./vm-hands-entry-lite-pxtycfdv.js";import{st,Et,Oe,kt,Ge,Cr,Zt,Ne,X,te,Ui}from"./vm-hands-entry-lite-9g52kxyj.js";import{kn,vr}from"./vm-hands-entry-lite-q9s1e2y1.js";import{ic,F,zt,gt,qt,He,Wt,jo,_t,fn,rt,Ee,ce,nt,xi,Ci,Uo}from"./vm-hands-entry-lite-jpvmkce5.js";import{xt,Ke,at,Le,At,xe,pe}from"./vm-hands-entry-lite-71ebge0c.js";import{tn,hi,pr,Re,U,H,R,Ro}from"./vm-hands-entry-lite-v4hr9x9h.js";import{Bt,pi,Ao,tc,je,Po}from"./vm-hands-entry-lite-weqam12f.js";import{ue}from"./vm-hands-entry-lite-q9djb28r.js";import{da}from"./vm-hands-entry-lite-z0ht62s4.js";import{v,Mt,en,dr,Ya,pt,ht}from"./vm-hands-entry-lite-0wb1n769.js";import{b,m,y}from"./vm-hands-entry-lite-yvws5zpx.js";import{L}from"./vm-hands-entry-lite-ptycjmkc.js";import{On}from"./vm-hands-entry-lite-f95mg81d.js";import{s,Lc,$c,Ve,Bc}from"./vm-hands-entry-lite-zawytz09.js";import{he,sa,aa,zc,I,t,V,Mr,o,_,d,n,h,A,$e,c,i}from"./vm-hands-entry-lite-k5ytpgzz.js";import{la}from"./vm-hands-entry-lite-qf990rxw.js";import{Wc,Xe,fa,B,Tt,Be,G}from"./vm-hands-entry-lite-8xv6c0rm.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{readFileSync as Oo,realpathSync as go,statSync as Hi}from"fs";import{homedir as Ni}from"os";import{dirname as Li,isAbsolute as Bi,join as wt,sep as ji}from"path";var Di=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function a(f){return e[f]??null}let l={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},u={nan:"NaN"};return(f)=>{switch(f.code){case"invalid_type":{let g=u[f.expected]??f.expected,k=zc(f.input),O=u[k]??k;return`Invalid input: expected ${g}, received ${O}`}case"invalid_value":if(f.values.length===1)return`Invalid input: expected ${aa(f.values[0])}`;return`Invalid option: expected one of ${sa(f.values,"|")}`;case"too_big":{let g=f.inclusive?"<=":"<",k=a(f.origin);if(k)return`Too big: expected ${f.origin??"value"} to have ${g}${f.maximum.toString()} ${k.unit??"elements"}`;return`Too big: expected ${f.origin??"value"} to be ${g}${f.maximum.toString()}`}case"too_small":{let g=f.inclusive?">=":">",k=a(f.origin);if(k)return`Too small: expected ${f.origin} to have ${g}${f.minimum.toString()} ${k.unit}`;return`Too small: expected ${f.origin} to be ${g}${f.minimum.toString()}`}case"invalid_format":{let g=f;if(g.format==="starts_with")return`Invalid string: must start with "${g.prefix}"`;if(g.format==="ends_with")return`Invalid string: must end with "${g.suffix}"`;if(g.format==="includes")return`Invalid string: must include "${g.includes}"`;if(g.format==="regex")return`Invalid string: must match pattern ${g.pattern}`;return`Invalid ${l[g.format]??f.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${f.divisor}`;case"unrecognized_keys":return`Unrecognized key${f.keys.length>1?"s":""}: ${sa(f.keys,", ")}`;case"invalid_key":return`Invalid key in ${f.origin}`;case"invalid_union":if(f.options&&Array.isArray(f.options)&&f.options.length>0)return`Invalid discriminator value. Expected ${f.options.map((k)=>`'${k}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${f.origin}`;default:return"Invalid input"}}};function mn(){return{localeError:Di()}}he(mn());var Zn="--proxy",Qn="--proxy-ca-file",Mi=262144;class K extends Error{}function gn(e){let a;try{a=new URL(e)}catch{throw new K("The proxy must be a URL like https://proxy.example.com:3128.")}if(a.protocol!=="https:"&&a.protocol!=="http:")throw new K("The proxy URL must use the https or http scheme.");if(!a.hostname)throw new K("The proxy URL must name a host.");if(a.port!==""&&Number(a.port)<1)throw new K("The proxy URL must use a port between 1 and 65535.");if(a.pathname!==""&&a.pathname!=="/"||a.search||a.hash)throw new K("The proxy URL must not carry a path, query, or fragment.");return a.toString()}function La(e){let a=new URL(e.url),l=a.port||(a.protocol==="https:"?"443":"80");return`${a.hostname}:${l}`}function Wi(e={}){let a=e.home??Ni(),l=e.statePath??mt();return[Li(l),wt(a,".ssh"),wt(a,".aws"),wt(a,".gnupg"),wt(a,".kube"),wt(a,"Library","Keychains")]}function Fi(e,a){return a===e||a.startsWith(e+ji)}function zi(e,a={}){if(!Bi(e))throw new K("The proxy CA file must be an absolute path.");let l,u,f;try{l=go(e);let O=Hi(l);u=O.size,f=O.isFile()}catch{throw new K("The proxy CA file does not exist or is not readable.")}if(!f)throw new K("The proxy CA file must be a regular file.");if(u>Mi)throw new K("The proxy CA file must be 256 KB or smaller.");let g=Wi(a).flatMap((O)=>{try{let w=go(O);return w===O?[O]:[O,w]}catch{return[O]}});for(let O of[e,l])if(g.some((w)=>Fi(w,O)))throw new K("The proxy CA file must not live inside a credential directory.");let k;try{k=Oo(l,"utf8")}catch{throw new K("The proxy CA file is not readable.")}if(!k.includes("-----BEGIN CERTIFICATE-----"))throw new K("The proxy CA file must be a PEM certificate bundle.");return l}function $a(e,a={}){if(!e.proxyUrl)throw new K("A proxy URL is required.");let l=gn(e.proxyUrl),u=e.caFile===void 0?void 0:zi(e.caFile,a);return{version:gr,url:l,...u===void 0?{}:{caFile:u}}}function oe(e,a=fetch){if(!e)return a;let l,u=!1;return(g,k)=>{if(!u){if(e.caFile)try{l=Oo(e.caFile,"utf8")}catch{throw new K(`The configured proxy CA file is not readable: ${e.caFile}`)}u=!0}let O={...k,proxy:e.url,...l===void 0?{}:{tls:{ca:l}}};return a(g,O)}}import{createHash as $i}from"crypto";import{isAbsolute as To,join as Do,relative as Co,resolve as jt,sep as Ho}from"path";var Nt=t().min(1).refine(To,"absolute path required"),Io=h({version:i(1),apiOrigin:Mr(),channel:c(["staging","production"]),stateDirectory:Nt,workspaceRoot:Nt,lifetime:c(["persistent","ephemeral"]),executionMode:c(["confined","host"]).default("confined"),name:t().min(1).max(160).default("Reason headless worker"),slots:o().int().min(1).max(4).default(1),shutdownGraceMs:o().int().min(0).max(300000).default(30000),proxy:h({version:i(gr),url:t().refine((e)=>{try{return gn(e)===e}catch{return!1}},"invalid proxy URL"),caFile:Nt.optional()}).optional(),userChrome:_().optional(),cloudSessions:i(!0).optional(),localLogins:_().optional(),folders:d(Nt).min(1).max(31).optional()}),Ki=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,x=A("channel",[Io,Io.extend({channel:i("local-qa"),apiOrigin:t()})]).superRefine((e,a)=>{if(e.channel==="local-qa"){if(!Ki.test(e.apiOrigin))a.addIssue({code:"custom",message:"local QA worker requires an exact HTTPS trycloudflare.com quick-tunnel origin"})}else{let u=new URL(e.apiOrigin);if(u.origin!==e.apiOrigin||u.username||u.password||u.protocol!=="https:"&&!(u.protocol==="http:"&&vr(u.origin))||!vr(u.origin)&&!kn(e.channel,u.origin))a.addIssue({code:"custom",message:"API origin must match channel (or loopback)"})}if(!ge(e.workspaceRoot,e.stateDirectory))a.addIssue({code:"custom",message:"state and workspace must be disjoint"});let l=e.folders??[];if(new Set([e.workspaceRoot,...l]).size!==l.length+1||l.some((u)=>!ge(u,e.stateDirectory)))a.addIssue({code:"custom",message:"folders must be distinct and disjoint from state"})});function p(e){return Do(e.stateDirectory,`headless-${e.channel}`)}function _o(e,a={},l={}){let u=e.executionMode==="host"?"unsandboxed":"sandboxed";return{worker:Object.freeze({executionMode:u,runtimeDirectory:p(e),handsSlots:e.slots,...l.ownComputer?{ownComputer:!0}:{},readiness:Object.freeze({...a}),...l.persistentTerminals?{persistentTerminals:!0}:{},...l.probing?.length?{probing:Object.freeze([...l.probing])}:{},...l.displayVideo?{displayVideo:!0}:{},...l.handsBrowser&&a["hands.connect"]===!0?{handsBrowser:!0}:{},...l.githubSignedIn===void 0?{}:{githubSignedIn:l.githubSignedIn},...e.userChrome!==!1&&l.userChrome?{userChrome:l.userChrome}:{},...e.cloudSessions&&a["automation.call.v1"]===!0?{cloudSessions:!0}:{}}),proxy:e.proxy??null}}function ge(e,a){if(se(a,e))return!1;return!se(e,a)||L(Do(Ho,Co(jt(e),jt(a))))}function se(e,a){let l=Co(jt(e),jt(a));return l===""||l!==".."&&!l.startsWith(`..${Ho}`)&&!To(l)}function D(e){let{proxy:a,userChrome:l,cloudSessions:u,localLogins:f,folders:g,...k}=e;return $i("sha256").update(JSON.stringify(k)).digest("hex")}var Gi=4,Ji=[2375,2376,9222,9229];function ei(e){let a=new Set(Ji);for(let l of e){let u=new URL(l);a.add(Number(u.port||(["https:","wss:"].includes(u.protocol)?443:80)))}return a}function kr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var Vi=60000;function No(e){let a=new AbortController,l=new Map,u=(w)=>JSON.stringify([w.jobId,w.port]);function f(w){let P=e.authority.owner;if(a.signal.aborted||!e.isCurrent()||e.expiresAtMs<=Date.now()||w.organization_id!==P.organization_id||w.user_id!==P.user_id||w.device_id!==P.device_id)kr()}function g(w){let P;try{P=e.environment.current()}catch{return null}return P.binding.target_generation===w.generation&&P.binding.target_fence_id===w.fenceId&&P.run_id===e.runId&&P.device_id===e.authority.owner.device_id&&P.root_id===e.authority.rootId?P:null}async function k(w,P,N){let T=await O(w,P,N);if(T!=="moved")return T;let S=await O(w,P,N);return S==="moved"?null:S}async function O(w,P,N){try{f(e.authority.owner);let T=e.identity();if(!T||N.aborted||w.expiresAtMs<=Date.now()||w.expiresAtMs>e.expiresAtMs)return null;let S=P.opened,M=S!==void 0&&T.generation>S.generation,j=g(T);if(M){if(j){if(j.revision<=S.revision||w.expiresAtMs>Date.parse(j.expires_at)||j.binding.target_revision!==S.attachmentRevision||j.binding.root_grant_revision!==S.grantRevision)return null;P.recoveringSinceMs=void 0}else if(Date.now()-(P.recoveringSinceMs??=Date.now())>Vi)return null}else if(!j||w.expiresAtMs>Date.parse(j.expires_at)||S&&(T.generation!==S.generation||T.fenceId!==S.fenceId))return null;let C=await e.inspect(w.jobId,N),z=e.identity(),Q=z&&g(z);f(e.authority.owner);let Y=j&&{generation:T.generation,fenceId:T.fenceId,snapshotId:j.snapshot_id,revision:j.revision,attachmentRevision:j.binding.target_revision,grantRevision:j.binding.root_grant_revision},re=M?S:Y;if(N.aborted||!z)return null;if(z.generation!==T.generation||z.fenceId!==T.fenceId||Q?.snapshot_id!==j?.snapshot_id||Q?.revision!==j?.revision)return"moved";let we=C.ok&&C.job.environmentSnapshotId!==void 0&&C.job.environmentRevision!==void 0?{snapshotId:C.job.environmentSnapshotId,revision:C.job.environmentRevision}:null;if(!C.ok||C.generation!==T.generation||!re||!we)return null;if((we.snapshotId!==re.snapshotId||we.revision!==re.revision)&&(M||!e.environment.carried(we.snapshotId,we.revision)))return null;if(!S&&T.generation===w.generation&&T.fenceId===w.fenceId)P.opened={...re,...we};return{executorLaunchId:e.executorLaunchId,job:C.job,binding:{organizationId:e.authority.owner.organization_id,userId:e.authority.owner.user_id,deviceId:e.authority.owner.device_id,rootId:e.authority.rootId,runId:e.runId,attachmentRevision:re.attachmentRevision,grantRevision:re.grantRevision,generation:re.generation,fenceId:re.fenceId,jobId:C.job.jobId,port:w.port,expiresAtMs:w.expiresAtMs}}}catch{return null}}return{async open(w,P,N){f(P);let{binding:T,deviceRelayUrl:S}=dr(w);if(N.aborted||T.expiresAtMs<=Date.now()||T.expiresAtMs>Date.now()+v.lifetimeMs||new URL(S).origin!==e.authority.relayOrigin)kr();let M=u(T),j=l.get(M);if(j){if(!Mt(j.binding,T)||j.relay!==S)kr();if(await j.opened,!await en(()=>j.port.check())||N.aborted||j.abort.signal.aborted)kr();return{opened:!0,binding:T}}if(l.size>=Gi)kr();let C=new AbortController,z={},Q=ht({binding:T,deniedPorts:e.authority.deniedPorts,readCurrentJob:()=>k(T,z,C.signal)}),Y=()=>C.abort();if(N.addEventListener("abort",Y,{once:!0}),a.signal.addEventListener("abort",Y,{once:!0}),N.aborted||a.signal.aborted)Y();let re=pt({binding:T,deviceRelayUrl:S,port:Q,signal:C.signal}),we={binding:T,relay:S,abort:C,port:Q,opened:re};l.set(M,we);let Ie=()=>{if(N.removeEventListener("abort",Y),a.signal.removeEventListener("abort",Y),l.get(M)===we)l.delete(M)};try{if((await re).closed.then(Ie),N.removeEventListener("abort",Y),f(P),C.signal.aborted||!await en(()=>Q.check()))kr();return{opened:!0,binding:T}}catch{C.abort(),Ie(),kr()}},async close(w,P){f(P);let{binding:N}=Ya(w),T=l.get(u(N));if(!T||!Mt(T.binding,N))kr();return T.abort.abort(),await T.opened.then((S)=>S.closed,()=>{return}),{closed:!0,binding:N}},dispose(){a.abort();for(let w of l.values())w.abort.abort();l.clear()}}}import{WebSocket as bn}from"ws";var Lo=(e)=>("data"in e)?e.data.length:e.bytes,Bo=2*Wt;function Fe(e){throw new r(e,"The bound Hands terminal is unavailable or its outcome is unconfirmed.")}var Ur=(e)=>!["starting","running"].includes(e.state);function Ma(e,a,l=Date.now()){let u=["relay_url","session_id","expires_at","cols","rows","pty","workspace"];if(Object.keys(e).length!==u.length||Object.keys(e).some((P)=>!u.includes(P))||!rt(a)||!rt(e.session_id)||typeof e.expires_at!=="string"||typeof e.relay_url!=="string"||e.relay_url.length>4096||![e.cols,e.rows].every((P)=>Number.isSafeInteger(P)&&Number(P)>=1&&Number(P)<=_t))Fe("invalid_pty_request");let f=e.pty;if(!f||typeof f!=="object"||Array.isArray(f))Fe("invalid_pty_request");let g=f;if(Object.keys(g).length!==2||g.version!==1||!nt(g.jobId))Fe("invalid_pty_request");let k;try{k=new URL(e.relay_url)}catch{return Fe("invalid_pty_request")}if(!["ws:","wss:"].includes(k.protocol)||k.username||k.password||k.hash||k.protocol==="ws:"&&!["127.0.0.1","[::1]","localhost"].includes(k.hostname))Fe("invalid_pty_request");let O=Date.parse(e.expires_at);if(!Number.isSafeInteger(O)||O<=l)Fe("invalid_pty_request");return{workspace:te(e.workspace)??Fe("invalid_pty_request"),session:{jobId:g.jobId,sessionId:e.session_id,operationId:a,relayUrl:k.href,cols:Number(e.cols),rows:Number(e.rows),leaseExpiresAtMs:Math.min(O,l+43200000)}}}async function Mo(e){let{session:a,binding:l}=e;if(l.assertCurrent(),e.signal.aborted||Date.now()>=a.leaseExpiresAtMs)Fe("cancelled");let u=new bn(a.relayUrl,{followRedirects:!1,perMessageDeflate:!1,maxPayload:He}),f=new AbortController,g=()=>{},k=()=>{f.abort(),g()};e.signal.addEventListener("abort",k,{once:!0});let O=setTimeout(k,Math.max(1,a.leaseExpiresAtMs-Date.now())),w=[],P=0,N=0,T=0,S=!1,M=!1,j=!1,C,z,Q,Y=(W)=>{Q=new r(W,"Bound terminal input was refused."),k()};u.on("error",()=>Y("pty_relay_unavailable")),u.on("close",k),u.on("message",(W,q)=>{if(f.signal.aborted)return;if(!M){Y("pty_not_ready");return}let ne=Array.isArray(W)?Buffer.concat(W):W instanceof ArrayBuffer?Buffer.from(W):W;if(ne.length===0)return;let ye=w.at(-1),le=q&&ye!==void 0&&"data"in ye&&ye.data.length+ne.length<=He;if(ne.length>He||P+ne.length>jo){Y("pty_input_backpressure");return}if(le)ye.data=Buffer.concat([ye.data,ne]);else if(q)w.push({data:Buffer.from(ne)});else try{let fe=JSON.parse(ne.toString("utf8"));if(fe&&fe.t==="close"&&Object.keys(fe).length===1){j=!0,k();return}if(!fe||fe.t!=="resize"||Object.keys(fe).length!==3||![fe.cols,fe.rows].every((ee)=>Number.isSafeInteger(ee)&&ee>=1&&ee<=_t))throw Error("invalid_control");w.push({cols:fe.cols,rows:fe.rows,bytes:ne.length})}catch{Y("invalid_pty_control");return}P+=ne.length,g()});function re(W){return Uo(JSON.stringify({...l.scope,version:1,sessionId:a.sessionId,operationId:a.operationId,job:{...W,output:[],pty:W.pty?{...W.pty,output:[]}:void 0}}))}function we(W){if(!W.ok)Fe(W.error);let q=W.job;if(W.generation!==l.scope.generation||q.jobId!==a.jobId||!q.pty||q.leaseExpiresAtMs>a.leaseExpiresAtMs||q.process&&q.process.executorLaunchId!==l.scope.executorLaunchId||q.process&&z&&(q.process.pid!==z.pid||q.process.processGroupId!==z.processGroupId)||q.state!=="starting"&&(q.environmentRevision!==l.environment.revision||q.environmentSnapshotId!==l.environment.snapshotId))Fe("pty_binding_changed");if(re(q),q.process)z??={...q.process};return q}async function Ie(W){l.assertCurrent();let q=await l.request(W,f.signal);if(l.assertCurrent(),f.signal.aborted)Fe("cancelled");let ne=we(q);if(ne.inputSequence!==N)Fe("job_input_sequence");if(!Ur(ne)&&ne.leaseExpiresAtMs<=Date.now())Fe("pty_binding_changed");return ne}function Z(W){if(l.assertCurrent(),f.signal.aborted||u.readyState!==bn.OPEN||u.bufferedAmount+Buffer.byteLength(W)>Bo)Fe("pty_output_backpressure");u.send(W)}function be(W){if(W.firstCursor>T+1)T=W.firstCursor-1;for(let q of W.pty.output){if(q.cursor<=T)continue;if(q.cursor!==T+1)Fe("pty_output_gap");let ne=Buffer.from(q.dataBase64,"base64");if(u.bufferedAmount+ne.length>Bo)return!1;Z(ne),T=q.cursor}if(T!==W.nextCursor)Fe("pty_output_gap");return!0}async function ke(W,q){let ne;try{await Promise.race([e.emit(W,q),new Promise((ye,le)=>{ne=setTimeout(()=>le(new r("pty_event_unavailable","Terminal metadata delivery timed out.")),2000)})])}finally{clearTimeout(ne)}}async function ae(){let W=AbortSignal.timeout(fn),q=l.request({jobId:a.jobId,action:"cancel",input:{}},W),ne,ye=new Promise((le,fe)=>{if(ne=()=>fe(new r("pty_cleanup_unconfirmed","Terminal cleanup acknowledgement was not observed within authority.")),W.addEventListener("abort",ne,{once:!0}),W.aborted)ne()});try{let le=await Promise.race([q,ye]);if(W.aborted)Fe("pty_cleanup_unconfirmed");return we(le)}finally{W.removeEventListener("abort",ne)}}try{await new Promise((le,fe)=>{let ee=setTimeout(()=>{k(),fe(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),me=()=>{clearTimeout(ee),fe(new r("cancelled","Terminal pairing was cancelled."))};if(f.signal.addEventListener("abort",me,{once:!0}),u.once("open",()=>{clearTimeout(ee),f.signal.removeEventListener("abort",me),le()}),f.signal.aborted)me()}),l.assertCurrent(),S=!0,C=await Ie({jobId:a.jobId,action:"start",input:{mode:"pty",cols:a.cols,rows:a.rows,leaseExpiresAtMs:a.leaseExpiresAtMs}});let W=Date.now()+5000;while(C.state==="starting"){if(Date.now()>=W)Fe("pty_not_ready");await new Promise((le)=>setTimeout(le,25)),C=await Ie({jobId:a.jobId,action:"inspect",input:{after:T}})}if(C.state!=="running"||C.inputSequence!==0||C.leaseExpiresAtMs<=Date.now())Fe("pty_not_ready");await ke("pty.ready",re(C)),M=!0,Z(JSON.stringify({t:"open",cols:C.pty.cols,rows:C.pty.rows,receipt:re(C)}));let q=!1,ne=0,ye=!1;while(!f.signal.aborted){let le=C.firstCursor>T+1,fe=be(C);if(Ur(C)){if(fe)break}else if(le)q=!0;else if(q&&fe&&Date.now()>=ne){q=!1,ne=Date.now()+1000;let{cols:me,rows:De}=C.pty;for(let Me of[{cols:me,rows:De>1?De-1:2},{cols:me,rows:De}]){if(Ur(C))break;let tr=++N;if(C=await Ie({jobId:a.jobId,action:"resize",input:{sequence:tr,...Me}}),C.inputSequence!==tr)Fe("job_input_sequence")}continue}let ee=Ur(C)||ye?void 0:w.shift();if(ee){P-=Lo(ee);let me=++N;try{C=await Ie("data"in ee?{jobId:a.jobId,action:"input",input:{sequence:me,dataBase64:ee.data.toString("base64")}}:{jobId:a.jobId,action:"resize",input:{sequence:me,cols:ee.cols,rows:ee.rows}})}catch(De){if(!(De instanceof r)||De.code!=="job_input_backpressure")throw De;N-=1,w.unshift(ee),P+=Lo(ee),ye=!0;continue}if(C.inputSequence!==me)Fe("job_input_sequence")}else if(await new Promise((me)=>{let De=setTimeout(me,ye||!fe?10:50);if(g=()=>{clearTimeout(De),me()},f.signal.aborted||!ye&&w.length)g()}),ye=!1,g=()=>{},!f.signal.aborted&&fe)try{C=await Ie({jobId:a.jobId,action:"inspect",input:{after:T}})}catch(me){if(!j||!(me instanceof r)||me.code!=="cancelled")throw me}}}catch(W){Q??=W}finally{if(M=!1,w.length=0,clearTimeout(O),e.signal.removeEventListener("abort",k),k(),S&&(!C||!Ur(C)))try{C=await ae()}catch{C=void 0}try{if(!C||!Ur(C)||C.pty?.cleanup!=="confirmed")Fe("pty_cleanup_unconfirmed");let W=re(C);if(u.readyState===bn.OPEN)await new Promise((q)=>{let ne=setTimeout(q,500);u.send(JSON.stringify({t:"exit",code:C.exitCode,receipt:W}),()=>{clearTimeout(ne),q()})});await ke("pty.stopped",W)}catch(W){Q??=W}u.terminate()}if(Q)throw Q;if(e.signal.aborted)Fe("cancelled");if(!C)Fe("pty_cleanup_unconfirmed");return{receipt:re(C)}}import{createHash as qi,randomUUID as Sn}from"crypto";import{spawnSync as $o}from"child_process";import{closeSync as Wo,constants as wn,fstatSync as Yi,fsyncSync as Xi,lstatSync as yt,mkdirSync as Zi,mkdtempSync as Ko,openSync as Fo,readFileSync as Qi,readdirSync as Go,realpathSync as Er,rmSync as yn,unlinkSync as ea}from"fs";import{createConnection as ra}from"net";import{dirname as ta,join as Dr,sep as vn}from"path";import{tmpdir as Jo}from"os";var rr=new Map,Sr=new Map;function hr(e,a){return qi("sha256").update(JSON.stringify([e,a])).digest("hex")}function zr(e){try{Zi(e,{mode:448})}catch(l){if(!(l instanceof Error&&("code"in l)&&l.code==="EEXIST"))throw l}let a=yt(e);if(!a.isDirectory()||a.isSymbolicLink()||!G(a)||Er(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function na(e){let a;try{a=yt(e)}catch(l){if(l instanceof Error&&"code"in l&&l.code==="ENOENT")return!1;throw l}return!a.isDirectory()||a.isSymbolicLink()||Go(e).length>0}function oa(e){if(process.platform==="win32")return fa();let a=e.map((l)=>{try{return Er(l)}catch{return l}});for(let l of[()=>fa(),()=>Er("/dev/shm"),()=>Er(Jo())]){let u;try{u=l()}catch{continue}if(!a.some((f)=>u===f||u.startsWith(f.endsWith(vn)?f:f+vn)))return u}throw new r("invalid_hands_workspace","A Session can't work in this computer's temporary folder itself; start it in a project folder inside it.")}function Lt(e){let a=hr(e.root,e.runId),l=e.previousRuntimeDirectories?.find((k)=>na(Dr(k,"jobs",a.slice(0,16))))??e.runtimeDirectory;zr(l);let u=Dr(l,"jobs");zr(u);let f=Dr(u,a.slice(0,16));if(e.maxScopes!==void 0){let k=Go(u);if(!Number.isSafeInteger(e.maxScopes)||e.maxScopes<1||k.length>e.maxScopes||!k.includes(a.slice(0,16))&&k.length>=e.maxScopes)throw new r("process_journal_capacity","Managed process receipt capacity is full; preserve uncertain jobs and reconcile their existing receipts before starting more work.")}zr(f);let g=Ko(Dr(oa(e.folders??[]),"reason-j-"));try{return zr(g),{journalDirectory:f,scopeId:a,launchDirectory:g,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${Sn()}`:Dr(g,"control.sock"),disposeSocket:()=>yn(g,{recursive:!0,force:!0})}}catch(k){throw yn(g,{recursive:!0,force:!0}),k}}var ia=60000,ca=5000;function ua(e){if(process.platform==="win32")return pa(e);let a=$o("ps",["-o","lstart=","-p",String(e)],{encoding:"utf8",timeout:2000,env:{...process.env,LC_ALL:"C",LANG:"C"}}),l=a.status===0?/^\w{3} (\w{3}) +(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/.exec(a.stdout.trim()):null,u=l?"JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(l[1]):-1;if(!l||u<0||u%3!==0)return null;let f=new Date(Number(l[6]),u/3,Number(l[2]),Number(l[3]),Number(l[4]),Number(l[5])).getTime();return Number.isFinite(f)?f:null}function pa(e){let a=$o(B("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().ToString('o')`],{encoding:"utf8",timeout:5000,windowsHide:!0,env:Tt()}),l=a.status===0?Date.parse(a.stdout.trim()):Number.NaN;return Number.isFinite(l)?l:null}function Vo(e,a={}){let l=Dr(e.journalDirectory,"owner.lock"),u;try{u=Fo(l,wn.O_RDONLY|wn.O_NOFOLLOW)}catch{return null}try{let f=Yi(u);if(!f.isFile()||f.nlink!==1||!G(f)||f.size>4096)return null;let g=null;try{g=JSON.parse(Qi(u,"utf8"))}catch{}let k;if(g===null){if((a.now??Date.now)()-f.mtimeMs<ia)return null;k={reason:"never_written",executorLaunchId:null}}else{let{version:P,scopeId:N,pid:T,createdAtMs:S,executorLaunchId:M}=g;if(P!==1||N!==e.scopeId||typeof M!=="string"||typeof T!=="number"||!Number.isSafeInteger(T)||T<1||T===process.pid||typeof S!=="number"||!Number.isSafeInteger(S))return null;if(!(a.exists??((C)=>{try{return process.kill(C,0),!0}catch(z){return!(z instanceof Error&&("code"in z)&&z.code==="ESRCH")}}))(T))k={reason:"owner_exited",executorLaunchId:M};else{let C=(a.startedAtMs??ua)(T);if(C===null||C<=S+ca)return null;k={reason:"pid_reused",executorLaunchId:M}}}let O=yt(l);if(O.dev!==f.dev||O.ino!==f.ino)return null;ea(l);let w=Fo(e.journalDirectory,wn.O_RDONLY);try{Xi(w)}finally{Wo(w)}return k}catch{return null}finally{Wo(u)}}function qo(e){let a={...e,workspace:e.workspace&&Object.freeze({...e.workspace}),previewAuthority:e.previewAuthority&&Object.freeze({...e.previewAuthority,owner:Object.freeze({...e.previewAuthority.owner}),deniedPorts:new Set(e.previewAuthority.deniedPorts)})},l=hr(a.root,a.runId);if(rr.has(l)||a.operationId!==void 0&&Sr.has(a.operationId))throw new r("hands_jobs_busy","The Session already has a live Hands job supervisor.");let u={binding:a,key:l,terminals:new Map};if(a.previewAuthority&&a.environment)u.previews=No({authority:a.previewAuthority,runId:a.runId,expiresAtMs:a.expiresAtMs,executorLaunchId:a.executorLaunchId,environment:a.environment,isCurrent:()=>rr.get(u.key)===u,identity:()=>{try{return $r(a)}catch{return null}},inspect:(f,g)=>{if(rr.get(u.key)!==u)throw new r("preview_unavailable","The Hands supervisor is no longer current.");return Yo(a,{jobId:f,action:"inspect",input:{after:0}},g)}});if(rr.set(l,u),a.operationId!==void 0)Sr.set(a.operationId,u);return()=>{if(rr.get(u.key)===u)rr.delete(u.key);if(a.operationId!==void 0&&Sr.get(a.operationId)===u)Sr.delete(a.operationId);u.previews?.dispose();for(let f of u.terminals.values())f.abort()}}var _a=5000,ma=20;async function Ba(e){let a=(f)=>{throw new r("hands_rebind_unavailable",f)};if(!ce(e.operationId)||!ce(e.runId)||!ce(e.fenceId)||!Ee(e.targetGeneration))a("Reason sent an invalid Hands rebind.");let l=Sr.get(e.operationId);if(!l||l.binding.root!==e.root)return a("No live Hands supervisor owns this operation.");for(let f=Date.now()+_a;;){if(e.signal?.aborted)a("The Hands rebind was cancelled.");if(Sr.get(e.operationId)!==l)a("The Hands supervisor is no longer current.");let g=null;try{g=$r(l.binding)}catch{}if(g&&g.generation===e.targetGeneration&&g.fenceId===e.fenceId)break;if(g&&g.generation>e.targetGeneration||Date.now()>=f)a("The executor did not adopt this take.");await new Promise((k)=>setTimeout(k,ma))}if(Sr.get(e.operationId)!==l||rr.get(l.key)!==l)a("The Hands supervisor is no longer current.");let u=hr(e.root,e.runId);if(l.key===u)return;if(rr.has(u))a("The taking run already has a live Hands job supervisor.");rr.delete(l.key);for(let f of l.terminals.values())f.abort();l.key=u,rr.set(u,l)}function Ze(e){let a="operationId"in e?Sr.get(e.operationId):rr.get(hr(e.root,e.runId)),l=a&&a.binding.root===e.root?a.binding:void 0;if(!l?.environment||l.expiresAtMs<=Date.now())throw new r("environment_unavailable","No live Hands supervisor owns this environment.");return l.environment.install(e.payload)}async function Fa(e){let a=rr.get(hr(e.root,e.runId));if(!a?.previews||!e.owner)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return a.previews.open(e.payload,e.owner,e.signal)}async function ja(e){let a=rr.get(hr(e.root,e.runId));if(!a?.previews||!e.owner||e.signal.aborted)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return a.previews.close(e.payload,e.owner)}async function Xr(e){let a=hr(e.root,e.runId),l=rr.get(a),u=l?.binding,f=u?.runId,g=u?.previewAuthority,k=u?.environment,O=e.owner&&{...e.owner},w=e.authority&&{...e.authority},P=()=>{throw new r("pty_binding_unavailable","No current authenticated Hands scope owns this terminal.")};if(!l||!u||!g||!k||!O||!w||!u.workspace)return P();let N=Object.freeze({...u.workspace}),T=$r(u),S=k.current(),M=()=>{if(rr.get(a)!==l||O.organization_id!==g.owner.organization_id||O.user_id!==g.owner.user_id||O.device_id!==g.owner.device_id||e.deviceId!==g.owner.device_id||e.rootId!==g.rootId||X(e.workspace)!==X(N))P();let C=$r(u),z=k.current();if(C.generation!==T.generation||C.fenceId!==T.fenceId||z.run_id!==f||z.device_id!==e.deviceId||z.root_id!==e.rootId||z.snapshot_id!==S.snapshot_id||z.revision!==S.revision||z.binding.target_generation!==T.generation||z.binding.target_fence_id!==T.fenceId||w.device_id!==e.deviceId||w.binding!==z.binding.kind||w.target_revision!==z.binding.target_revision||w.root_grant_revision!==z.binding.root_grant_revision||w.target_generation!==T.generation||w.target_fence_id!==T.fenceId)P()};if(M(),new URL(e.session.relayUrl).origin!==g.relayOrigin||l.terminals.has(e.session.jobId)||l.terminals.size>=4)return P();let j=new AbortController;l.terminals.set(e.session.jobId,j);try{return await Mo({session:{...e.session,leaseExpiresAtMs:Math.min(e.session.leaseExpiresAtMs,T.expiresAtMs,Date.parse(S.expires_at))},signal:AbortSignal.any([e.signal,j.signal]),emit:e.emit,binding:{assertCurrent:M,environment:{revision:S.revision,snapshotId:S.snapshot_id},scope:{runId:e.runId,deviceId:e.deviceId,rootId:e.rootId,workspace:N,binding:S.binding.kind,targetRevision:S.binding.target_revision,rootGrantRevision:S.binding.root_grant_revision,generation:T.generation,fenceId:T.fenceId,executorLaunchId:T.executorLaunchId},request:(C,z)=>ti(T,xi(JSON.stringify({...C,type:"job",version:2,generation:T.generation,id:Sn()})),z)}})}finally{if(l.terminals.get(e.session.jobId)===j)l.terminals.delete(e.session.jobId)}}async function Ha(e){if(nt(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let a=rr.get(hr(e.root,e.runId))?.binding;if(!a||a.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","No live Hands supervisor owns this Session and root.");return Yo(a,e.payload,e.signal)}var ha=1e4,ga=20,ba=gt/2,wa=zt/2,ya=(e)=>e.output.reduce((a,l)=>a+l.text.length,0);async function Yo(e,a,l){if(Object.keys(a).some((P)=>!["jobId","action","input","waitForExitMs"].includes(P)))throw new r("invalid_payload","Unexpected job control field.");let{waitForExitMs:u,...f}=a;if(u!==void 0&&(f.action!=="start"||typeof f.input!=="object"||f.input===null||!("script"in f.input)||typeof u!=="number"||!Number.isSafeInteger(u)||u<1||u>ha))throw new r("invalid_payload","Only a script start may wait for its job, within its bound.");let g=(P)=>{let N=$r(e);return ti(N,xi(JSON.stringify({...P,type:"job",version:2,generation:N.generation,id:Sn()})),l)},k=await g(f);if(u===void 0)return k;let O=Date.now()+u,w=k;while(w.ok&&["starting","running"].includes(w.job.state)&&w.job.output.length<ba&&ya(w.job)<wa&&!l.aborted&&Date.now()<O){if(await new Promise((P)=>setTimeout(P,Math.min(ga,O-Date.now()))),l.aborted)break;try{let P=await g({jobId:f.jobId,action:"inspect",input:{after:0}});if(!P.ok)break;w=P}catch{break}}return w}function $r(e){if(e.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","Hands authority expired.");let a=e.readIdentity?e.readIdentity():e;if(!a||!Ee(a.generation)||!ce(a.fenceId)||a.generation<e.generation||a.generation===e.generation&&a.fenceId!==e.fenceId)throw new r("hands_jobs_unavailable","The live Hands fencing identity could not be verified.");return e.generation=a.generation,e.fenceId=a.fenceId,{...e}}function ti(e,a,l){if(l.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((u,f)=>{let g=ra(e.socketPath),k="",O=!1,w,P=(T,S)=>{if(O)return;if(O=!0,clearTimeout(w),l.removeEventListener("abort",N),g.destroy(),T)f(T);else u(S)},N=()=>P(new r("cancelled","Job control waiter cancelled; inspect before retrying mutations."));l.addEventListener("abort",N,{once:!0}),g.setEncoding("utf8"),w=setTimeout(()=>P(new r("hands_job_result_unknown","Job control timed out; inspect before retrying mutations.")),Math.min(1e4,Math.max(1,e.expiresAtMs-Date.now()))),g.on("error",()=>P(new r("hands_job_result_unknown","Hands job control connection failed."))),g.once("connect",()=>g.write(JSON.stringify({version:1,scopeId:e.scopeId,fenceId:e.fenceId,executorLaunchId:e.executorLaunchId,request:a})+`
|
|
2
|
+
import{mt,gr,Se}from"./vm-hands-entry-lite-pxtycfdv.js";import{st,Et,Oe,kt,Ge,Cr,Zt,Ne,X,te,Ui}from"./vm-hands-entry-lite-9g52kxyj.js";import{kn,vr}from"./vm-hands-entry-lite-q9s1e2y1.js";import{ic,F,zt,gt,qt,He,Wt,jo,_t,fn,rt,Ee,ce,nt,xi,Ci,Uo}from"./vm-hands-entry-lite-jpvmkce5.js";import{xt,Ke,at,Le,At,xe,pe}from"./vm-hands-entry-lite-71ebge0c.js";import{tn,hi,pr,Re,U,H,R,Ro}from"./vm-hands-entry-lite-v4hr9x9h.js";import{Bt,pi,Ao,tc,je,Po}from"./vm-hands-entry-lite-weqam12f.js";import{ue}from"./vm-hands-entry-lite-q9djb28r.js";import{da}from"./vm-hands-entry-lite-z0ht62s4.js";import{v,Mt,en,dr,Ya,pt,ht}from"./vm-hands-entry-lite-0wb1n769.js";import{b,m,y}from"./vm-hands-entry-lite-yvws5zpx.js";import{L}from"./vm-hands-entry-lite-ptycjmkc.js";import{On}from"./vm-hands-entry-lite-xvccy3z4.js";import{s,Lc,$c,Ve,Bc}from"./vm-hands-entry-lite-zawytz09.js";import{he,sa,aa,zc,I,t,V,Mr,o,_,d,n,h,A,$e,c,i}from"./vm-hands-entry-lite-k5ytpgzz.js";import{la}from"./vm-hands-entry-lite-qf990rxw.js";import{Wc,Xe,fa,B,Tt,Be,G}from"./vm-hands-entry-lite-8xv6c0rm.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{readFileSync as Oo,realpathSync as go,statSync as Hi}from"fs";import{homedir as Ni}from"os";import{dirname as Li,isAbsolute as Bi,join as wt,sep as ji}from"path";var Di=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function a(f){return e[f]??null}let l={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},u={nan:"NaN"};return(f)=>{switch(f.code){case"invalid_type":{let g=u[f.expected]??f.expected,k=zc(f.input),O=u[k]??k;return`Invalid input: expected ${g}, received ${O}`}case"invalid_value":if(f.values.length===1)return`Invalid input: expected ${aa(f.values[0])}`;return`Invalid option: expected one of ${sa(f.values,"|")}`;case"too_big":{let g=f.inclusive?"<=":"<",k=a(f.origin);if(k)return`Too big: expected ${f.origin??"value"} to have ${g}${f.maximum.toString()} ${k.unit??"elements"}`;return`Too big: expected ${f.origin??"value"} to be ${g}${f.maximum.toString()}`}case"too_small":{let g=f.inclusive?">=":">",k=a(f.origin);if(k)return`Too small: expected ${f.origin} to have ${g}${f.minimum.toString()} ${k.unit}`;return`Too small: expected ${f.origin} to be ${g}${f.minimum.toString()}`}case"invalid_format":{let g=f;if(g.format==="starts_with")return`Invalid string: must start with "${g.prefix}"`;if(g.format==="ends_with")return`Invalid string: must end with "${g.suffix}"`;if(g.format==="includes")return`Invalid string: must include "${g.includes}"`;if(g.format==="regex")return`Invalid string: must match pattern ${g.pattern}`;return`Invalid ${l[g.format]??f.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${f.divisor}`;case"unrecognized_keys":return`Unrecognized key${f.keys.length>1?"s":""}: ${sa(f.keys,", ")}`;case"invalid_key":return`Invalid key in ${f.origin}`;case"invalid_union":if(f.options&&Array.isArray(f.options)&&f.options.length>0)return`Invalid discriminator value. Expected ${f.options.map((k)=>`'${k}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${f.origin}`;default:return"Invalid input"}}};function mn(){return{localeError:Di()}}he(mn());var Zn="--proxy",Qn="--proxy-ca-file",Mi=262144;class K extends Error{}function gn(e){let a;try{a=new URL(e)}catch{throw new K("The proxy must be a URL like https://proxy.example.com:3128.")}if(a.protocol!=="https:"&&a.protocol!=="http:")throw new K("The proxy URL must use the https or http scheme.");if(!a.hostname)throw new K("The proxy URL must name a host.");if(a.port!==""&&Number(a.port)<1)throw new K("The proxy URL must use a port between 1 and 65535.");if(a.pathname!==""&&a.pathname!=="/"||a.search||a.hash)throw new K("The proxy URL must not carry a path, query, or fragment.");return a.toString()}function La(e){let a=new URL(e.url),l=a.port||(a.protocol==="https:"?"443":"80");return`${a.hostname}:${l}`}function Wi(e={}){let a=e.home??Ni(),l=e.statePath??mt();return[Li(l),wt(a,".ssh"),wt(a,".aws"),wt(a,".gnupg"),wt(a,".kube"),wt(a,"Library","Keychains")]}function Fi(e,a){return a===e||a.startsWith(e+ji)}function zi(e,a={}){if(!Bi(e))throw new K("The proxy CA file must be an absolute path.");let l,u,f;try{l=go(e);let O=Hi(l);u=O.size,f=O.isFile()}catch{throw new K("The proxy CA file does not exist or is not readable.")}if(!f)throw new K("The proxy CA file must be a regular file.");if(u>Mi)throw new K("The proxy CA file must be 256 KB or smaller.");let g=Wi(a).flatMap((O)=>{try{let w=go(O);return w===O?[O]:[O,w]}catch{return[O]}});for(let O of[e,l])if(g.some((w)=>Fi(w,O)))throw new K("The proxy CA file must not live inside a credential directory.");let k;try{k=Oo(l,"utf8")}catch{throw new K("The proxy CA file is not readable.")}if(!k.includes("-----BEGIN CERTIFICATE-----"))throw new K("The proxy CA file must be a PEM certificate bundle.");return l}function $a(e,a={}){if(!e.proxyUrl)throw new K("A proxy URL is required.");let l=gn(e.proxyUrl),u=e.caFile===void 0?void 0:zi(e.caFile,a);return{version:gr,url:l,...u===void 0?{}:{caFile:u}}}function oe(e,a=fetch){if(!e)return a;let l,u=!1;return(g,k)=>{if(!u){if(e.caFile)try{l=Oo(e.caFile,"utf8")}catch{throw new K(`The configured proxy CA file is not readable: ${e.caFile}`)}u=!0}let O={...k,proxy:e.url,...l===void 0?{}:{tls:{ca:l}}};return a(g,O)}}import{createHash as $i}from"crypto";import{isAbsolute as To,join as Do,relative as Co,resolve as jt,sep as Ho}from"path";var Nt=t().min(1).refine(To,"absolute path required"),Io=h({version:i(1),apiOrigin:Mr(),channel:c(["staging","production"]),stateDirectory:Nt,workspaceRoot:Nt,lifetime:c(["persistent","ephemeral"]),executionMode:c(["confined","host"]).default("confined"),name:t().min(1).max(160).default("Reason headless worker"),slots:o().int().min(1).max(4).default(1),shutdownGraceMs:o().int().min(0).max(300000).default(30000),proxy:h({version:i(gr),url:t().refine((e)=>{try{return gn(e)===e}catch{return!1}},"invalid proxy URL"),caFile:Nt.optional()}).optional(),userChrome:_().optional(),cloudSessions:i(!0).optional(),localLogins:_().optional(),folders:d(Nt).min(1).max(31).optional()}),Ki=/^https:\/\/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.trycloudflare\.com$/,x=A("channel",[Io,Io.extend({channel:i("local-qa"),apiOrigin:t()})]).superRefine((e,a)=>{if(e.channel==="local-qa"){if(!Ki.test(e.apiOrigin))a.addIssue({code:"custom",message:"local QA worker requires an exact HTTPS trycloudflare.com quick-tunnel origin"})}else{let u=new URL(e.apiOrigin);if(u.origin!==e.apiOrigin||u.username||u.password||u.protocol!=="https:"&&!(u.protocol==="http:"&&vr(u.origin))||!vr(u.origin)&&!kn(e.channel,u.origin))a.addIssue({code:"custom",message:"API origin must match channel (or loopback)"})}if(!ge(e.workspaceRoot,e.stateDirectory))a.addIssue({code:"custom",message:"state and workspace must be disjoint"});let l=e.folders??[];if(new Set([e.workspaceRoot,...l]).size!==l.length+1||l.some((u)=>!ge(u,e.stateDirectory)))a.addIssue({code:"custom",message:"folders must be distinct and disjoint from state"})});function p(e){return Do(e.stateDirectory,`headless-${e.channel}`)}function _o(e,a={},l={}){let u=e.executionMode==="host"?"unsandboxed":"sandboxed";return{worker:Object.freeze({executionMode:u,runtimeDirectory:p(e),handsSlots:e.slots,...l.ownComputer?{ownComputer:!0}:{},readiness:Object.freeze({...a}),...l.persistentTerminals?{persistentTerminals:!0}:{},...l.probing?.length?{probing:Object.freeze([...l.probing])}:{},...l.displayVideo?{displayVideo:!0}:{},...l.handsBrowser&&a["hands.connect"]===!0?{handsBrowser:!0}:{},...l.githubSignedIn===void 0?{}:{githubSignedIn:l.githubSignedIn},...e.userChrome!==!1&&l.userChrome?{userChrome:l.userChrome}:{},...e.cloudSessions&&a["automation.call.v1"]===!0?{cloudSessions:!0}:{}}),proxy:e.proxy??null}}function ge(e,a){if(se(a,e))return!1;return!se(e,a)||L(Do(Ho,Co(jt(e),jt(a))))}function se(e,a){let l=Co(jt(e),jt(a));return l===""||l!==".."&&!l.startsWith(`..${Ho}`)&&!To(l)}function D(e){let{proxy:a,userChrome:l,cloudSessions:u,localLogins:f,folders:g,...k}=e;return $i("sha256").update(JSON.stringify(k)).digest("hex")}var Gi=4,Ji=[2375,2376,9222,9229];function ei(e){let a=new Set(Ji);for(let l of e){let u=new URL(l);a.add(Number(u.port||(["https:","wss:"].includes(u.protocol)?443:80)))}return a}function kr(){throw new r("preview_unavailable","The live Hands preview binding is unavailable or stale.")}var Vi=60000;function No(e){let a=new AbortController,l=new Map,u=(w)=>JSON.stringify([w.jobId,w.port]);function f(w){let P=e.authority.owner;if(a.signal.aborted||!e.isCurrent()||e.expiresAtMs<=Date.now()||w.organization_id!==P.organization_id||w.user_id!==P.user_id||w.device_id!==P.device_id)kr()}function g(w){let P;try{P=e.environment.current()}catch{return null}return P.binding.target_generation===w.generation&&P.binding.target_fence_id===w.fenceId&&P.run_id===e.runId&&P.device_id===e.authority.owner.device_id&&P.root_id===e.authority.rootId?P:null}async function k(w,P,N){let T=await O(w,P,N);if(T!=="moved")return T;let S=await O(w,P,N);return S==="moved"?null:S}async function O(w,P,N){try{f(e.authority.owner);let T=e.identity();if(!T||N.aborted||w.expiresAtMs<=Date.now()||w.expiresAtMs>e.expiresAtMs)return null;let S=P.opened,M=S!==void 0&&T.generation>S.generation,j=g(T);if(M){if(j){if(j.revision<=S.revision||w.expiresAtMs>Date.parse(j.expires_at)||j.binding.target_revision!==S.attachmentRevision||j.binding.root_grant_revision!==S.grantRevision)return null;P.recoveringSinceMs=void 0}else if(Date.now()-(P.recoveringSinceMs??=Date.now())>Vi)return null}else if(!j||w.expiresAtMs>Date.parse(j.expires_at)||S&&(T.generation!==S.generation||T.fenceId!==S.fenceId))return null;let C=await e.inspect(w.jobId,N),z=e.identity(),Q=z&&g(z);f(e.authority.owner);let Y=j&&{generation:T.generation,fenceId:T.fenceId,snapshotId:j.snapshot_id,revision:j.revision,attachmentRevision:j.binding.target_revision,grantRevision:j.binding.root_grant_revision},re=M?S:Y;if(N.aborted||!z)return null;if(z.generation!==T.generation||z.fenceId!==T.fenceId||Q?.snapshot_id!==j?.snapshot_id||Q?.revision!==j?.revision)return"moved";let we=C.ok&&C.job.environmentSnapshotId!==void 0&&C.job.environmentRevision!==void 0?{snapshotId:C.job.environmentSnapshotId,revision:C.job.environmentRevision}:null;if(!C.ok||C.generation!==T.generation||!re||!we)return null;if((we.snapshotId!==re.snapshotId||we.revision!==re.revision)&&(M||!e.environment.carried(we.snapshotId,we.revision)))return null;if(!S&&T.generation===w.generation&&T.fenceId===w.fenceId)P.opened={...re,...we};return{executorLaunchId:e.executorLaunchId,job:C.job,binding:{organizationId:e.authority.owner.organization_id,userId:e.authority.owner.user_id,deviceId:e.authority.owner.device_id,rootId:e.authority.rootId,runId:e.runId,attachmentRevision:re.attachmentRevision,grantRevision:re.grantRevision,generation:re.generation,fenceId:re.fenceId,jobId:C.job.jobId,port:w.port,expiresAtMs:w.expiresAtMs}}}catch{return null}}return{async open(w,P,N){f(P);let{binding:T,deviceRelayUrl:S}=dr(w);if(N.aborted||T.expiresAtMs<=Date.now()||T.expiresAtMs>Date.now()+v.lifetimeMs||new URL(S).origin!==e.authority.relayOrigin)kr();let M=u(T),j=l.get(M);if(j){if(!Mt(j.binding,T)||j.relay!==S)kr();if(await j.opened,!await en(()=>j.port.check())||N.aborted||j.abort.signal.aborted)kr();return{opened:!0,binding:T}}if(l.size>=Gi)kr();let C=new AbortController,z={},Q=ht({binding:T,deniedPorts:e.authority.deniedPorts,readCurrentJob:()=>k(T,z,C.signal)}),Y=()=>C.abort();if(N.addEventListener("abort",Y,{once:!0}),a.signal.addEventListener("abort",Y,{once:!0}),N.aborted||a.signal.aborted)Y();let re=pt({binding:T,deviceRelayUrl:S,port:Q,signal:C.signal}),we={binding:T,relay:S,abort:C,port:Q,opened:re};l.set(M,we);let Ie=()=>{if(N.removeEventListener("abort",Y),a.signal.removeEventListener("abort",Y),l.get(M)===we)l.delete(M)};try{if((await re).closed.then(Ie),N.removeEventListener("abort",Y),f(P),C.signal.aborted||!await en(()=>Q.check()))kr();return{opened:!0,binding:T}}catch{C.abort(),Ie(),kr()}},async close(w,P){f(P);let{binding:N}=Ya(w),T=l.get(u(N));if(!T||!Mt(T.binding,N))kr();return T.abort.abort(),await T.opened.then((S)=>S.closed,()=>{return}),{closed:!0,binding:N}},dispose(){a.abort();for(let w of l.values())w.abort.abort();l.clear()}}}import{WebSocket as bn}from"ws";var Lo=(e)=>("data"in e)?e.data.length:e.bytes,Bo=2*Wt;function Fe(e){throw new r(e,"The bound Hands terminal is unavailable or its outcome is unconfirmed.")}var Ur=(e)=>!["starting","running"].includes(e.state);function Ma(e,a,l=Date.now()){let u=["relay_url","session_id","expires_at","cols","rows","pty","workspace"];if(Object.keys(e).length!==u.length||Object.keys(e).some((P)=>!u.includes(P))||!rt(a)||!rt(e.session_id)||typeof e.expires_at!=="string"||typeof e.relay_url!=="string"||e.relay_url.length>4096||![e.cols,e.rows].every((P)=>Number.isSafeInteger(P)&&Number(P)>=1&&Number(P)<=_t))Fe("invalid_pty_request");let f=e.pty;if(!f||typeof f!=="object"||Array.isArray(f))Fe("invalid_pty_request");let g=f;if(Object.keys(g).length!==2||g.version!==1||!nt(g.jobId))Fe("invalid_pty_request");let k;try{k=new URL(e.relay_url)}catch{return Fe("invalid_pty_request")}if(!["ws:","wss:"].includes(k.protocol)||k.username||k.password||k.hash||k.protocol==="ws:"&&!["127.0.0.1","[::1]","localhost"].includes(k.hostname))Fe("invalid_pty_request");let O=Date.parse(e.expires_at);if(!Number.isSafeInteger(O)||O<=l)Fe("invalid_pty_request");return{workspace:te(e.workspace)??Fe("invalid_pty_request"),session:{jobId:g.jobId,sessionId:e.session_id,operationId:a,relayUrl:k.href,cols:Number(e.cols),rows:Number(e.rows),leaseExpiresAtMs:Math.min(O,l+43200000)}}}async function Mo(e){let{session:a,binding:l}=e;if(l.assertCurrent(),e.signal.aborted||Date.now()>=a.leaseExpiresAtMs)Fe("cancelled");let u=new bn(a.relayUrl,{followRedirects:!1,perMessageDeflate:!1,maxPayload:He}),f=new AbortController,g=()=>{},k=()=>{f.abort(),g()};e.signal.addEventListener("abort",k,{once:!0});let O=setTimeout(k,Math.max(1,a.leaseExpiresAtMs-Date.now())),w=[],P=0,N=0,T=0,S=!1,M=!1,j=!1,C,z,Q,Y=(W)=>{Q=new r(W,"Bound terminal input was refused."),k()};u.on("error",()=>Y("pty_relay_unavailable")),u.on("close",k),u.on("message",(W,q)=>{if(f.signal.aborted)return;if(!M){Y("pty_not_ready");return}let ne=Array.isArray(W)?Buffer.concat(W):W instanceof ArrayBuffer?Buffer.from(W):W;if(ne.length===0)return;let ye=w.at(-1),le=q&&ye!==void 0&&"data"in ye&&ye.data.length+ne.length<=He;if(ne.length>He||P+ne.length>jo){Y("pty_input_backpressure");return}if(le)ye.data=Buffer.concat([ye.data,ne]);else if(q)w.push({data:Buffer.from(ne)});else try{let fe=JSON.parse(ne.toString("utf8"));if(fe&&fe.t==="close"&&Object.keys(fe).length===1){j=!0,k();return}if(!fe||fe.t!=="resize"||Object.keys(fe).length!==3||![fe.cols,fe.rows].every((ee)=>Number.isSafeInteger(ee)&&ee>=1&&ee<=_t))throw Error("invalid_control");w.push({cols:fe.cols,rows:fe.rows,bytes:ne.length})}catch{Y("invalid_pty_control");return}P+=ne.length,g()});function re(W){return Uo(JSON.stringify({...l.scope,version:1,sessionId:a.sessionId,operationId:a.operationId,job:{...W,output:[],pty:W.pty?{...W.pty,output:[]}:void 0}}))}function we(W){if(!W.ok)Fe(W.error);let q=W.job;if(W.generation!==l.scope.generation||q.jobId!==a.jobId||!q.pty||q.leaseExpiresAtMs>a.leaseExpiresAtMs||q.process&&q.process.executorLaunchId!==l.scope.executorLaunchId||q.process&&z&&(q.process.pid!==z.pid||q.process.processGroupId!==z.processGroupId)||q.state!=="starting"&&(q.environmentRevision!==l.environment.revision||q.environmentSnapshotId!==l.environment.snapshotId))Fe("pty_binding_changed");if(re(q),q.process)z??={...q.process};return q}async function Ie(W){l.assertCurrent();let q=await l.request(W,f.signal);if(l.assertCurrent(),f.signal.aborted)Fe("cancelled");let ne=we(q);if(ne.inputSequence!==N)Fe("job_input_sequence");if(!Ur(ne)&&ne.leaseExpiresAtMs<=Date.now())Fe("pty_binding_changed");return ne}function Z(W){if(l.assertCurrent(),f.signal.aborted||u.readyState!==bn.OPEN||u.bufferedAmount+Buffer.byteLength(W)>Bo)Fe("pty_output_backpressure");u.send(W)}function be(W){if(W.firstCursor>T+1)T=W.firstCursor-1;for(let q of W.pty.output){if(q.cursor<=T)continue;if(q.cursor!==T+1)Fe("pty_output_gap");let ne=Buffer.from(q.dataBase64,"base64");if(u.bufferedAmount+ne.length>Bo)return!1;Z(ne),T=q.cursor}if(T!==W.nextCursor)Fe("pty_output_gap");return!0}async function ke(W,q){let ne;try{await Promise.race([e.emit(W,q),new Promise((ye,le)=>{ne=setTimeout(()=>le(new r("pty_event_unavailable","Terminal metadata delivery timed out.")),2000)})])}finally{clearTimeout(ne)}}async function ae(){let W=AbortSignal.timeout(fn),q=l.request({jobId:a.jobId,action:"cancel",input:{}},W),ne,ye=new Promise((le,fe)=>{if(ne=()=>fe(new r("pty_cleanup_unconfirmed","Terminal cleanup acknowledgement was not observed within authority.")),W.addEventListener("abort",ne,{once:!0}),W.aborted)ne()});try{let le=await Promise.race([q,ye]);if(W.aborted)Fe("pty_cleanup_unconfirmed");return we(le)}finally{W.removeEventListener("abort",ne)}}try{await new Promise((le,fe)=>{let ee=setTimeout(()=>{k(),fe(new r("pty_relay_unavailable","Terminal pairing timed out."))},5000),me=()=>{clearTimeout(ee),fe(new r("cancelled","Terminal pairing was cancelled."))};if(f.signal.addEventListener("abort",me,{once:!0}),u.once("open",()=>{clearTimeout(ee),f.signal.removeEventListener("abort",me),le()}),f.signal.aborted)me()}),l.assertCurrent(),S=!0,C=await Ie({jobId:a.jobId,action:"start",input:{mode:"pty",cols:a.cols,rows:a.rows,leaseExpiresAtMs:a.leaseExpiresAtMs}});let W=Date.now()+5000;while(C.state==="starting"){if(Date.now()>=W)Fe("pty_not_ready");await new Promise((le)=>setTimeout(le,25)),C=await Ie({jobId:a.jobId,action:"inspect",input:{after:T}})}if(C.state!=="running"||C.inputSequence!==0||C.leaseExpiresAtMs<=Date.now())Fe("pty_not_ready");await ke("pty.ready",re(C)),M=!0,Z(JSON.stringify({t:"open",cols:C.pty.cols,rows:C.pty.rows,receipt:re(C)}));let q=!1,ne=0,ye=!1;while(!f.signal.aborted){let le=C.firstCursor>T+1,fe=be(C);if(Ur(C)){if(fe)break}else if(le)q=!0;else if(q&&fe&&Date.now()>=ne){q=!1,ne=Date.now()+1000;let{cols:me,rows:De}=C.pty;for(let Me of[{cols:me,rows:De>1?De-1:2},{cols:me,rows:De}]){if(Ur(C))break;let tr=++N;if(C=await Ie({jobId:a.jobId,action:"resize",input:{sequence:tr,...Me}}),C.inputSequence!==tr)Fe("job_input_sequence")}continue}let ee=Ur(C)||ye?void 0:w.shift();if(ee){P-=Lo(ee);let me=++N;try{C=await Ie("data"in ee?{jobId:a.jobId,action:"input",input:{sequence:me,dataBase64:ee.data.toString("base64")}}:{jobId:a.jobId,action:"resize",input:{sequence:me,cols:ee.cols,rows:ee.rows}})}catch(De){if(!(De instanceof r)||De.code!=="job_input_backpressure")throw De;N-=1,w.unshift(ee),P+=Lo(ee),ye=!0;continue}if(C.inputSequence!==me)Fe("job_input_sequence")}else if(await new Promise((me)=>{let De=setTimeout(me,ye||!fe?10:50);if(g=()=>{clearTimeout(De),me()},f.signal.aborted||!ye&&w.length)g()}),ye=!1,g=()=>{},!f.signal.aborted&&fe)try{C=await Ie({jobId:a.jobId,action:"inspect",input:{after:T}})}catch(me){if(!j||!(me instanceof r)||me.code!=="cancelled")throw me}}}catch(W){Q??=W}finally{if(M=!1,w.length=0,clearTimeout(O),e.signal.removeEventListener("abort",k),k(),S&&(!C||!Ur(C)))try{C=await ae()}catch{C=void 0}try{if(!C||!Ur(C)||C.pty?.cleanup!=="confirmed")Fe("pty_cleanup_unconfirmed");let W=re(C);if(u.readyState===bn.OPEN)await new Promise((q)=>{let ne=setTimeout(q,500);u.send(JSON.stringify({t:"exit",code:C.exitCode,receipt:W}),()=>{clearTimeout(ne),q()})});await ke("pty.stopped",W)}catch(W){Q??=W}u.terminate()}if(Q)throw Q;if(e.signal.aborted)Fe("cancelled");if(!C)Fe("pty_cleanup_unconfirmed");return{receipt:re(C)}}import{createHash as qi,randomUUID as Sn}from"crypto";import{spawnSync as $o}from"child_process";import{closeSync as Wo,constants as wn,fstatSync as Yi,fsyncSync as Xi,lstatSync as yt,mkdirSync as Zi,mkdtempSync as Ko,openSync as Fo,readFileSync as Qi,readdirSync as Go,realpathSync as Er,rmSync as yn,unlinkSync as ea}from"fs";import{createConnection as ra}from"net";import{dirname as ta,join as Dr,sep as vn}from"path";import{tmpdir as Jo}from"os";var rr=new Map,Sr=new Map;function hr(e,a){return qi("sha256").update(JSON.stringify([e,a])).digest("hex")}function zr(e){try{Zi(e,{mode:448})}catch(l){if(!(l instanceof Error&&("code"in l)&&l.code==="EEXIST"))throw l}let a=yt(e);if(!a.isDirectory()||a.isSymbolicLink()||!G(a)||Er(e)!==e)throw new r("hands_jobs_unavailable","Hands job state must be a private canonical directory.")}function na(e){let a;try{a=yt(e)}catch(l){if(l instanceof Error&&"code"in l&&l.code==="ENOENT")return!1;throw l}return!a.isDirectory()||a.isSymbolicLink()||Go(e).length>0}function oa(e){if(process.platform==="win32")return fa();let a=e.map((l)=>{try{return Er(l)}catch{return l}});for(let l of[()=>fa(),()=>Er("/dev/shm"),()=>Er(Jo())]){let u;try{u=l()}catch{continue}if(!a.some((f)=>u===f||u.startsWith(f.endsWith(vn)?f:f+vn)))return u}throw new r("invalid_hands_workspace","A Session can't work in this computer's temporary folder itself; start it in a project folder inside it.")}function Lt(e){let a=hr(e.root,e.runId),l=e.previousRuntimeDirectories?.find((k)=>na(Dr(k,"jobs",a.slice(0,16))))??e.runtimeDirectory;zr(l);let u=Dr(l,"jobs");zr(u);let f=Dr(u,a.slice(0,16));if(e.maxScopes!==void 0){let k=Go(u);if(!Number.isSafeInteger(e.maxScopes)||e.maxScopes<1||k.length>e.maxScopes||!k.includes(a.slice(0,16))&&k.length>=e.maxScopes)throw new r("process_journal_capacity","Managed process receipt capacity is full; preserve uncertain jobs and reconcile their existing receipts before starting more work.")}zr(f);let g=Ko(Dr(oa(e.folders??[]),"reason-j-"));try{return zr(g),{journalDirectory:f,scopeId:a,launchDirectory:g,socketPath:process.platform==="win32"?`\\\\.\\pipe\\reason-jobs-${Sn()}`:Dr(g,"control.sock"),disposeSocket:()=>yn(g,{recursive:!0,force:!0})}}catch(k){throw yn(g,{recursive:!0,force:!0}),k}}var ia=60000,ca=5000;function ua(e){if(process.platform==="win32")return pa(e);let a=$o("ps",["-o","lstart=","-p",String(e)],{encoding:"utf8",timeout:2000,env:{...process.env,LC_ALL:"C",LANG:"C"}}),l=a.status===0?/^\w{3} (\w{3}) +(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/.exec(a.stdout.trim()):null,u=l?"JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(l[1]):-1;if(!l||u<0||u%3!==0)return null;let f=new Date(Number(l[6]),u/3,Number(l[2]),Number(l[3]),Number(l[4]),Number(l[5])).getTime();return Number.isFinite(f)?f:null}function pa(e){let a=$o(B("powershell"),["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e}).StartTime.ToUniversalTime().ToString('o')`],{encoding:"utf8",timeout:5000,windowsHide:!0,env:Tt()}),l=a.status===0?Date.parse(a.stdout.trim()):Number.NaN;return Number.isFinite(l)?l:null}function Vo(e,a={}){let l=Dr(e.journalDirectory,"owner.lock"),u;try{u=Fo(l,wn.O_RDONLY|wn.O_NOFOLLOW)}catch{return null}try{let f=Yi(u);if(!f.isFile()||f.nlink!==1||!G(f)||f.size>4096)return null;let g=null;try{g=JSON.parse(Qi(u,"utf8"))}catch{}let k;if(g===null){if((a.now??Date.now)()-f.mtimeMs<ia)return null;k={reason:"never_written",executorLaunchId:null}}else{let{version:P,scopeId:N,pid:T,createdAtMs:S,executorLaunchId:M}=g;if(P!==1||N!==e.scopeId||typeof M!=="string"||typeof T!=="number"||!Number.isSafeInteger(T)||T<1||T===process.pid||typeof S!=="number"||!Number.isSafeInteger(S))return null;if(!(a.exists??((C)=>{try{return process.kill(C,0),!0}catch(z){return!(z instanceof Error&&("code"in z)&&z.code==="ESRCH")}}))(T))k={reason:"owner_exited",executorLaunchId:M};else{let C=(a.startedAtMs??ua)(T);if(C===null||C<=S+ca)return null;k={reason:"pid_reused",executorLaunchId:M}}}let O=yt(l);if(O.dev!==f.dev||O.ino!==f.ino)return null;ea(l);let w=Fo(e.journalDirectory,wn.O_RDONLY);try{Xi(w)}finally{Wo(w)}return k}catch{return null}finally{Wo(u)}}function qo(e){let a={...e,workspace:e.workspace&&Object.freeze({...e.workspace}),previewAuthority:e.previewAuthority&&Object.freeze({...e.previewAuthority,owner:Object.freeze({...e.previewAuthority.owner}),deniedPorts:new Set(e.previewAuthority.deniedPorts)})},l=hr(a.root,a.runId);if(rr.has(l)||a.operationId!==void 0&&Sr.has(a.operationId))throw new r("hands_jobs_busy","The Session already has a live Hands job supervisor.");let u={binding:a,key:l,terminals:new Map};if(a.previewAuthority&&a.environment)u.previews=No({authority:a.previewAuthority,runId:a.runId,expiresAtMs:a.expiresAtMs,executorLaunchId:a.executorLaunchId,environment:a.environment,isCurrent:()=>rr.get(u.key)===u,identity:()=>{try{return $r(a)}catch{return null}},inspect:(f,g)=>{if(rr.get(u.key)!==u)throw new r("preview_unavailable","The Hands supervisor is no longer current.");return Yo(a,{jobId:f,action:"inspect",input:{after:0}},g)}});if(rr.set(l,u),a.operationId!==void 0)Sr.set(a.operationId,u);return()=>{if(rr.get(u.key)===u)rr.delete(u.key);if(a.operationId!==void 0&&Sr.get(a.operationId)===u)Sr.delete(a.operationId);u.previews?.dispose();for(let f of u.terminals.values())f.abort()}}var _a=5000,ma=20;async function Ba(e){let a=(f)=>{throw new r("hands_rebind_unavailable",f)};if(!ce(e.operationId)||!ce(e.runId)||!ce(e.fenceId)||!Ee(e.targetGeneration))a("Reason sent an invalid Hands rebind.");let l=Sr.get(e.operationId);if(!l||l.binding.root!==e.root)return a("No live Hands supervisor owns this operation.");for(let f=Date.now()+_a;;){if(e.signal?.aborted)a("The Hands rebind was cancelled.");if(Sr.get(e.operationId)!==l)a("The Hands supervisor is no longer current.");let g=null;try{g=$r(l.binding)}catch{}if(g&&g.generation===e.targetGeneration&&g.fenceId===e.fenceId)break;if(g&&g.generation>e.targetGeneration||Date.now()>=f)a("The executor did not adopt this take.");await new Promise((k)=>setTimeout(k,ma))}if(Sr.get(e.operationId)!==l||rr.get(l.key)!==l)a("The Hands supervisor is no longer current.");let u=hr(e.root,e.runId);if(l.key===u)return;if(rr.has(u))a("The taking run already has a live Hands job supervisor.");rr.delete(l.key);for(let f of l.terminals.values())f.abort();l.key=u,rr.set(u,l)}function Ze(e){let a="operationId"in e?Sr.get(e.operationId):rr.get(hr(e.root,e.runId)),l=a&&a.binding.root===e.root?a.binding:void 0;if(!l?.environment||l.expiresAtMs<=Date.now())throw new r("environment_unavailable","No live Hands supervisor owns this environment.");return l.environment.install(e.payload)}async function Fa(e){let a=rr.get(hr(e.root,e.runId));if(!a?.previews||!e.owner)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return a.previews.open(e.payload,e.owner,e.signal)}async function ja(e){let a=rr.get(hr(e.root,e.runId));if(!a?.previews||!e.owner||e.signal.aborted)throw new r("preview_unavailable","No authenticated Hands supervisor owns this preview.");return a.previews.close(e.payload,e.owner)}async function Xr(e){let a=hr(e.root,e.runId),l=rr.get(a),u=l?.binding,f=u?.runId,g=u?.previewAuthority,k=u?.environment,O=e.owner&&{...e.owner},w=e.authority&&{...e.authority},P=()=>{throw new r("pty_binding_unavailable","No current authenticated Hands scope owns this terminal.")};if(!l||!u||!g||!k||!O||!w||!u.workspace)return P();let N=Object.freeze({...u.workspace}),T=$r(u),S=k.current(),M=()=>{if(rr.get(a)!==l||O.organization_id!==g.owner.organization_id||O.user_id!==g.owner.user_id||O.device_id!==g.owner.device_id||e.deviceId!==g.owner.device_id||e.rootId!==g.rootId||X(e.workspace)!==X(N))P();let C=$r(u),z=k.current();if(C.generation!==T.generation||C.fenceId!==T.fenceId||z.run_id!==f||z.device_id!==e.deviceId||z.root_id!==e.rootId||z.snapshot_id!==S.snapshot_id||z.revision!==S.revision||z.binding.target_generation!==T.generation||z.binding.target_fence_id!==T.fenceId||w.device_id!==e.deviceId||w.binding!==z.binding.kind||w.target_revision!==z.binding.target_revision||w.root_grant_revision!==z.binding.root_grant_revision||w.target_generation!==T.generation||w.target_fence_id!==T.fenceId)P()};if(M(),new URL(e.session.relayUrl).origin!==g.relayOrigin||l.terminals.has(e.session.jobId)||l.terminals.size>=4)return P();let j=new AbortController;l.terminals.set(e.session.jobId,j);try{return await Mo({session:{...e.session,leaseExpiresAtMs:Math.min(e.session.leaseExpiresAtMs,T.expiresAtMs,Date.parse(S.expires_at))},signal:AbortSignal.any([e.signal,j.signal]),emit:e.emit,binding:{assertCurrent:M,environment:{revision:S.revision,snapshotId:S.snapshot_id},scope:{runId:e.runId,deviceId:e.deviceId,rootId:e.rootId,workspace:N,binding:S.binding.kind,targetRevision:S.binding.target_revision,rootGrantRevision:S.binding.root_grant_revision,generation:T.generation,fenceId:T.fenceId,executorLaunchId:T.executorLaunchId},request:(C,z)=>ti(T,xi(JSON.stringify({...C,type:"job",version:2,generation:T.generation,id:Sn()})),z)}})}finally{if(l.terminals.get(e.session.jobId)===j)l.terminals.delete(e.session.jobId)}}async function Ha(e){if(nt(e.payload.jobId))throw new r("pty_binding_required","PTY jobs require the bound terminal capability.");let a=rr.get(hr(e.root,e.runId))?.binding;if(!a||a.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","No live Hands supervisor owns this Session and root.");return Yo(a,e.payload,e.signal)}var ha=1e4,ga=20,ba=gt/2,wa=zt/2,ya=(e)=>e.output.reduce((a,l)=>a+l.text.length,0);async function Yo(e,a,l){if(Object.keys(a).some((P)=>!["jobId","action","input","waitForExitMs"].includes(P)))throw new r("invalid_payload","Unexpected job control field.");let{waitForExitMs:u,...f}=a;if(u!==void 0&&(f.action!=="start"||typeof f.input!=="object"||f.input===null||!("script"in f.input)||typeof u!=="number"||!Number.isSafeInteger(u)||u<1||u>ha))throw new r("invalid_payload","Only a script start may wait for its job, within its bound.");let g=(P)=>{let N=$r(e);return ti(N,xi(JSON.stringify({...P,type:"job",version:2,generation:N.generation,id:Sn()})),l)},k=await g(f);if(u===void 0)return k;let O=Date.now()+u,w=k;while(w.ok&&["starting","running"].includes(w.job.state)&&w.job.output.length<ba&&ya(w.job)<wa&&!l.aborted&&Date.now()<O){if(await new Promise((P)=>setTimeout(P,Math.min(ga,O-Date.now()))),l.aborted)break;try{let P=await g({jobId:f.jobId,action:"inspect",input:{after:0}});if(!P.ok)break;w=P}catch{break}}return w}function $r(e){if(e.expiresAtMs<=Date.now())throw new r("hands_jobs_unavailable","Hands authority expired.");let a=e.readIdentity?e.readIdentity():e;if(!a||!Ee(a.generation)||!ce(a.fenceId)||a.generation<e.generation||a.generation===e.generation&&a.fenceId!==e.fenceId)throw new r("hands_jobs_unavailable","The live Hands fencing identity could not be verified.");return e.generation=a.generation,e.fenceId=a.fenceId,{...e}}function ti(e,a,l){if(l.aborted)return Promise.reject(new r("cancelled","Job control was cancelled."));return new Promise((u,f)=>{let g=ra(e.socketPath),k="",O=!1,w,P=(T,S)=>{if(O)return;if(O=!0,clearTimeout(w),l.removeEventListener("abort",N),g.destroy(),T)f(T);else u(S)},N=()=>P(new r("cancelled","Job control waiter cancelled; inspect before retrying mutations."));l.addEventListener("abort",N,{once:!0}),g.setEncoding("utf8"),w=setTimeout(()=>P(new r("hands_job_result_unknown","Job control timed out; inspect before retrying mutations.")),Math.min(1e4,Math.max(1,e.expiresAtMs-Date.now()))),g.on("error",()=>P(new r("hands_job_result_unknown","Hands job control connection failed."))),g.once("connect",()=>g.write(JSON.stringify({version:1,scopeId:e.scopeId,fenceId:e.fenceId,executorLaunchId:e.executorLaunchId,request:a})+`
|
|
3
3
|
`)),g.on("data",(T)=>{if(k+=T,Buffer.byteLength(k)>qt)P(new r("hands_job_result_unknown","Hands job result exceeded its bound."))}),g.once("end",()=>{if(Date.now()>=e.expiresAtMs){P(new r("hands_job_result_unknown","Hands authority expired before the result was acknowledged."));return}try{let T=Ci(k.trim());if(T.id!==a.id||T.generation!==e.generation||T.ok&&T.job.jobId!==a.jobId)throw Error("identity");P(void 0,T)}catch{P(new r("hands_job_result_unknown","Hands job response identity or shape was invalid."))}}),g.once("close",()=>{if(!O)P(new r("hands_job_result_unknown","Hands job control closed before an acknowledged result."))})})}function zo(e){let a=Er(e.root),l=e.authority,u=Date.parse(e.leaseUntil),f=()=>{if(e.signal.throwIfAborted(),!Number.isFinite(u)||u<=Date.now())throw Error("local_device_gh_lease_expired")};if(f(),l.readOnly&&l.generation===null)return{root:a,readOnly:!0,signal:e.signal,deadlineMs:u,assertCurrent:f};let g=hr(a,e.runId),k=rr.get(g),O=k?.binding;if(!O?.environment||!O.workspace||O.localGithubConfinement!==!0)throw Error("local_device_gh_confinement_unavailable");let w=O.environment.current(),P=()=>{f();let T=O.environment.current(),S=$r(O);if(rr.get(g)!==k||T.github_auth!=="local_gh"||T.run_id!==O.runId||l.runId!==e.runId||T.device_id!==l.deviceId||T.root_id!==l.rootId||String(T.binding.root_grant_revision)!==l.rootRevision||T.binding.target_generation!==l.generation||T.binding.target_fence_id!==l.fenceId||S.generation!==l.generation||S.fenceId!==l.fenceId||T.snapshot_id!==w.snapshot_id||T.revision!==w.revision)throw Error("local_device_gh_authority_changed")};P();let N=Ve(a,O.workspace);return{root:N.boundary,signal:e.signal,deadlineMs:u,privateDirectory:ta(O.environment.path),repoPath:N.path,readOnly:l.readOnly,forbiddenSecretValues:Object.values(w.variables),secretNames:(T)=>Object.entries(w.variables).filter(([,S])=>S.trim()===T.trim()).map(([S])=>`variable ${S}`),assertCurrent:P}}async function Ua(e,a){let l=xt.parse(e.request),u=Ke.parse(e.authority);if(u.contributorRefresh&&l.kind==="read"&&u.readOnly)return a(zo(e));let f=Boolean(u.contributorRefresh);if(f&&(u.merge||l.kind!=="pr_mutation"||l.mutation.action!=="edit"||typeof l.mutation.body!=="string"||l.mutation.title!==void 0||l.mutation.base!==void 0||u.readOnly||u.runId!==e.runId||u.repoFullName!==l.repoFullName))throw Error("local_device_gh_contributor_refresh_authority_invalid");if(l.kind!=="pr_merge"&&!f){if(u.merge)throw Error("local_device_gh_merge_authority_invalid");return a(zo(e))}if(!f&&(!u.merge||u.readOnly||u.runId!==e.runId||u.repoFullName!==l.repoFullName||u.merge.source==="agent"&&(u.generation===null||u.fenceId===null)))throw Error("local_device_gh_merge_authority_invalid");let g=Er(e.root),k=yt(g),O=Date.parse(e.leaseUntil);if(!Number.isFinite(O)||O<=Date.now())throw Error("local_device_gh_lease_expired");let w=Er(Jo());if(w===g||w.startsWith(g+vn))throw Error("local_device_gh_private_scope_unavailable");let P=Ko(Dr(w,"reason-gh-merge-"));try{zr(P);let N=()=>{if(e.signal.throwIfAborted(),Date.now()>=O)throw Error("local_device_gh_lease_expired");let T=yt(e.root);if(T.isSymbolicLink()||T.dev!==k.dev||T.ino!==k.ino||Er(e.root)!==g)throw Error("local_device_gh_authority_changed");zr(P)};return N(),await a({root:g,readOnly:!1,privateDirectory:P,forbiddenSecretValues:[],signal:e.signal,deadlineMs:O,assertCurrent:N})}finally{yn(P,{recursive:!0,force:!0})}}var Qo=43200000;function Kr(e){return Number.isSafeInteger(e)&&Math.abs(e)<=8640000000000000?e:null}function Xo(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Zo(e,a){return Object.keys(e).length===a.length&&a.every((l)=>Object.hasOwn(e,l))}function za(e){if(!Xo(e)||!Zo(e,["version","outcome","clock_source","validation_now_ms","expiry_ms","remaining_ms","maximum_lifetime_ms","cli_artifact"])||e.version!==1||e.maximum_lifetime_ms!==43200000||typeof e.outcome!=="string"||!["accepted","parse","noncanonical","expired","over_cap"].includes(e.outcome)||typeof e.clock_source!=="string"||!["date_now","injected"].includes(e.clock_source))return null;for(let u of["validation_now_ms","expiry_ms"]){let f=e[u];if(f!==null&&(typeof f!=="number"||Kr(f)===null))return null}if(e.remaining_ms!==null&&(typeof e.remaining_ms!=="number"||!Number.isSafeInteger(e.remaining_ms)))return null;let a=typeof e.expiry_ms==="number"&&typeof e.validation_now_ms==="number"?e.expiry_ms-e.validation_now_ms:null;if(e.remaining_ms!==(a!==null&&Number.isSafeInteger(a)?a:null))return null;if(e.outcome==="parse"&&e.expiry_ms!==null)return null;if(e.outcome!=="parse"&&e.expiry_ms===null)return null;if(e.outcome==="expired"&&!(typeof a==="number"&&a<=0))return null;if(e.outcome==="over_cap"&&!(typeof a==="number"&&a>43200000))return null;if(e.outcome==="accepted"&&!(typeof a==="number"&&a>0&&a<=43200000))return null;let l=e.cli_artifact;if(!Xo(l)||!Zo(l,["kind","status","sha256","observed_at_ms"])||l.observed_at_ms!==null&&(typeof l.observed_at_ms!=="number"||Kr(l.observed_at_ms)===null))return null;if(l.kind==="entrypoint_file"){if(l.status!=="observed"||typeof l.sha256!=="string"||!/^[a-f0-9]{64}$/.test(l.sha256)||l.observed_at_ms===null)return null}else if(l.kind!=="unavailable"||l.sha256!==null||typeof l.status!=="string"||!["unsupported_entrypoint","read_failed","file_changed","size_limit","time_limit"].includes(l.status))return null;return e}var En=h({kind:c(["workspace_source","mcp_control"]),target_revision:o().int().nonnegative(),root_grant_revision:o().int().positive()}),es=new RegExp(pr.tokenPattern),va=h({token_url:Mr().max(2048),request_token:t().min(1).max(8192).regex(es),aws_credentials_url:Mr().max(2048).nullable()});function rs(e,a){let l=(u,f)=>{try{let g=new URL(u);return g.origin===new URL(a).origin&&g.pathname===f&&!g.username&&!g.password&&!g.search&&!g.hash}catch{return!1}};if(!es.test(e.request_token)||!l(e.token_url,pr.tokenPath)||e.aws_credentials_url!==null&&!l(e.aws_credentials_url,pr.awsPath))return null;return{REASON_OIDC_TOKEN_URL:e.token_url,REASON_OIDC_REQUEST_TOKEN:e.request_token,...e.aws_credentials_url!==null?{AWS_CONTAINER_CREDENTIALS_FULL_URI:e.aws_credentials_url,AWS_CONTAINER_AUTHORIZATION_TOKEN:e.request_token}:{}}}function ts(e){return new TextEncoder().encode(e).byteLength}function ka(e){return ts(JSON.stringify(e)+`
|
|
4
4
|
`)}var ri=h({version:i(1),snapshot_id:V(),revision:o().int().positive(),run_id:t().min(1).max(160),device_id:V(),root_id:V(),binding:En.extend({target_generation:o().int().positive(),target_fence_id:V()}),expires_at:I.datetime({offset:!0}),variables:$e(t().max(128).regex(tn),t().refine((e)=>!e.includes("\x00")&&ts(e)<=Re.valueBytes)).refine((e)=>Object.keys(e).length<=Re.variables),github_auth:i("local_gh").optional(),git:h({base_url:Mr().max(2048),token:t().min(1).max(4096).regex(/^[A-Za-z0-9._~-]+$/),expires_at:I.datetime({offset:!0})}).nullable(),cloud_access:va.optional()}).refine((e)=>e.github_auth!=="local_gh"||e.git===null,"conflicting git authority").refine((e)=>ka(e)<=Re.snapshotBytes,"snapshot too large");import{spawn as Sa}from"child_process";import{basename as Ea,isAbsolute as Ef}from"path";var Ra=0,ns=120000,os=15000,Oa=65536;function Rn(e=process.execPath,a=process.argv[1]){let l=Ea(e),u=(l.startsWith("bun")||l.startsWith("node"))&&typeof a==="string"&&a.length>0;return{command:e,prefix:u?[a]:[]}}function Yr(e={}){let{command:a,prefix:l}=Rn(e.executablePath,e.sourceEntrypoint),u=e.spawnProcess??Sa,f=e.now??Date.now,g=null,k=0,O=!1,w=(N)=>{try{N.kill("SIGKILL")}catch{}},P=()=>{if(O)return;if(g&&f()-k<ns-os)return;if(g){let T=g;g=null,w(T)}let N;try{N=u(a,[...l,"__device","__hands-worker","--handoff-fd",String(Ra)],{cwd:"/",env:{PATH:process.env.PATH??"/usr/local/bin:/usr/bin:/bin"},shell:!1,stdio:["pipe","ignore","pipe"]})}catch{return}g=N,k=f(),N.on("error",()=>{if(g===N)g=null}),N.once("exit",(T,S)=>{if(g!==N)return;g=null,e.log?.("hands.worker_prespawn_exited",{exit_code:T,exit_signal:S})}),e.log?.("hands.worker_prespawned",{pid:N.pid??null})};return{arm:P,take(N){let T=g;if(!T||O)return null;let S=N.args.at(-1),M=N.options.env,j=N.options.cwd,C=[...l,"__device","__hands-worker","--config"];if(N.command!==a||N.args.length!==C.length+1||C.some((re,we)=>N.args[we]!==re)||typeof S!=="string"||!M||typeof j!=="string"||N.options.shell||JSON.stringify(N.options.stdio)!==JSON.stringify(["ignore","ignore","pipe"]))return null;g=null;let z=T.stdin,Q={configPath:S,cwd:j,env:Object.fromEntries(Object.entries(M).filter((re)=>typeof re[1]==="string"))},Y=JSON.stringify(Q);if(T.exitCode!==null||T.signalCode!==null||!z||z.destroyed||f()-k>=ns-os||Buffer.byteLength(Y,"utf8")>Oa)return w(T),null;return z.on("error",()=>{return}),z.end(Y),T.once("exit",()=>{P()}),e.log?.("hands.worker_prespawn_taken",{pid:T.pid??null}),T},adopt(N){N.once("exit",()=>{P()})},close(){if(O=!0,g)w(g);g=null}}}import{accessSync as Da,constants as Ca,statSync as Na}from"fs";import{homedir as Za,tmpdir as Qa,userInfo as ec}from"os";import{delimiter as rc,win32 as nc}from"path";var xa=new Set(["ALL_PROXY","BUN_BE_BUN","BUN_OPTIONS","CURL_CA_BUNDLE","GIT_SSL_CAINFO","GRPC_DEFAULT_SSL_ROOTS_FILE_PATH","HTTPS_PROXY","HTTP_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED","REQUESTS_CA_BUNDLE","SSLKEYLOGFILE","SSL_CERT_DIR","SSL_CERT_FILE","all_proxy","http_proxy","https_proxy","no_proxy"]);var Pa=["BUN_CONFIG_","BUN_INSPECT","DYLD_","NODE_DEBUG"],Ia=new Set(["BUN_INSTALL"]);var Aa=/^--(?:max-old-space-size|max-semi-space-size|stack-size)=\d{1,9}$/;function Ta(e){return(e??"").split(/\s+/).filter(Boolean).every((a)=>Aa.test(a.replaceAll("_","-")))}function dt(e){return Object.keys(e).filter((a)=>xa.has(a)&&!(a==="NODE_OPTIONS"&&Ta(e[a]))||Pa.some((l)=>a.startsWith(l))||a.startsWith("BUN_")&&!Ia.has(a)).sort()}var oc=new Set(["HOME","PATH","PWD","OLDPWD","SHLVL","_","TMPDIR","TMP","TEMP","SHELL","BASH_ENV","ENV","ZDOTDIR","PROMPT_COMMAND","IFS","CDPATH","GLOBIGNORE","SHELLOPTS","BASHOPTS","NODE_PATH"]),sc=/^(?:ARA_|REASON_|PI_|GIT_|GH_|GITHUB_|LD_|DYLD_|BUN_|BASH_FUNC_|SSH_)/,ac=/TOKEN|SECRET|PASSW|PASSPHRASE|CREDENTIAL|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|AUTH/i,cc=/^[A-Za-z_][A-Za-z0-9_]*$/;function ii(e=process.env){let a=(f)=>{if(!(process.platform==="win32"?nc.isAbsolute(f):f.startsWith("/"))||/[\0\r\n]/.test(f)||f.length>32768)throw Error("invalid_host_execution_environment");return f};if(e.PATH!==void 0&&(/[\0\r\n]/.test(e.PATH)||e.PATH.length>32768))throw Error("invalid_host_execution_environment");let l=new Set(dt(e)),u=Object.fromEntries(Object.entries(e).filter((f)=>{let[g,k]=f;return typeof k==="string"&&k.length<=32768&&!k.includes("\x00")&&g.length<=128&&cc.test(g)&&!l.has(g)&&!oc.has(g)&&!sc.test(g)&&!ac.test(g)}).sort(([f],[g])=>f.localeCompare(g)).slice(0,512));return{home:a(e.HOME||(process.platform==="win32"?e.USERPROFILE:void 0)||Za()),path:((f)=>process.platform==="win32"?Po(f):f)(pi(e.PATH??"").join(rc)||Bt),temporaryDirectory:a(e.TMPDIR||e.TMP||e.TEMP||Qa()),variables:u}}function oi(e=process.env,a=()=>ec().shell){if(process.platform==="win32")return Xe();let l=(f)=>{if(!f||!/^\/[A-Za-z0-9._/-]*\/(?:bash|zsh)$/.test(f))return!1;try{return Da(f,Ca.X_OK),Na(f).isFile()}catch{return!1}};if(l(e.SHELL))return e.SHELL;let u;try{u=a()}catch{u=void 0}return l(u)?u:"/bin/zsh"}import{readdir as dc}from"fs/promises";var lc=15000;function wo(e){let a=e instanceof Error&&"code"in e?e.code:null;return a==="EPERM"||a==="EACCES"}function bo(e){return new r("folder_access_denied",`macOS blocked Reason from opening ${e}. Allow Reason in System Settings \u203A Privacy & Security \u203A Files and Folders `+"(or Full Disk Access), then restart the Reason app or worker on this Mac and try again: until it restarts it keeps the earlier refusal.")}async function ss(e,{timeoutMs:a=lc,open:l=(u)=>dc(u)}={}){let u,f=new Promise((g)=>{u=setTimeout(()=>g("pending"),a)});try{if(await Promise.race([l(e).then(()=>"open"),f])==="pending")throw new r("folder_access_pending",`macOS is asking whether Reason may open ${e}. Answer the prompt on this Mac, then try again.`)}catch(g){if(wo(g))throw bo(e);if(g instanceof r)throw g}finally{clearTimeout(u)}}import{chmodSync as Jc,closeSync as Vc,constants as Ln,fstatSync as qc,lstatSync as Os,openSync as Yc,readSync as Xc,realpathSync as Bn,unlinkSync as Zc}from"fs";import{lookup as Qc}from"dns/promises";import{createRequire as ed}from"module";import{request as rd}from"http";import{request as td}from"https";import Lr from"net";import{platform as Ts}from"os";import{basename as nd,extname as od,isAbsolute as xs,relative as jn,resolve as qr,sep as Mn}from"path";var is=String.raw`
|
|
5
5
|
async (roots) => {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Xt,Er}from"./vm-hands-entry-lite-j10cw3d9.js";import{g}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Xt,Er}from"./vm-hands-entry-lite-j10cw3d9.js";import{g}from"./vm-hands-entry-lite-bj3w2ven.js";import{Ic,ot,Yt,kr,In}from"./vm-hands-entry-lite-6jxshhps.js";import{L}from"./vm-hands-entry-lite-ptycjmkc.js";import{s,St}from"./vm-hands-entry-lite-zawytz09.js";import{spawnSync as se}from"child_process";import{dirname as S}from"path";import{spawn as U}from"child_process";import{accessSync as H,constants as J}from"fs";import{basename as q,join as B}from"path";var d=null;function R(e){if(d===e)d=null;if(e.exitCode===null&&e.signalCode===null)e.kill("SIGTERM")}var Li=(e,t)=>{if(d)R(d);let r=B(e,Ic);try{H(r,J.X_OK)}catch{return()=>{}}let n;try{n=U(r,["--app",e,"--name",q(e,".app"),"--permission",t==="screen"?"screen_recording":"accessibility"],{detached:!0,stdio:"ignore"})}catch{return()=>{}}return n.on("error",()=>{if(d===n)d=null}),n.once("exit",()=>{if(d===n)d=null}),n.unref(),d=n,()=>R(n)};import{chmodSync as K,existsSync as I,mkdirSync as V,readFileSync as Y,realpathSync as A,renameSync as X,statSync as _,writeFileSync as z}from"fs";import{dirname as v,isAbsolute as Q,join as Z,resolve as C,sep as w}from"path";function k(e=s()){return Z(St(e),"reason","protected-path-grants.json")}var p=null;function ee(e){let t=JSON.parse(e);if(!Array.isArray(t?.grants))return[];return t.grants.flatMap((r)=>{let n=r;return n&&typeof n.path==="string"&&Q(n.path)&&(n.kind==="file"||n.kind==="folder")&&typeof n.grantedAt==="number"?[{path:n.path,kind:n.kind,grantedAt:n.grantedAt}]:[]})}function m(e=k()){try{let{mtimeMs:t}=_(e);if(p&&p.file===e&&p.mtimeMs===t)return p.grants;let r=ee(Y(e,"utf8"));return p={file:e,mtimeMs:t,grants:r},r}catch{return[]}}function te(e,t){return e.kind==="file"?t===e.path:t===e.path||t.startsWith(`${e.path}${w}`)}function ne(e,t){let r=C(e);return m(t).some((n)=>te(n,r))}function yc(e,t){return L(e)&&!ne(e,t)}function O(e,t){V(v(t),{recursive:!0,mode:448});let r=`${t}.${process.pid}.tmp`;z(r,`${JSON.stringify({version:1,grants:e},null,2)}
|
|
3
3
|
`,{mode:384}),K(r,384),X(r,t),p=null}function D(e,t=k(),r=Date.now()){if(!I(e))throw Error(`No file or folder at ${e}.`);let n=A(e),i=v(t);if(i===n||i.startsWith(`${n}${w}`)||n.startsWith(`${i}${w}`))throw Error("Reason's own configuration folder cannot be allowed.");let o={path:n,kind:_(n).isDirectory()?"folder":"file",grantedAt:r},a=m(t).filter((l)=>l.path!==n);return O([...a,o],t),o}function j(e,t=k()){let r=I(e)?A(e):C(e),n=m(t),i=n.filter((o)=>o.path!==r);if(i.length===n.length)return!1;return O(i,t),!0}function wc(e,t,r){let n=t?"file-read* file-write*":"file-read*";return m(r).filter((i)=>i.path===e||i.path.startsWith(`${e}${w}`)).map((i)=>`(allow ${n} (${i.kind==="file"?"literal":"subpath"} ${JSON.stringify(i.path)}))`)}var G=`Reason permissions
|
|
4
4
|
|
|
5
5
|
Usage:
|
|
@@ -20,7 +20,7 @@ this Mac may open. Only you can change this list; Sessions cannot.
|
|
|
20
20
|
allow asks for each missing one, or the one named. macOS cannot ask for Full
|
|
21
21
|
Disk Access: allow disk opens its pane, shows the file to add in Finder and
|
|
22
22
|
waits until the worker has it.
|
|
23
|
-
`,b="x-apple.systempreferences:com.apple.preference.security",re="curl -fsSL https://reasonmachines.com/install.sh | bash",ie=180000,oe=2000,M=["screen","accessibility","disk"],x={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${b}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${b}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${b}?Privacy_AllFiles`}};function F(e){return e.executable}function ae(e,t){if(e==="computer_use_identity_missing")return`Reason's background identity is not installed (${e}); reinstall Reason: ${re}`;if(e==="computer_use_identity_outdated")return`Reason's background identity is outdated (${Yt(t)??"unknown"}; this CLI is ${g}) (${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 Qc(e=s()){let t=kr(e);if(t.length>0)return{state:"ready",path:S(S(S(t[0]))),prefix:t};let r=In(t,e)??"computer_use_identity_unavailable";return{state:r,path:ot(e),detail:ae(r,e)}}function E(){return{identity:()=>Qc(),grants:(e)=>Xt(e),request:(e,t)=>Er(e,t),worker:async()=>(await import("./status-
|
|
23
|
+
`,b="x-apple.systempreferences:com.apple.preference.security",re="curl -fsSL https://reasonmachines.com/install.sh | bash",ie=180000,oe=2000,M=["screen","accessibility","disk"],x={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${b}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${b}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${b}?Privacy_AllFiles`}};function F(e){return e.executable}function ae(e,t){if(e==="computer_use_identity_missing")return`Reason's background identity is not installed (${e}); reinstall Reason: ${re}`;if(e==="computer_use_identity_outdated")return`Reason's background identity is outdated (${Yt(t)??"unknown"}; this CLI is ${g}) (${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 Qc(e=s()){let t=kr(e);if(t.length>0)return{state:"ready",path:S(S(S(t[0]))),prefix:t};let r=In(t,e)??"computer_use_identity_unavailable";return{state:r,path:ot(e),detail:ae(r,e)}}function E(){return{identity:()=>Qc(),grants:(e)=>Xt(e),request:(e,t)=>Er(e,t),worker:async()=>(await import("./status-khqk4cjw.js")).connectionMacState(),open:(e)=>{se("/usr/bin/open",e,{stdio:"ignore",timeout:1e4})},tile:Li,restartConnection:async()=>(await import("./connect-cli-dmwph620.js")).restartConnection(),sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now()}}function N(e,t,r){if(e.state!=="ready"||!t)return"unknown";return t[r]?"granted":"missing"}async function bc(e){let t=e.identity(),r=t.state==="ready"?await e.grants(t.prefix):null,n=await e.worker(),i=n?F(n):null,o=!i||n?.full_disk_access==="unknown"?"unknown":n?.full_disk_access==="granted"?"granted":"missing",a=(l,u,c)=>{let{label:f,purpose:y,level:h}=x[l];return{id:l,label:f,purpose:y,level:h,state:u,holder:c}};return{identity:{state:t.state,path:t.path,detail:t.state==="ready"?null:t.detail},worker_detail:i?null:"Full Disk Access is read from this computer's running worker; `reason connect` starts it.",permissions:[a("screen",N(t,r,"screen"),t.path),a("accessibility",N(t,r,"accessibility"),t.path),a("disk",o,i)]}}function vl(e){let t=e.identity.state==="ready"?null:e.identity.state,r=e.permissions.filter((o)=>o.state==="granted").length,n=[...t?[t]:[],...e.permissions.filter((o)=>o.state!=="granted"&&!(t&&o.id!=="disk")).map((o)=>`${o.label} ${o.state}`)],i=!t&&e.permissions.some((o)=>o.state==="missing");return`Permissions: ${r} of ${e.permissions.length}${n.length>0?` (${n.join(", ")})`:""}`+(i?" \u2014 reason permissions allow":n.length>0?" \u2014 reason permissions":"")}function ce(e){let t=[];if(e.identity.detail)t.push(e.identity.detail);t.push(`Reason: ${e.identity.path}`);let r=e.permissions.find((n)=>n.id==="disk");t.push(r?.holder?`Worker: ${r.holder}`:`Worker: ${e.worker_detail}`),t.push("");for(let n of e.permissions){let i=`${n.label}${n.level==="recommended"?" (recommended)":""}`;t.push(` ${n.id.padEnd(13)} ${n.state.padEnd(7)} ${i}: ${n.purpose}`)}if(e.permissions.some((n)=>n.state==="missing"))t.push("","Allow the missing ones: reason permissions allow");return`${t.join(`
|
|
24
24
|
`)}
|
|
25
25
|
`}async function T(e,t){let r=t.now()+ie;for(;;){if(await e())return!0;if(t.now()>=r)return!1;await t.sleep(oe)}}async function el(e,t){let r=t.host??E(),{io:n}=t,i=await bc(r),o=i.permissions.filter((c)=>e.includes(c.id)&&c.state!=="granted");if(o.length===0)return n.stdout.write(`Reason permissions: ${e.map((c)=>x[c].label).join(", ")} already allowed.
|
|
26
26
|
`),0;let a=!1,l=!1,u=r.identity();for(let c of o){let{label:f,pane:y}=x[c.id];if(c.id!=="disk"){if(u.state!=="ready"){if(!a)n.stderr.write(`Reason permissions: ${u.detail}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var On={name:"github-native-engineer-device-worker-production",version:"0.2.
|
|
2
|
+
var On={name:"github-native-engineer-device-worker-production",version:"0.2.561",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@agentclientprotocol/sdk":"1.9.0","@anthropic-ai/sandbox-runtime":"^0.0.80","@earendil-works/pi-tui":"1.0.0","@reason/runtime-distribution":"workspace:*",diff:"8.0.4","open-browser-use-sdk":"0.1.42","playwright-core":"1.60.0",toml:"5.0.1",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.4",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^5.0.1",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
|
|
3
3
|
export{On};
|