@reason-machines/cli-linux-x64 0.2.566 → 0.2.567
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-0sng03r6.js +2 -0
- package/bin/vm-hands/api-credentials-h4neeejt.js +2 -0
- package/bin/vm-hands/api-mr6xds10.js +2 -0
- package/bin/vm-hands/{ask-relay-gk4ks8mg.js → ask-relay-c0v30hh6.js} +2 -2
- package/bin/vm-hands/connect-cli-jc4m755k.js +2 -0
- package/bin/vm-hands/credentials-nfx99zxr.js +2 -0
- package/bin/vm-hands/custom-endpoint-device-5047vdn3.js +2 -0
- package/bin/vm-hands/desktop-account-d1g1m6yb.js +2 -0
- package/bin/vm-hands/desktop-components-7ngf8byq.js +2 -0
- package/bin/vm-hands/desktop-delegate-4hb0163k.js +2 -0
- package/bin/vm-hands/device-workspace-8941tdsy.js +2 -0
- package/bin/vm-hands/{fsevents-ezcg3e40.js → fsevents-e57jgcfe.js} +1 -1
- package/bin/vm-hands/hands-worker-source-8a4kh44t.js +2 -0
- package/bin/vm-hands/{index-w92ys6ra.js → index-y21r07rf.js} +8 -8
- package/bin/vm-hands/install-receipt-rckwjqmt.js +2 -0
- package/bin/vm-hands/local-automation-3mdhfw08.js +2 -0
- package/bin/vm-hands/local-capabilities-6e0gkrqq.js +2 -0
- package/bin/vm-hands/local-desktop-users-hkdfxqtj.js +2 -0
- package/bin/vm-hands/local-display-mac-gsh74khc.js +2 -0
- package/bin/vm-hands/local-display-session-r6s0wghh.js +2 -0
- package/bin/vm-hands/local-display-video-61peg1pj.js +2 -0
- package/bin/vm-hands/local-managed-process-p8xd7m5f.js +2 -0
- package/bin/vm-hands/local-pty-session-w0yhjdvz.js +2 -0
- package/bin/vm-hands/managed-runtime-4s8q8r7f.js +2 -0
- package/bin/vm-hands/{network-auto-update-qwds22kt.js → network-auto-update-wep7067g.js} +2 -2
- package/bin/vm-hands/network-contract-ht0psj5j.js +2 -0
- package/bin/vm-hands/{network-sign-in-kqdg70kc.js → network-sign-in-rdnerhpz.js} +2 -2
- package/bin/vm-hands/package-3rv6jngd.js +2 -0
- package/bin/vm-hands/permissions-mmg1gbdx.js +2 -0
- package/bin/vm-hands/reason-hands-protocol-9r62swp0.js +2 -0
- package/bin/vm-hands/serve-service-k3mpxpj6.js +2 -0
- package/bin/vm-hands/{status-q55nprve.js → status-2s3zjapg.js} +5 -5
- package/bin/vm-hands/version-41q9twfs.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-pg7nnyc6.js → vm-hands-entry-lite-04nx5y4f.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ezhfkjqr.js → vm-hands-entry-lite-07wr95rz.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-33at6g06.js → vm-hands-entry-lite-0xfme8gg.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-xfak34av.js → vm-hands-entry-lite-1as6h9ed.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-gxf2r5en.js → vm-hands-entry-lite-1cdtev4n.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-fn2805g8.js → vm-hands-entry-lite-1sy80ca9.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-yg4dk99m.js → vm-hands-entry-lite-2927z566.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-6adz91f3.js → vm-hands-entry-lite-298kzt93.js} +70 -70
- package/bin/vm-hands/{vm-hands-entry-lite-3q2ng4e9.js → vm-hands-entry-lite-3594pdj0.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-rz1ep81m.js → vm-hands-entry-lite-3r063pb4.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-2qfmabqn.js → vm-hands-entry-lite-4kb5rq3d.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-5qrft0nw.js → vm-hands-entry-lite-6g9we34r.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-s93f3pbv.js → vm-hands-entry-lite-732hnx41.js} +3 -3
- package/bin/vm-hands/vm-hands-entry-lite-7aeqbfc8.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-y0jtj8zz.js → vm-hands-entry-lite-8twdd0ff.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-x6ybft9v.js → vm-hands-entry-lite-9gn7k5rp.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-b2w5071h.js → vm-hands-entry-lite-ax2w9ywb.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-2gxv7v1h.js → vm-hands-entry-lite-b3mfma12.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-qjrgvdbj.js → vm-hands-entry-lite-bbjsnjct.js} +21 -21
- package/bin/vm-hands/{vm-hands-entry-lite-zp7chzcc.js → vm-hands-entry-lite-bc9zq8gx.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-ngry8nkq.js → vm-hands-entry-lite-bqs4pkyb.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-zpvr7wc6.js → vm-hands-entry-lite-bt6skt4h.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-q62g6sx0.js → vm-hands-entry-lite-chve4vmh.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-72h3t64b.js → vm-hands-entry-lite-crjaacc2.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-fs6jbfp3.js → vm-hands-entry-lite-cy8yc9gb.js} +19 -19
- package/bin/vm-hands/{vm-hands-entry-lite-30z7wsqr.js → vm-hands-entry-lite-dfphra23.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-a3gq377t.js → vm-hands-entry-lite-dh87ysh2.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-994kah8n.js → vm-hands-entry-lite-dtw6cj95.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-a8z57vry.js → vm-hands-entry-lite-dzdjwa06.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-chq0qx9f.js → vm-hands-entry-lite-g0bpdyfz.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-rxydyqke.js → vm-hands-entry-lite-h7f5a5mb.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-13nx02p7.js → vm-hands-entry-lite-hh0kba1y.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-fccn6s4j.js → vm-hands-entry-lite-hpe54h0b.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-kbnxk71q.js → vm-hands-entry-lite-hpw27zfb.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-284z7ct8.js → vm-hands-entry-lite-kankyeep.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-9wp7ahwa.js → vm-hands-entry-lite-n5jyzccm.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-88dxn9b5.js → vm-hands-entry-lite-peyr9y6z.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-cmmb9k3g.js → vm-hands-entry-lite-r131db1f.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-72084j3g.js → vm-hands-entry-lite-rmcdfbkk.js} +24 -24
- package/bin/vm-hands/{vm-hands-entry-lite-1b21avcs.js → vm-hands-entry-lite-sb1xtqxr.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-b1vanmtv.js → vm-hands-entry-lite-sxnvhzy5.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-cc8hwgxc.js → vm-hands-entry-lite-t2rhwchw.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-sh4mqy93.js → vm-hands-entry-lite-t3k90kdn.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-bkhc5mt4.js → vm-hands-entry-lite-tv5mcw97.js} +6 -6
- package/bin/vm-hands/{vm-hands-entry-lite-12ck5swp.js → vm-hands-entry-lite-tzv8s0e7.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-50kqbrb7.js → vm-hands-entry-lite-vedb5r12.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-jj7873n8.js → vm-hands-entry-lite-vha0pf8k.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-fxptf351.js → vm-hands-entry-lite-vvhfaxpd.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-3gc2bn5a.js → vm-hands-entry-lite-wtjqjvea.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-p02vay5n.js → vm-hands-entry-lite-xd393rm3.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-z65xva21.js → vm-hands-entry-lite-ys4jhf7n.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ttfqxjms.js → vm-hands-entry-lite-zaj1vnnd.js} +9 -9
- package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
- package/bin/vm-hands/{vm-hands-executor-r6v6tzqj.js → vm-hands-executor-31ea40aw.js} +4 -4
- package/bin/vm-hands/{vm-hands-op-runner-wcbc42nw.js → vm-hands-op-runner-6r390v3d.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-2t08ywa4.js → vm-hands-runtime-z9m50n9p.js} +3 -3
- package/bin/vm-hands/worker-preview-readiness-w4zy5g2p.js +2 -0
- package/bin/vm-hands/worker-sandbox-2trfs79b.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/agent-network-pak3wvrv.js +0 -2
- package/bin/vm-hands/api-credentials-a433ykxs.js +0 -2
- package/bin/vm-hands/api-kex52g1d.js +0 -2
- package/bin/vm-hands/connect-cli-afdc1h11.js +0 -2
- package/bin/vm-hands/credentials-sk4sag42.js +0 -2
- package/bin/vm-hands/custom-endpoint-device-3jscber1.js +0 -2
- package/bin/vm-hands/desktop-account-xma0330a.js +0 -2
- package/bin/vm-hands/desktop-components-y89gpa6e.js +0 -2
- package/bin/vm-hands/desktop-delegate-tch2qzx0.js +0 -2
- package/bin/vm-hands/device-workspace-4bj43nxq.js +0 -2
- package/bin/vm-hands/hands-worker-source-8pe7yv0m.js +0 -2
- package/bin/vm-hands/install-receipt-68xxg7hn.js +0 -2
- package/bin/vm-hands/local-automation-1s7035zm.js +0 -2
- package/bin/vm-hands/local-capabilities-h1hxzrhn.js +0 -2
- package/bin/vm-hands/local-desktop-users-jpf0resr.js +0 -2
- package/bin/vm-hands/local-display-mac-h5yz0ydd.js +0 -2
- package/bin/vm-hands/local-display-session-0vw1x2k6.js +0 -2
- package/bin/vm-hands/local-display-video-k4bgptc7.js +0 -2
- package/bin/vm-hands/local-managed-process-b79p5wwv.js +0 -2
- package/bin/vm-hands/local-pty-session-tqn2xmph.js +0 -2
- package/bin/vm-hands/managed-runtime-9jfx2885.js +0 -2
- package/bin/vm-hands/network-contract-nkwcf4r9.js +0 -2
- package/bin/vm-hands/package-9w0mmxb5.js +0 -2
- package/bin/vm-hands/permissions-q9nfdxrh.js +0 -2
- package/bin/vm-hands/reason-hands-protocol-pck5har9.js +0 -2
- package/bin/vm-hands/serve-service-hcc0zvg8.js +0 -2
- package/bin/vm-hands/version-7q2ft41r.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-997y1m1r.js +0 -3
- package/bin/vm-hands/worker-preview-readiness-h96yr4wf.js +0 -2
- package/bin/vm-hands/worker-sandbox-6kkhvryn.js +0 -2
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{te}from"./vm-hands-entry-lite-
|
|
3
|
-
export{
|
|
2
|
+
import{te}from"./vm-hands-entry-lite-hpw27zfb.js";import{_r}from"./vm-hands-entry-lite-bc9zq8gx.js";import{_n}from"./vm-hands-entry-lite-dh87ysh2.js";import{Se}from"./vm-hands-entry-lite-1as6h9ed.js";import{Ge}from"./vm-hands-entry-lite-tzv8s0e7.js";import{Ot}from"./vm-hands-entry-lite-wnqqjsew.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{existsSync as D,realpathSync as W,statSync as J}from"fs";import{platform as h}from"os";import{isAbsolute as q,sep as X}from"path";import{existsSync as F}from"fs";import{createRequire as H}from"module";var k=Ot(_n)(()=>H(import.meta.url)("bun:ffi"),F);function yi(){return process.platform==="win32"&&typeof globalThis.Bun<"u"&&k.available()}function E(e=process.env){return k.defaultShell(e)}function C(e){return k.shellArgs(e)}function M(e){let n=k.spawn({...e,env:e.environment});return n.exited.then(()=>n.close()),{write:(o)=>n.write(o),resize:(o,t)=>n.resize(o,t),kill:()=>n.close(),exited:n.exited}}var wi=43200000,hn=_r,bi=4,Y=/^[A-Za-z0-9._:-]{1,160}$/,K=1000;function z(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function P(e,n){if(typeof e!=="number"||!Number.isFinite(e)||e<=0)return n;return Math.min(K,Math.max(1,Math.floor(e)))}function G(e,n=Date.now()){let o=["relay_url","session_id","expires_at"],t=new Set([...o,"cols","rows","cwd","workspace"]);if(!z(e)||o.some((b)=>!(b in e))||Object.keys(e).some((b)=>!t.has(b)))throw new r("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:c,session_id:m,expires_at:g}=e;if(typeof c!=="string")throw new r("invalid_pty_request","Reason terminal relay URL is missing.");let d;try{d=new URL(c)}catch{throw new r("invalid_pty_request","Reason terminal relay URL is invalid.")}if(d.protocol!=="wss:"&&d.protocol!=="ws:"||d.username||d.password)throw new r("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof m!=="string"||!Y.test(m))throw new r("invalid_pty_request","Reason terminal session identity is invalid.");let p=typeof g==="string"?Date.parse(g):Number.NaN;if(!Number.isFinite(p)||p<=n)throw new r("invalid_pty_request","Reason terminal session has already expired.");if(e.cwd!==void 0&&typeof e.cwd!=="string")throw new r("invalid_pty_request","Reason terminal working directory is invalid.");let a=e.workspace===void 0?void 0:te(e.workspace);if(a===null||a&&e.cwd!==void 0)throw new r("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:c,session_id:m,expires_at:new Date(Math.min(p,n+wi)).toISOString(),cols:P(e.cols,80),rows:P(e.rows,24),...e.cwd===void 0?{}:{cwd:e.cwd},...a?{workspace:a}:{}}}function Q(e,n){if(h()==="win32")[e,n]=[e.toLowerCase(),n.toLowerCase()];return n===e||n.startsWith(e+X)}function N(e,n){if(n===void 0)return e;if(!q(n))throw new r("pty_cwd_invalid","Reason terminal working directory must be absolute.");let o;try{o=W(n)}catch{throw new r("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!Q(e,o))throw new r("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!J(o).isDirectory())throw new r("pty_cwd_invalid","Reason terminal working directory is not a directory.");return o}function il(e=process.env){if(h()==="win32")return E(e);let n=e.SHELL;if(n&&q(n)&&D(n))return n;for(let o of h()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(D(o))return o;return"/bin/sh"}function V(){let e=globalThis.Bun;if(!e)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");return e.spawn}function Fo(){if(h()==="win32")return yi();return typeof globalThis.Bun<"u"}var Z=(e)=>{if(h()==="win32")try{return M({...e,file:e.shell,args:C(e.shell),environment:{...e.environment,TERM:"xterm-256color"}})}catch{throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}let n=V()({cmd:[e.shell,"-i","-l"],cwd:e.cwd,env:{...e.environment,TERM:"xterm-256color"},terminal:{cols:e.cols,rows:e.rows,data:(t,c)=>{e.onData(c)}}}),o=n.terminal;if(!o){try{n.kill()}catch{}throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(t)=>o.write(t),resize:(t,c)=>o.resize(t,c),kill:()=>{try{n.kill()}catch{}},exited:n.exited.then((t)=>typeof t==="number"?t:null,()=>null)}},vi=(e,n)=>n===void 0?new WebSocket(e):new WebSocket(e,{proxy:n}),v=new Set;function ee(e){if(v.size>=bi||v.has(e))return null;v.add(e);let n=!1;return()=>{if(n)return;n=!0,v.delete(e)}}async function jo(e,n={}){let o=n.now??Date.now,t=G(e.payload,o()),c=ee(e.operationId);if(!c)throw new r("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let m=o(),g,d,p;try{let a=t.workspace?Ge(e.root,t.workspace):void 0;g=a?N(D(a.boundary)?W(a.boundary):a.boundary,a.path):N(e.root,t.cwd),d=n.environment??process.env,p=n.shellPath??il(d)}catch(a){throw c(),a}return await new Promise((a,b)=>{let w=null,i=null,S=!1,x=!1,y=!1,T=null,U=0,B=0,O=[],R=0,A=null,l=(s)=>{if(y)return;if(y=!0,A)clearTimeout(A);e.signal.removeEventListener("abort",L);try{w?.kill()}catch{}try{i?.close(1000,"pty_session_over")}catch{}if(c(),s.kind==="rejected"){b(s.error);return}let u={reason:s.reason,exit_code:T,output_bytes:U,input_bytes:B,duration_ms:Math.max(0,o()-m)};e.emitEvent("pty.stopped",{...u}).catch(()=>{return}),a({...u})},L=()=>{let s=e.signal.reason;l({kind:"rejected",error:s instanceof r?s:new r("cancelled","Reason closed the terminal session.")})};if(e.signal.aborted){L();return}e.signal.addEventListener("abort",L,{once:!0}),A=setTimeout(()=>l({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(t.expires_at)-o()));let I=(s)=>{if(U+=s.byteLength,!S||!i){if(O.push(s),R+=s.byteLength,R>hn)l({kind:"resolved",reason:"output_backpressure"});return}try{i.send(s)}catch{l({kind:"resolved",reason:"relay_closed"});return}if(i.bufferedAmount>hn)l({kind:"resolved",reason:"output_backpressure"})};try{w=(n.spawnPty??Z)({shell:p,args:["-i","-l"],cwd:g,cols:t.cols,rows:t.rows,environment:d,onData:(s)=>{if(!y)I(s)}})}catch(s){l({kind:"rejected",error:s instanceof r?s:new r("pty_spawn_failed","Reason could not start the terminal shell.")});return}w.exited.then((s)=>{if(y)return;if(T=s,S&&i)try{i.send(JSON.stringify({t:"exit",code:s}))}catch{}l({kind:"resolved",reason:"shell_exited"})});let j=(n.loadProxy??Se)()?.url;try{i=(n.connect??vi)(t.relay_url,j)}catch{l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}i.binaryType="arraybuffer",i.onopen=()=>{if(y||!i)return;S=!0;try{i.send(JSON.stringify({t:"open",cols:t.cols,rows:t.rows}));for(let s of O.splice(0))i.send(s);R=0}catch{l({kind:"resolved",reason:"relay_closed"});return}x=!0,e.emitEvent("pty.ready",{session_id:t.session_id,cols:t.cols,rows:t.rows}).catch(()=>{return})},i.onmessage=(s)=>{if(y||!w)return;let u=s.data;if(typeof u==="string"){let f;try{f=JSON.parse(u)}catch{return}if(!z(f))return;if(f.t==="resize"){try{w.resize(P(f.cols,t.cols),P(f.rows,t.rows))}catch{}return}if(f.t==="close")l({kind:"resolved",reason:"client_closed"});return}let _=u instanceof ArrayBuffer?new Uint8Array(u):ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):null;if(!_||_.byteLength===0)return;B+=_.byteLength;try{w.write(_)}catch{}},i.onclose=()=>{if(y)return;if(!x){l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}l({kind:"resolved",reason:"relay_closed"})},i.onerror=()=>{if(y||x)return;l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
|
|
3
|
+
export{yi,wi,hn,bi,il,Fo,vi,jo};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Pa}from"./vm-hands-entry-lite-cmmb9k3g.js";import{R}from"./vm-hands-entry-lite-z65xva21.js";import{W}from"./vm-hands-entry-lite-33at6g06.js";import{Q,oo,ve,so}from"./vm-hands-entry-lite-2qfmabqn.js";import{Ir}from"./vm-hands-entry-lite-72h3t64b.js";import{t,o,_,d,n,ll,we,c,i}from"./vm-hands-entry-lite-zpvr7wc6.js";var E=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function k(e){let s=typeof e==="string"?E.exec(e):null;return s?{major:Number(s[1]),minor:Number(s[2])}:null}import{createHash as q,randomBytes as P}from"crypto";import{createInterface as M}from"readline";var v=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var Ge=v.filter((e)=>e!=="network:read"&&e!=="network:write");class y extends Error{oauthCode;constructor(e,s=null){super(e);this.oauthCode=s;this.name="LoginError"}}function Ca(){let e=P(48).toString("base64url"),s=q("sha256").update(e).digest("base64url");return{verifier:e,challenge:s,state:P(32).toString("base64url")}}function z(e,s){let r=typeof e.error==="string"?e.error:null,a=typeof e.error_description==="string"?e.error_description:r?r:s;return new y(a,r)}async function L(e,s,r,a){let l=await r(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:s,signal:a}),u=await l.json().catch(()=>({}));if(!l.ok)throw z(u,`OAuth token request failed (${l.status})`);return u}var j=1e4;async function D(e,s={}){let r=s.fetchImpl??fetch,a=await L(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),r,AbortSignal.timeout(j)).catch((u)=>{if(u instanceof Error&&u.name==="TimeoutError")throw new y("Reason did not answer the login refresh in time. Check the network and retry.");throw u});if(typeof a.access_token!=="string"||typeof a.refresh_token!=="string"||typeof a.expires_in!=="number")throw new y("Reason returned an incomplete refreshed login.");let l={...e,accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:new Date(Date.now()+a.expires_in*1000).toISOString(),scopes:typeof a.scope==="string"?a.scope.split(/\s+/).filter(Boolean):e.scopes};return oo(l,s.path??Q()),l}var w=new Map,N=2000,H=100;function I(e,s){if(!s)return e;if(s.aborted)return Promise.reject(s.reason);return new Promise((r,a)=>{let l=()=>a(s.reason);s.addEventListener("abort",l,{once:!0}),e.then(r,a).finally(()=>s.removeEventListener("abort",l))})}async function be(e={}){let s=e.path??Q(),r=ve(s);if(!r)return null;let a=e.apiOrigin??R(process.env,"REASON_API_URL")?.trim();if(a&&!W(r.apiOrigin,new URL(a).origin))return null;if(!(Date.parse(r.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&r.accessToken!==e.refused))return r;let u=[s,r.apiOrigin,r.clientId,r.refreshToken].join("\x00"),g=w.get(u);if(g)return I(g,e.signal);let h;return h=D(r,{fetchImpl:e.fetchImpl,path:s}).catch(async(p)=>{if(!(p instanceof y)||p.oauthCode!=="invalid_grant"&&p.oauthCode!=="invalid_client")throw p;let S=(f)=>f!==null&&(p.oauthCode==="invalid_client"?f.clientId!==r.clientId:f.refreshToken!==r.refreshToken),O=Date.now()+N;while(!S(ve(s))&&Date.now()<O)await new Promise((f)=>setTimeout(f,H));if(S(ve(s)))return be({fetchImpl:e.fetchImpl,path:s});return so(s),null}).finally(()=>{if(w.get(u)===h)w.delete(u)}),w.set(u,h),I(h,e.signal)}function Aa(e,s){return new Promise((r)=>{let a=M({input:e}),l=!1,u=(h)=>{if(l)return;l=!0,s.removeEventListener("abort",g),a.close(),e.pause(),r(h)},g=()=>u(null);s.addEventListener("abort",g,{once:!0}),a.once("line",(h)=>u(h)),a.once("close",()=>u(null))})}var F=n({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:_().nullable()}),B=n({groups:d(n({selectable:_().optional(),accounts:d(n({source_id:t().min(1),model_ids:d(t().min(1)).optional()}))}))});function G(e){let s=B.safeParse(e);if(!s.success)return;return s.data.groups.some((r)=>r.selectable!==!1&&r.accounts.some((a)=>a.model_ids===void 0||a.model_ids.length>0))}class C extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;refusal;constructor(e,s,r,a,l,u,g){super(r);this.status=e;this.code=s;this.suggestedModel=a;this.retryAfterMs=l;this.resolutionReason=u;this.refusal=g;this.name="ApiError"}static rateLimitDelayMs(e,s){if(!(e instanceof C)||e.status!==429)return null;return Math.min(60000,Math.max(s,e.retryAfterMs??0))}}var J=["minimal","low","medium","high","xhigh","max"],K=n({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:_(),compatible:_().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:d(n({id:t().min(1),label:t()}))}),V=n({devices:d(K),end_cursor:t().nullish(),has_next_page:_().optional()}),Y=n({id:t().min(1),name:t()}),Z=n({items:d(Y)}),X=n({id:t().min(1),name:t(),main:_(),mine:_(),session_id:t().nullish(),appearance:n({color:t().nullish()}).nullish().catch(null)}),ee=n({items:d(X)}),ne=n({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:d(t()).default([]),is_enabled:_().default(!0)}),te=n({items:d(ne).default([])}),se=n({id:t().min(1),kind:t(),enabled:_(),schedule:n({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:n({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),A=n({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:_(),triggers:d(se).default([])}),oe=n({items:d(A).default([]),end_cursor:t().nullish(),has_next_page:_().optional()}),re=n({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:_()}),ie=n({items:d(re).default([])}),ae=n({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),x=n({tags:d(t()).default([])}),le=c(["linux","macos"]),T=n({id:t().min(1),name:t().min(1),platform:le.nullable(),workers:n({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:n({queued:o().int(),running:o().int()})}),ce=n({machines:d(T)}),de=n({machine:T}),ue=n({deleted:i(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),ge=n({token:n({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),U=ll({machine_id:t().min(1),machine_name:t().min(1)}),he=U.extend({organization_id:t().min(1)}),tn=n({id:t().min(1),name:t().min(1),state:c(["waiting","placed"]),queue_position:o().int().nullable()});var sn=we([n({kind:i("cloud")}),n({kind:c(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function m(e,s,r){let a=e.safeParse(s);if(!a.success)throw new C(502,r,"Reason returned an unexpected response.");return a.data}var pe=n({error:n({type:t(),message:t()})});function b(e,s,r){let a=pe.safeParse(s),l=typeof s.error==="string"?s.error:a.success?a.data.error.type:`http_${e}`,u=typeof s.detail==="string"?s.detail:typeof s.message==="string"?s.message:a.success?a.data.error.message:`Reason request failed (${e}${typeof s.error==="string"?` ${s.error}`:""})`,g=l==="github_connection_required"&&typeof s.connect_url==="string"&&/^https?:\/\//.test(s.connect_url)?` Connect it at ${s.connect_url}`:"",h=r===null||r.trim()===""?NaN:Number(r);return new C(e,l,`${u}${g}`,typeof s.suggested_model==="string"?s.suggested_model:void 0,Number.isFinite(h)&&h>=0?h*1000:void 0,typeof s.resolution_reason==="string"?s.resolution_reason:void 0,typeof s.code==="string"?{code:s.code,...typeof s.billing_path==="string"&&/^\/(?![/\\])/.test(s.billing_path)?{billingPath:s.billing_path}:{}}:void 0)}async function no(e){let s=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),r=await s.json().catch(()=>({}));if(!s.ok)throw b(s.status,r,s.headers.get("retry-after"));return m(he,r,"invalid_machine_ticket")}var fe=n({items:d(n({name:t()}))}),_e=n({name:t(),scope:t(),result:c(["created","updated"]).optional(),warning:n({message:t()}).optional()});class me{options;credentials;constructor(e,s={}){this.options=s;this.credentials=e}trackEvent(e,s={}){}async request(e,s={}){let{status:r,headers:a,json:l}=await this.exchange(e,s);if(r<200||r>299)throw b(r,l,a.get("retry-after"));return l}async exchange(e,s={},r=!1){let a=this.options.fetchImpl??fetch;if(!r&&s.retryUnauthorized!==!1)await this.renewBeforeExpiry(a,s.signal);let l=await a(`${this.credentials.apiOrigin}/v3${e}`,{method:s.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Ir,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...s.raw?{"content-type":s.raw.contentType}:s.body===void 0?{}:{"content-type":"application/json"},...s.headers,...s.ifNoneMatch?{"if-none-match":s.ifNoneMatch}:{}},body:s.raw?s.raw.bytes:s.body===void 0?void 0:JSON.stringify(s.body),signal:s.signal,redirect:s.ifNoneMatch?"manual":"error"}),u=await l.json().catch(()=>({}));if(l.status===401&&!r&&s.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let g=await be({fetchImpl:a,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:s.signal});if(g)return this.credentials=g,this.exchange(e,s,!0)}return{status:l.status,headers:l.headers,json:u}}async renewBeforeExpiry(e,s){let r=this.credentials;if(r.credentialKind==="api_key"||!(Date.parse(r.expiresAt)<=Date.now()+60000))return;let a=await be({fetchImpl:e,path:this.options.credentialsPath,signal:s}).catch(()=>null);if(a&&a.apiOrigin===r.apiOrigin&&a.orgId===r.orgId&&a.clientId===r.clientId)this.credentials=a}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(s){if(s instanceof C&&(s.status===404||s.status===405||s.status===403&&s.code==="endpoint_not_available"))return null;throw s}}addDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(s)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,s=""){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?r:`${r}/${encodeURIComponent(e)}${s}`}async listMachines(){return m(ce,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let s=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return m(de,s,"invalid_machine").machine}async deleteMachine(e){let s=await this.request(this.machinePath(e),{method:"DELETE"});return m(ue,s,"invalid_machine_deletion")}async listSecretNames(e){let s=await this.request(`${this.secretsPath()}?scope=${e}`);return m(fe,s,"invalid_secret_list").items.map((r)=>r.name)}async setSecret(e){let s=await this.request(this.secretsPath(),{method:"POST",body:e});return m(_e,s,"invalid_secret_write")}secretsPath(){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/secrets`}async createMachineToken(e){let s=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return m(ge,s,"invalid_machine_token")}async createMachineEnrollmentTicket(e,s){let r=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:s,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return m(U,r,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(e=AbortSignal.timeout(30000)){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:e})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async registerNetworkTeam(e){await this.request("/network/teams",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:s});return m(Pa,r,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((s)=>typeof s.email==="string"?[{email:s.email,role:typeof s.role==="string"?s.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,s,r={}){let a=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:r.retryUnauthorized,signal:r.signal,body:{...a,...s?{account_key:s}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((s)=>{let r=typeof s.full_name==="string"?s.full_name:typeof s.repo_full_name==="string"?s.repo_full_name:null;if(!r)return[];return[{repo_id:typeof s.repo_id==="string"?s.repo_id:void 0,full_name:r,provider:s.provider==="gitlab"?"gitlab":"github",default_branch:typeof s.default_branch==="string"?s.default_branch:null,private:typeof s.private==="boolean"?s.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),s=Z.safeParse(e);if(!s.success)throw new C(502,"invalid_project_list","Reason returned an unexpected project list.");return s.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return m(ee,e,"invalid_reason_list").items}async openReasonConversation(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return m(n({session_id:t().min(1)}),s,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return m(te,e,"invalid_skill_list").items}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],s=null;for(let r=0;r<50;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${s?`?after=${encodeURIComponent(s)}`:""}`),l=V.safeParse(a);if(!l.success)throw new C(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...l.data.devices),s=l.data.has_next_page?l.data.end_cursor??null:null,!s)break}return e}async listModels(){try{let s=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((l)=>l.hidden!==!0),r=s.filter((l)=>l.available!==!1).map(({reasoning_efforts:l,hidden:u,available:g,...h})=>({...h,...Array.isArray(l)?{reasoning_efforts:J.filter((p)=>l.includes(p))}:{}})),a=new Set(r.map((l)=>l.detail));return{models:r.length>1&&a.size===1?r.map(({detail:l,...u})=>u):r,runnable:r.length>0||s.length===0}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let s=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return k(s.reason_version)?s.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=F.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let s;try{s=G(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:s}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let s=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)s.set("origin",e.origin);s.set("fields",e.fields.join(","));let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${s.toString()}`,{status:a,headers:l,json:u}=await this.exchange(r,e.etag?{ifNoneMatch:e.etag}:{});if(a===304)return null;if(a<200||a>299)throw b(a,u,l.get("retry-after"));return{items:Array.isArray(u.items)?u.items:[],etag:l.get("etag")}}async listSessions(e=50,s,r={}){let a=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:r.status??"active"});if(s)a.set("project_id",s);if(r.origin)a.set("origin",r.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${a.toString()}`)).items??[]}getSession(e,s){let r=s?.fields.length?`?fields=${encodeURIComponent(s.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`)}async prestartSession(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return s?.status==="starting"||s?.status==="ready"}async createSession(e){let s=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(s||e.runtimeProfile){let l=await this.request("/deployment");if(s&&(!Array.isArray(l.session_modes)||!l.session_modes.includes(e.mode??"standard")||!Array.isArray(l.workspace_ownerships)||!l.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(l.experimental_runtime_profiles)||!l.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),a=await this.getSession(r.session_id);if(s){let l=a.session_policy,u=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!l||l.version!==1||l.mode!==(e.mode??"standard")||l.workspaceOwnership!==(e.workspaceOwnership??"managed")||!l.components||u.some((g)=>l.components[g]!==!0))throw await this.cancelSession(r.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&a.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(r.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return a}async getEvents(e,s=-1,r={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${s}&limit=500${r.waitMs?`&wait_ms=${r.waitMs}`:""}`,r.signal?{signal:r.signal}:{})}catch(a){if(!(a instanceof C)||a.status!==403&&a.status!==404)throw a;return{session:await this.getSession(e),items:[],next_seq:s}}}async getMessages(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${s===void 0?"":`&after_seq=${s}`}`)}async getAttachments(e,s){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${s?`?view=${s}`:""}`)).items??[]}catch(r){if(r instanceof C&&(r.status===403||r.status===404))return[];throw r}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let s=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,r=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,a=[s,r].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${a?` (${a})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,s,r={}){if(r.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:s,...r.attachments?.length?{attachments:r.attachments}:{},...r.model?{model:r.model}:{},...r.reasoningEffort?{reasoning_effort:r.reasoningEffort}:{},...r.target?{target:r.target}:{},...r.delivery?{delivery:r.delivery}:{}}})}async steerQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/queued`,{method:"DELETE"})}async getConversation(e){let s=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${r?`?after=${encodeURIComponent(r)}`:""}`);if(s.push(...l.items??[]),!l.has_next_page||!l.end_cursor)break;r=l.end_cursor}return s}createSharedLink(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:s.url,...s.label?{label:s.label}:{},...s.expiresInSeconds!==void 0?{expires_in_seconds:s.expiresInSeconds}:{}}})}sessionAction(e,s,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${s}`,{method:"POST",body:r})}renameSession(e,s){return this.sessionAction(e,"rename",{title:s||null})}moveSessionToProject(e,s){return this.sessionAction(e,"project",{project_id:s})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,s){return this.sessionAction(e,"rewind",{message_id:s.messageId,content:s.content,request_id:s.requestId})}forkSession(e,s){return this.sessionAction(e,"fork",{...s.message?{message:s.message}:{},client_session_id:s.clientSessionId})}cancelSession(e,s={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:s.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,s=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${s}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return m(x,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,s){let r=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:s}});return m(x,r,"invalid_session_tags").tags}async sessionInsight(e,s=!1){let r=await this.request(this.sessionPath(e,s?"/insights/generate":"/insights"),s?{method:"POST",body:{}}:{});return m(ae,r,"invalid_session_insight")}async listAutomations(){let e=[],s=null;for(let r=0;r<20;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${s?`&after=${encodeURIComponent(s)}`:""}`),l=m(oe,a,"invalid_automation_list");if(e.push(...l.items),s=l.has_next_page?l.end_cursor??null:null,!s)break}return e}async createScheduledAutomation(e,s){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,a=m(A,await this.request(r,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${r}/${encodeURIComponent(a.id)}/triggers`,{method:"POST",body:s})}catch(l){throw await this.deleteAutomation(a.id).catch(()=>{return}),l}return a}async setAutomationEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:s}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:s}});return m(n({transcript:t()}),r,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return m(ie,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:s}})}}
|
|
3
|
-
export{
|
|
2
|
+
import{Ra}from"./vm-hands-entry-lite-r131db1f.js";import{R}from"./vm-hands-entry-lite-ys4jhf7n.js";import{W}from"./vm-hands-entry-lite-0xfme8gg.js";import{Q,so,ve,ao}from"./vm-hands-entry-lite-4kb5rq3d.js";import{Ir}from"./vm-hands-entry-lite-crjaacc2.js";import{t,o,_,d,n,ll,we,c,i}from"./vm-hands-entry-lite-bt6skt4h.js";var E=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function k(e){let s=typeof e==="string"?E.exec(e):null;return s?{major:Number(s[1]),minor:Number(s[2])}:null}import{createHash as q,randomBytes as P}from"crypto";import{createInterface as M}from"readline";var v=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var Ge=v.filter((e)=>e!=="network:read"&&e!=="network:write");class y extends Error{oauthCode;constructor(e,s=null){super(e);this.oauthCode=s;this.name="LoginError"}}function Aa(){let e=P(48).toString("base64url"),s=q("sha256").update(e).digest("base64url");return{verifier:e,challenge:s,state:P(32).toString("base64url")}}function z(e,s){let r=typeof e.error==="string"?e.error:null,a=typeof e.error_description==="string"?e.error_description:r?r:s;return new y(a,r)}async function L(e,s,r,a){let l=await r(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:s,signal:a}),u=await l.json().catch(()=>({}));if(!l.ok)throw z(u,`OAuth token request failed (${l.status})`);return u}var j=1e4;async function D(e,s={}){let r=s.fetchImpl??fetch,a=await L(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),r,AbortSignal.timeout(j)).catch((u)=>{if(u instanceof Error&&u.name==="TimeoutError")throw new y("Reason did not answer the login refresh in time. Check the network and retry.");throw u});if(typeof a.access_token!=="string"||typeof a.refresh_token!=="string"||typeof a.expires_in!=="number")throw new y("Reason returned an incomplete refreshed login.");let l={...e,accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:new Date(Date.now()+a.expires_in*1000).toISOString(),scopes:typeof a.scope==="string"?a.scope.split(/\s+/).filter(Boolean):e.scopes};return so(l,s.path??Q()),l}var w=new Map,N=2000,H=100;function I(e,s){if(!s)return e;if(s.aborted)return Promise.reject(s.reason);return new Promise((r,a)=>{let l=()=>a(s.reason);s.addEventListener("abort",l,{once:!0}),e.then(r,a).finally(()=>s.removeEventListener("abort",l))})}async function be(e={}){let s=e.path??Q(),r=ve(s);if(!r)return null;let a=e.apiOrigin??R(process.env,"REASON_API_URL")?.trim();if(a&&!W(r.apiOrigin,new URL(a).origin))return null;if(!(Date.parse(r.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&r.accessToken!==e.refused))return r;let u=[s,r.apiOrigin,r.clientId,r.refreshToken].join("\x00"),g=w.get(u);if(g)return I(g,e.signal);let h;return h=D(r,{fetchImpl:e.fetchImpl,path:s}).catch(async(p)=>{if(!(p instanceof y)||p.oauthCode!=="invalid_grant"&&p.oauthCode!=="invalid_client")throw p;let S=(f)=>f!==null&&(p.oauthCode==="invalid_client"?f.clientId!==r.clientId:f.refreshToken!==r.refreshToken),O=Date.now()+N;while(!S(ve(s))&&Date.now()<O)await new Promise((f)=>setTimeout(f,H));if(S(ve(s)))return be({fetchImpl:e.fetchImpl,path:s});return ao(s),null}).finally(()=>{if(w.get(u)===h)w.delete(u)}),w.set(u,h),I(h,e.signal)}function Pa(e,s){return new Promise((r)=>{let a=M({input:e}),l=!1,u=(h)=>{if(l)return;l=!0,s.removeEventListener("abort",g),a.close(),e.pause(),r(h)},g=()=>u(null);s.addEventListener("abort",g,{once:!0}),a.once("line",(h)=>u(h)),a.once("close",()=>u(null))})}var F=n({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:_().nullable()}),B=n({groups:d(n({selectable:_().optional(),accounts:d(n({source_id:t().min(1),model_ids:d(t().min(1)).optional()}))}))});function G(e){let s=B.safeParse(e);if(!s.success)return;return s.data.groups.some((r)=>r.selectable!==!1&&r.accounts.some((a)=>a.model_ids===void 0||a.model_ids.length>0))}class C extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;refusal;constructor(e,s,r,a,l,u,g){super(r);this.status=e;this.code=s;this.suggestedModel=a;this.retryAfterMs=l;this.resolutionReason=u;this.refusal=g;this.name="ApiError"}static rateLimitDelayMs(e,s){if(!(e instanceof C)||e.status!==429)return null;return Math.min(60000,Math.max(s,e.retryAfterMs??0))}}var J=["minimal","low","medium","high","xhigh","max"],K=n({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:_(),compatible:_().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:d(n({id:t().min(1),label:t()}))}),V=n({devices:d(K),end_cursor:t().nullish(),has_next_page:_().optional()}),Y=n({id:t().min(1),name:t()}),Z=n({items:d(Y)}),X=n({id:t().min(1),name:t(),main:_(),mine:_(),session_id:t().nullish(),appearance:n({color:t().nullish()}).nullish().catch(null)}),ee=n({items:d(X)}),ne=n({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:d(t()).default([]),is_enabled:_().default(!0)}),te=n({items:d(ne).default([])}),se=n({id:t().min(1),kind:t(),enabled:_(),schedule:n({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:n({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),A=n({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:_(),triggers:d(se).default([])}),oe=n({items:d(A).default([]),end_cursor:t().nullish(),has_next_page:_().optional()}),re=n({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:_()}),ie=n({items:d(re).default([])}),ae=n({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),x=n({tags:d(t()).default([])}),le=c(["linux","macos"]),T=n({id:t().min(1),name:t().min(1),platform:le.nullable(),workers:n({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:n({queued:o().int(),running:o().int()})}),ce=n({machines:d(T)}),de=n({machine:T}),ue=n({deleted:i(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),ge=n({token:n({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),U=ll({machine_id:t().min(1),machine_name:t().min(1)}),he=U.extend({organization_id:t().min(1)}),tn=n({id:t().min(1),name:t().min(1),state:c(["waiting","placed"]),queue_position:o().int().nullable()});var sn=we([n({kind:i("cloud")}),n({kind:c(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function m(e,s,r){let a=e.safeParse(s);if(!a.success)throw new C(502,r,"Reason returned an unexpected response.");return a.data}var pe=n({error:n({type:t(),message:t()})});function b(e,s,r){let a=pe.safeParse(s),l=typeof s.error==="string"?s.error:a.success?a.data.error.type:`http_${e}`,u=typeof s.detail==="string"?s.detail:typeof s.message==="string"?s.message:a.success?a.data.error.message:`Reason request failed (${e}${typeof s.error==="string"?` ${s.error}`:""})`,g=l==="github_connection_required"&&typeof s.connect_url==="string"&&/^https?:\/\//.test(s.connect_url)?` Connect it at ${s.connect_url}`:"",h=r===null||r.trim()===""?NaN:Number(r);return new C(e,l,`${u}${g}`,typeof s.suggested_model==="string"?s.suggested_model:void 0,Number.isFinite(h)&&h>=0?h*1000:void 0,typeof s.resolution_reason==="string"?s.resolution_reason:void 0,typeof s.code==="string"?{code:s.code,...typeof s.billing_path==="string"&&/^\/(?![/\\])/.test(s.billing_path)?{billingPath:s.billing_path}:{}}:void 0)}async function io(e){let s=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),r=await s.json().catch(()=>({}));if(!s.ok)throw b(s.status,r,s.headers.get("retry-after"));return m(he,r,"invalid_machine_ticket")}var fe=n({items:d(n({name:t()}))}),_e=n({name:t(),scope:t(),result:c(["created","updated"]).optional(),warning:n({message:t()}).optional()});class me{options;credentials;constructor(e,s={}){this.options=s;this.credentials=e}trackEvent(e,s={}){}async request(e,s={}){let{status:r,headers:a,json:l}=await this.exchange(e,s);if(r<200||r>299)throw b(r,l,a.get("retry-after"));return l}async exchange(e,s={},r=!1){let a=this.options.fetchImpl??fetch;if(!r&&s.retryUnauthorized!==!1)await this.renewBeforeExpiry(a,s.signal);let l=await a(`${this.credentials.apiOrigin}/v3${e}`,{method:s.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Ir,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...s.raw?{"content-type":s.raw.contentType}:s.body===void 0?{}:{"content-type":"application/json"},...s.headers,...s.ifNoneMatch?{"if-none-match":s.ifNoneMatch}:{}},body:s.raw?s.raw.bytes:s.body===void 0?void 0:JSON.stringify(s.body),signal:s.signal,redirect:s.ifNoneMatch?"manual":"error"}),u=await l.json().catch(()=>({}));if(l.status===401&&!r&&s.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let g=await be({fetchImpl:a,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:s.signal});if(g)return this.credentials=g,this.exchange(e,s,!0)}return{status:l.status,headers:l.headers,json:u}}async renewBeforeExpiry(e,s){let r=this.credentials;if(r.credentialKind==="api_key"||!(Date.parse(r.expiresAt)<=Date.now()+60000))return;let a=await be({fetchImpl:e,path:this.options.credentialsPath,signal:s}).catch(()=>null);if(a&&a.apiOrigin===r.apiOrigin&&a.orgId===r.orgId&&a.clientId===r.clientId)this.credentials=a}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(s){if(s instanceof C&&(s.status===404||s.status===405||s.status===403&&s.code==="endpoint_not_available"))return null;throw s}}addDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(s)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,s=""){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?r:`${r}/${encodeURIComponent(e)}${s}`}async listMachines(){return m(ce,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let s=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return m(de,s,"invalid_machine").machine}async deleteMachine(e){let s=await this.request(this.machinePath(e),{method:"DELETE"});return m(ue,s,"invalid_machine_deletion")}async listSecretNames(e){let s=await this.request(`${this.secretsPath()}?scope=${e}`);return m(fe,s,"invalid_secret_list").items.map((r)=>r.name)}async setSecret(e){let s=await this.request(this.secretsPath(),{method:"POST",body:e});return m(_e,s,"invalid_secret_write")}secretsPath(){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/secrets`}async createMachineToken(e){let s=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return m(ge,s,"invalid_machine_token")}async createMachineEnrollmentTicket(e,s){let r=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:s,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return m(U,r,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(e=AbortSignal.timeout(30000)){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:e})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async registerNetworkTeam(e){await this.request("/network/teams",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:s});return m(Ra,r,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((s)=>typeof s.email==="string"?[{email:s.email,role:typeof s.role==="string"?s.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,s,r={}){let a=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:r.retryUnauthorized,signal:r.signal,body:{...a,...s?{account_key:s}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((s)=>{let r=typeof s.full_name==="string"?s.full_name:typeof s.repo_full_name==="string"?s.repo_full_name:null;if(!r)return[];return[{repo_id:typeof s.repo_id==="string"?s.repo_id:void 0,full_name:r,provider:s.provider==="gitlab"?"gitlab":"github",default_branch:typeof s.default_branch==="string"?s.default_branch:null,private:typeof s.private==="boolean"?s.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),s=Z.safeParse(e);if(!s.success)throw new C(502,"invalid_project_list","Reason returned an unexpected project list.");return s.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return m(ee,e,"invalid_reason_list").items}async openReasonConversation(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return m(n({session_id:t().min(1)}),s,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return m(te,e,"invalid_skill_list").items}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],s=null;for(let r=0;r<50;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${s?`?after=${encodeURIComponent(s)}`:""}`),l=V.safeParse(a);if(!l.success)throw new C(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...l.data.devices),s=l.data.has_next_page?l.data.end_cursor??null:null,!s)break}return e}async listModels(){try{let s=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((l)=>l.hidden!==!0),r=s.filter((l)=>l.available!==!1).map(({reasoning_efforts:l,hidden:u,available:g,...h})=>({...h,...Array.isArray(l)?{reasoning_efforts:J.filter((p)=>l.includes(p))}:{}})),a=new Set(r.map((l)=>l.detail));return{models:r.length>1&&a.size===1?r.map(({detail:l,...u})=>u):r,runnable:r.length>0||s.length===0}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let s=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return k(s.reason_version)?s.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=F.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let s;try{s=G(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:s}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let s=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)s.set("origin",e.origin);s.set("fields",e.fields.join(","));let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${s.toString()}`,{status:a,headers:l,json:u}=await this.exchange(r,e.etag?{ifNoneMatch:e.etag}:{});if(a===304)return null;if(a<200||a>299)throw b(a,u,l.get("retry-after"));return{items:Array.isArray(u.items)?u.items:[],etag:l.get("etag")}}async listSessions(e=50,s,r={}){let a=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:r.status??"active"});if(s)a.set("project_id",s);if(r.origin)a.set("origin",r.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${a.toString()}`)).items??[]}getSession(e,s){let r=s?.fields.length?`?fields=${encodeURIComponent(s.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`)}async prestartSession(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return s?.status==="starting"||s?.status==="ready"}async createSession(e){let s=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(s||e.runtimeProfile){let l=await this.request("/deployment");if(s&&(!Array.isArray(l.session_modes)||!l.session_modes.includes(e.mode??"standard")||!Array.isArray(l.workspace_ownerships)||!l.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(l.experimental_runtime_profiles)||!l.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),a=await this.getSession(r.session_id);if(s){let l=a.session_policy,u=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!l||l.version!==1||l.mode!==(e.mode??"standard")||l.workspaceOwnership!==(e.workspaceOwnership??"managed")||!l.components||u.some((g)=>l.components[g]!==!0))throw await this.cancelSession(r.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&a.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(r.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return a}async getEvents(e,s=-1,r={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${s}&limit=500${r.waitMs?`&wait_ms=${r.waitMs}`:""}`,r.signal?{signal:r.signal}:{})}catch(a){if(!(a instanceof C)||a.status!==403&&a.status!==404)throw a;return{session:await this.getSession(e),items:[],next_seq:s}}}async getMessages(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${s===void 0?"":`&after_seq=${s}`}`)}async getAttachments(e,s){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${s?`?view=${s}`:""}`)).items??[]}catch(r){if(r instanceof C&&(r.status===403||r.status===404))return[];throw r}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let s=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,r=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,a=[s,r].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${a?` (${a})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,s,r={}){if(r.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:s,...r.attachments?.length?{attachments:r.attachments}:{},...r.model?{model:r.model}:{},...r.reasoningEffort?{reasoning_effort:r.reasoningEffort}:{},...r.target?{target:r.target}:{},...r.delivery?{delivery:r.delivery}:{}}})}async steerQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/queued`,{method:"DELETE"})}async getConversation(e){let s=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${r?`?after=${encodeURIComponent(r)}`:""}`);if(s.push(...l.items??[]),!l.has_next_page||!l.end_cursor)break;r=l.end_cursor}return s}createSharedLink(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:s.url,...s.label?{label:s.label}:{},...s.expiresInSeconds!==void 0?{expires_in_seconds:s.expiresInSeconds}:{}}})}sessionAction(e,s,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${s}`,{method:"POST",body:r})}renameSession(e,s){return this.sessionAction(e,"rename",{title:s||null})}moveSessionToProject(e,s){return this.sessionAction(e,"project",{project_id:s})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,s){return this.sessionAction(e,"rewind",{message_id:s.messageId,content:s.content,request_id:s.requestId})}forkSession(e,s){return this.sessionAction(e,"fork",{...s.message?{message:s.message}:{},client_session_id:s.clientSessionId})}cancelSession(e,s={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:s.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,s=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${s}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return m(x,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,s){let r=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:s}});return m(x,r,"invalid_session_tags").tags}async sessionInsight(e,s=!1){let r=await this.request(this.sessionPath(e,s?"/insights/generate":"/insights"),s?{method:"POST",body:{}}:{});return m(ae,r,"invalid_session_insight")}async listAutomations(){let e=[],s=null;for(let r=0;r<20;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${s?`&after=${encodeURIComponent(s)}`:""}`),l=m(oe,a,"invalid_automation_list");if(e.push(...l.items),s=l.has_next_page?l.end_cursor??null:null,!s)break}return e}async createScheduledAutomation(e,s){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,a=m(A,await this.request(r,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${r}/${encodeURIComponent(a.id)}/triggers`,{method:"POST",body:s})}catch(l){throw await this.deleteAutomation(a.id).catch(()=>{return}),l}return a}async setAutomationEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:s}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:s}});return m(n({transcript:t()}),r,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return m(ie,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:s}})}}
|
|
3
|
+
export{Aa,be,Pa,C,io,me};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{w,ye}from"./vm-hands-entry-lite-
|
|
2
|
+
import{w,ye}from"./vm-hands-entry-lite-0xfme8gg.js";import{wt}from"./vm-hands-entry-lite-peyr9y6z.js";import{randomBytes as f}from"crypto";import{chmodSync as c,existsSync as a,lstatSync as p,mkdirSync as u,readFileSync as g,renameSync as m,unlinkSync as l,writeFileSync as d}from"fs";import{homedir as y}from"os";import{dirname as S,join as o}from"path";function Q(r=process.env,n=y()){let e=r.XDG_CONFIG_HOME?.trim()||o(n,".config"),t=w({env:r})==="staging"?["staging"]:[];return o(wt(e,...t),"credentials.json")}function so(r,n=Q()){return u(S(n),{recursive:!0,mode:448}),d(n,`${JSON.stringify(r,null,2)}
|
|
3
3
|
`,{mode:384}),c(n,384),n}function ve(r=Q()){if(!a(r))return null;try{let n=g(r,"utf8"),e=JSON.parse(n);if(typeof e.apiOrigin!=="string"||typeof e.clientId!=="string"||typeof e.accessToken!=="string"||typeof e.refreshToken!=="string"||typeof e.expiresAt!=="string"||typeof e.orgId!=="string"||!Array.isArray(e.scopes))return null;let i=new URL(e.apiOrigin).origin,t=ye(i);if(t!==i)k(r,n,t);return{apiOrigin:t,clientId:e.clientId,accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,scopes:e.scopes.filter((s)=>typeof s==="string"),orgId:e.orgId}}catch{return null}}function k(r,n,e){let i=`${r}.${process.pid}.${f(6).toString("hex")}.tmp`;try{let t=p(r);if(!t.isFile()||process.platform!=="win32"&&t.uid!==process.geteuid?.())return;let s=JSON.parse(n);if(d(i,`${JSON.stringify({...s,apiOrigin:e},null,2)}
|
|
4
|
-
`,{mode:384,flag:"wx"}),c(i,384),g(r,"utf8")!==n)throw Error("credentials_changed");m(i,r)}catch{try{l(i)}catch{}}}function
|
|
5
|
-
export{Q,
|
|
4
|
+
`,{mode:384,flag:"wx"}),c(i,384),g(r,"utf8")!==n)throw Error("credentials_changed");m(i,r)}catch{try{l(i)}catch{}}}function ao(r=Q()){if(!a(r))return!1;return l(r),!0}
|
|
5
|
+
export{Q,so,ve,ao};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{te}from"./vm-hands-entry-lite-
|
|
3
|
-
`)}).finally(()=>{if(a.get(h.port)===k)a.delete(h.port)})},dispose(){for(let p of a.values())p.abort();a.clear()}}}class lr extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var le=256,J=new Map,pe="preview.serve.v1",M=new Map;function ue(e){let a=M.get(e.operation_id);if(a){if(a.claim!==e)throw D("process_authority_lost");return a}if(M.size>=le)throw D("process_journal_capacity");let p={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return M.set(e.operation_id,p),p}function ae(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ce=(e)=>new Promise((a)=>setTimeout(a,e)),D=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function Ve(e=s(),a=He()){let p=Le(gt({},e)),l=We(Et(e),p),[E,...h]=l.split(Ne);return{directory:A(a,l,"processes"),previous:[A(p,"processes"),...E==="reason"?[A(a,"ara",...h,"processes")]:[]]}}function He(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=qc();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function
|
|
4
|
-
export{
|
|
2
|
+
import{te}from"./vm-hands-entry-lite-hpw27zfb.js";import{U,H,T}from"./vm-hands-entry-lite-bbjsnjct.js";import{ge,$t,oi,Po,Ro,ur}from"./vm-hands-entry-lite-cy8yc9gb.js";import{gt}from"./vm-hands-entry-lite-1as6h9ed.js";import{v,pr,Io,ht,ft}from"./vm-hands-entry-lite-sxnvhzy5.js";import{b,m}from"./vm-hands-entry-lite-2927z566.js";import{s,Et,qc}from"./vm-hands-entry-lite-tzv8s0e7.js";import{Xi,I,t,V,o,_,cl,Rt,_a,d,n,we,P,$e,c,i,Yi}from"./vm-hands-entry-lite-bt6skt4h.js";import{Ye,G}from"./vm-hands-entry-lite-04nx5y4f.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{randomUUID as X}from"crypto";import{spawn as ke}from"child_process";import{existsSync as Y,lstatSync as de,mkdirSync as Oe,readFileSync as Me,realpathSync as q,rmSync as Te,writeFileSync as je}from"fs";import{dirname as Le,join as A,relative as We,sep as Ne}from"path";var he=["process.run.v1","process.full.v1"],be=600000,ve=1800000,ye=20000,re="process.cancel.v1",oe=n({action:i("start"),request_id:t().uuid(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),cwd:t().min(1).max(4096).refine((e)=>!e.includes("\x00")&&!e.startsWith("/")&&!e.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:c(["host","confined"]).default("host"),timeout_ms:o().int().min(1000).max(ve).default(be).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),B={device_id:t().uuid(),root_id:t().uuid()},Se=P("action",[oe.extend(B),n({...B,action:i("inspect"),process_id:t().uuid(),after:o().int().min(0).default(0),wait_ms:o().int().min(0).max(ye).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),n({...B,action:i("cancel"),process_id:t().uuid()}).strict()]),qe=Xi(Se,{io:"input"}),Je=oe.extend({process_brain_fence:t().uuid(),process_expires_at:I.datetime()}).strict(),W=n({version:i(1),process_id:t().uuid(),state:c(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:o().int().nullable(),first_cursor:o().int().min(0),next_cursor:o().int().min(0),truncated:_(),observed_at:I.datetime(),output:d(n({cursor:o().int().min(1),stream:c(["stdout","stderr"]),text:t().max(32768)}).strict()).max(128)}).strict().refine((e)=>{if(Buffer.byteLength(JSON.stringify(e))>1e5||e.next_cursor<e.first_cursor-1)return!1;if((e.state==="starting"||e.state==="running"||e.state==="uncertain")&&e.exit_code!==null)return!1;if(e.state==="exited"&&(e.exit_code===null||e.exit_code<0||e.exit_code>255))return!1;if(e.state==="cancelled"&&e.exit_code!==130||e.state==="expired"&&e.exit_code!==124)return!1;let p=e.first_cursor-1;for(let l of e.output){if(l.cursor<=p||l.cursor>e.next_cursor)return!1;p=l.cursor}return!0});function Qn(e){return he.includes(e)}var ze=n({operation_constraints:$e(t(),Rt())}),Ge=n({ready:i(!0),version:i(1),execution_mode:c(["host","confined"]),max_timeout_ms:o().int().min(1000).optional()});var xe=n({version:i(1),process_id:t().uuid(),state:c(["queued","cancelled_before_start","not_started"]),exit_code:cl(),output:d(_a()).length(0),first_cursor:i(0),next_cursor:i(0),truncated:i(!1),cancellation_requested:i(!1),reason_code:c(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:I.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),Pe=n({...W.shape,state:c(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:I.datetime().optional(),expires_at:I.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:_(),reason_code:t().nullable().optional(),execution_authority:i("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:n({cause:i("brain_generation_changed"),terminal_confirmed:_(),next_step:c(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:W.shape.state.or(i("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),Be=Xi(Pe),Fe=we([W,xe.refine((e)=>e.state==="cancelled_before_start")]),F=n({version:i(1),process_id:t().uuid(),state:c(["exited","cancelled","expired"]),exit_code:o().int().min(0).max(255),observed_at:I.datetime()}).strict().refine((e)=>(e.state!=="cancelled"||e.exit_code===130)&&(e.state!=="expired"||e.exit_code===124)),Ee=n({process_terminal_observation:F}).strict();function Ba(e,a){let p=Ee.safeParse(e);return p.success&&p.data.process_terminal_observation.process_id===a?p.data:null}var Fa="preview.serve.v1",ja=43200000;var Ha=3,ne="preview.open.v1",se=1,yo="gid_proxy_v1",Ua="egress",wo=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,Re=n({version:i(yo),allowed_domains:d(t().max(260).regex(wo)).max(1024)}).strict(),Ie=Yi((e)=>te(e)!==null,"invalid workspace"),De=n({version:i(1),request_id:V(),session_id:V(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),port:o().int().min(1024).max(65535),workspace:Ie,egress:Re.optional()}).strict(),za=De.extend({expires_at:I.datetime()}).strict();var Ce=4,Ae=5000;function K(e,a,p){let l=null;try{l=pr(e)}catch{}Io({deviceRelayUrl:l?.deviceRelayUrl??"",binding:l?.binding??null,jobId:a,port:l?.binding.port??0,reason:l?p:"binding_invalid"})}function ie(e){let a=new Map;return{open(p){let l=(w)=>K(p,e.claim.operation_id,w),E;try{E=pr(p)}catch{return l("binding_invalid")}let{binding:h,deviceRelayUrl:N}=E,S=e.claim.owner;if(!S||h.organizationId!==S.organization_id||h.userId!==S.user_id||h.deviceId!==S.device_id||h.rootId!==e.claim.root_id||h.jobId!==e.claim.operation_id||h.fenceId!==e.claim.operation_id||h.generation!==se||h.expiresAtMs>Math.min(Date.now()+v.lifetimeMs+Ae,e.expiresAtMs))return l("binding_mismatch");if(h.expiresAtMs<=Date.now())return l("binding_expired");if(a.get(h.port)?.abort(),a.delete(h.port),a.size>=Ce)return l("preview_capacity");let k=new AbortController;a.set(h.port,k);let y=ft({binding:h,deniedPorts:e.deniedPorts,readCurrentJob:async()=>{if(k.signal.aborted)return null;let w=await e.inspect();return w?{binding:h,executorLaunchId:e.executorLaunchId,job:w}:null}});ht({binding:h,deviceRelayUrl:N,port:y,signal:k.signal}).then((w)=>w.closed,(w)=>{let x=w instanceof Error?w.message:"preview_failed";if(x!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:h.jobId,port:h.port,reason_code:x})}
|
|
3
|
+
`)}).finally(()=>{if(a.get(h.port)===k)a.delete(h.port)})},dispose(){for(let p of a.values())p.abort();a.clear()}}}class lr extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var le=256,J=new Map,pe="preview.serve.v1",M=new Map;function ue(e){let a=M.get(e.operation_id);if(a){if(a.claim!==e)throw D("process_authority_lost");return a}if(M.size>=le)throw D("process_journal_capacity");let p={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return M.set(e.operation_id,p),p}function ae(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ce=(e)=>new Promise((a)=>setTimeout(a,e)),D=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function Ve(e=s(),a=He()){let p=Le(gt({},e)),l=We(Et(e),p),[E,...h]=l.split(Ne);return{directory:A(a,l,"processes"),previous:[A(p,"processes"),...E==="reason"?[A(a,"ara",...h,"processes")]:[]]}}function He(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=qc();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function ei(e){if(!e.claim.owner||e.signal.aborted||e.expiresAtMs<=Date.now())throw D("process_authority_lost");let a=ue(e.claim);if(a.executing)throw D("process_busy");if(a.executing=!0,a.cancelRequested)return a.phase="settling",ae(e.claim.operation_id);a.phase="starting";let p=e.journals??Ve();Oe(p.directory,{recursive:!0,mode:448});let l=$t({runtimeDirectory:q(p.directory),previousRuntimeDirectories:(p.previous??[]).filter((u)=>Y(u)).map((u)=>q(u)),root:e.root,runId:JSON.stringify([e.claim.owner,e.claim.run_id,e.claim.root_id,e.claim.operation_id]),maxScopes:le,folders:[e.root,e.cwd]});try{for(let u of[e.root,e.cwd])if(!ge(q(u),l.journalDirectory))throw new r("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(u){throw l.disposeSocket(),u}let E=de(l.journalDirectory),h=e.claim.capability===pe,N=()=>J.set(e.claim.operation_id,{path:l.journalDirectory,ino:E.ino,dev:E.dev,anyCompletion:h}),S=l.launchDirectory,k=A(S,"config.json"),y={url:"",transport:"local_job_ipc",directShell:{mode:e.mode,executable:e.shell,jobId:e.claim.operation_id},workerVersion:U,protocolVersion:2,workerArtifactSha256:T,workerEntrypoint:H,targetGeneration:1,fenceId:X(),...process.platform==="win32"?{bashExecutable:Ye()}:{},workRoot:e.root,workspaceAliasPath:e.root,repoPath:e.cwd,jobEnvPath:A(S,"unused.env"),replSocketPath:A(S,"unused.sock"),readyPath:A(S,"ready.json"),directTerminalReceiptPath:A(S,"terminal.json"),launchId:X(),expiresAtMs:e.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:l.journalDirectory,scopeId:l.scopeId},jobControlSocketPath:l.socketPath,...e.prefix?{bashCommandPrefix:e.prefix}:{},...e.jobsUser?{jobsUser:e.jobsUser}:{}},w;try{je(k,JSON.stringify(y),{mode:384});let u=Po({configPath:k,root:e.cwd,grantedRoot:e.root,workRoot:e.root,temporaryDirectory:S});w=e.spawnWorker?.(k,y)??ke(u.command,u.args,{...u.options,env:e.environment,stdio:[Ro,"ignore","ignore"]})}catch(u){throw l.disposeSocket(),u}let x=!1,z=new Promise((u,g)=>{w.once("exit",(f)=>{x=!0,u(f)}),w.once("error",(f)=>{x=!0,g(f)})});z.catch(()=>{});let me={root:e.root,runId:e.claim.run_id,scopeId:l.scopeId,socketPath:l.socketPath,generation:1,fenceId:y.fenceId,executorLaunchId:y.launchId,expiresAtMs:y.expiresAtMs},O=async(u)=>{let g=await oi(me,{type:"job",version:2,generation:1,id:X(),jobId:e.claim.operation_id,...u==="start"?{action:u,input:{script:e.command,leaseExpiresAtMs:e.expiresAtMs}}:u==="inspect"?{action:u,input:{after:0}}:u==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:u,input:{}}},new AbortController().signal);if(!g.ok)throw D(g.error);return g.job},j=!1,L=!1,Q,Z=()=>{j=!0,ur(w,"SIGTERM")};e.signal.addEventListener("abort",Z,{once:!0});let C,ee=0,_e=async(u)=>{let g=[...u.output],f={version:1,process_id:e.claim.operation_id,state:u.state,exit_code:u.exitCode,first_cursor:u.firstCursor,next_cursor:u.nextCursor,truncated:u.truncated,output:g,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(f))>90000&&g.length)g.shift(),f.truncated=!0,f.first_cursor=g[0]?.cursor??f.next_cursor+1;C=W.parse(f),await e.emit(C),ee=Date.now()};try{let u=Math.min(Date.now()+1e4,e.expiresAtMs);while(!Y(y.readyPath)){if(x)throw new r("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if(e.signal.aborted||Date.now()>=u)throw D("process_start_unconfirmed");await ce(25)}let g=JSON.parse(Me(y.readyPath,"utf8"));if(g.launchId!==y.launchId||g.fenceId!==y.fenceId||g.workerArtifactSha256!==T)throw D();if(e.signal.throwIfAborted(),a.cancelRequested)return ae(e.claim.operation_id);let f;try{L=!0,f=await O("start")}catch(R){if(!(R instanceof r)||R.code!=="hands_job_result_unknown")throw R;f=await O("inspect")}if(a.phase="running",a.cancel=async()=>{await O("cancel")},h&&e.preview)a.tunnels=ie({claim:e.claim,executorLaunchId:y.launchId,expiresAtMs:e.expiresAtMs,deniedPorts:e.preview.deniedPorts,inspect:async()=>a.phase==="running"&&!x?await O("probe"):null});if(a.cancelRequested)await a.cancel(),f=await O("inspect");for(;;){if(!["starting","running"].includes(f.state))a.phase="settling",a.cancel=void 0;if(!C||C.state!==f.state||C.next_cursor!==f.nextCursor&&Date.now()-ee>=5000)await _e(f);if(!["starting","running"].includes(f.state))break;if(e.signal.aborted||x)throw D();await ce(1000);try{f=await O("inspect"),Q=void 0}catch(R){if(!(R instanceof r)||R.code!=="hands_job_result_unknown"||e.signal.aborted||x||Date.now()-(Q??=Date.now())>120000)throw R}}if(!C||C.state==="uncertain")throw D();return C}finally{if(a.phase="settling",a.cancel=void 0,a.tunnels?.dispose(),a.tunnels=void 0,await a.cancelInFlight?.catch(()=>{}),e.signal.removeEventListener("abort",Z),!x&&!j)ur(w,"SIGTERM");let u,g=await Promise.race([z.then((f)=>({code:f})),new Promise((f)=>{u=setTimeout(()=>f(null),6000)})]).finally(()=>{clearTimeout(u)});if(!g){try{ur(w,"SIGKILL")}catch{}try{await z}finally{if(x)l.disposeSocket()}throw D("process_cleanup_unconfirmed")}try{if((j||e.signal.aborted)&&g.code===0&&L){b(S);let f=JSON.parse(m(y.directTerminalReceiptPath)),R=F.safeParse(f.observation);if(Object.keys(f).length===4&&f.launch_id===y.launchId&&f.fence_id===y.fenceId&&f.scope_id===l.scopeId&&R.success&&R.data.process_id===e.claim.operation_id){if(h)N();throw new lr(R.data)}}}catch(f){if(f instanceof lr)throw f}finally{if(x)l.disposeSocket()}if(g.code!==0&&!j&&L)throw D("process_cleanup_unconfirmed");if(!j&&g.code===0&&(C&&["exited","cancelled","expired"].includes(C.state)||!L&&a.cancelRequested)||h&&g.code===0&&!L)N()}}async function bo(e,a){if(a.kind===ne&&e.capability===pe){let E=M.get(e.operation_id);if(E?.claim===e&&E.tunnels)E.tunnels.open(a.payload);else K(a.payload,e.operation_id,"server_not_running");return!0}if(a.kind!==re||!Qn(e.capability)||!e.owner||a.payload.process_id!==e.operation_id)return!1;let p=M.get(e.operation_id);if(p&&p.claim!==e)return!1;let l=ue(e);if(l.cancelRequested=!0,l.phase==="running"&&l.cancel)l.cancelInFlight??=l.cancel(),await l.cancelInFlight;return!0}function ti(e,a){M.delete(e);let p=J.get(e);if(!p||a!=="succeeded"&&!p.anyCompletion)return J.delete(e),!1;try{let l=de(p.path);if(!l.isDirectory()||l.isSymbolicLink()||l.ino!==p.ino||l.dev!==p.dev||!G(l)||q(p.path)!==p.path||Y(A(p.path,"owner.lock")))return!1;return Te(p.path,{recursive:!0}),J.delete(e),!0}catch{return!1}}
|
|
4
|
+
export{Qn,Ba,Fa,ja,Ha,yo,Ua,wo,za,lr,ei,bo,ti};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{L}from"./vm-hands-entry-lite-
|
|
3
|
-
`).at(-1)??"",o=[];for(let i of r.split(n?";":":")){let s=i.trim();if(n?!u.isAbsolute(s):!s.startsWith("/"))continue;if(s.includes("\x00"))continue;if(L(s))continue;o.push(s)}return h(o)}function
|
|
2
|
+
import{L}from"./vm-hands-entry-lite-hpe54h0b.js";import{Y,Tt,Me,Dt,Be}from"./vm-hands-entry-lite-04nx5y4f.js";import{spawn as y}from"child_process";import{existsSync as p,mkdirSync as T,readFileSync as _,writeFileSync as A}from"fs";import{homedir as g}from"os";import{basename as H,delimiter as E,join as f,win32 as u}from"path";var Ft=process.platform==="win32"?Tt("win32"):"/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",P=Ft.split(E),R=5000,S=65536,O=new Set(["zsh","bash"]),b=[[".local","bin"],[".bun","bin"],[".cargo","bin"],["go","bin"]],x=(t,e)=>new Promise((n,r)=>{let o;try{o=y(t,[...e],{...Me(),stdio:["ignore","pipe","ignore"]}),Dt(o)}catch(c){r(c);return}let i=[],s=0,a=null,d=(c)=>{a??=Error(c);try{if(o.pid!==void 0)Be(o.pid,"SIGKILL")}catch{}},m=setTimeout(()=>d("login_shell_timeout"),R);o.stdout?.on("data",(c)=>{if(s+=c.length,s>S)d("login_shell_output_too_large");else i.push(c)}),o.once("error",(c)=>{clearTimeout(m),r(c)}),o.once("close",(c)=>{if(clearTimeout(m),a)r(a);else if(c!==0)r(Error("login_shell_exit_nonzero"));else n(Buffer.concat(i).toString("utf8"))})});function w(t){return typeof t==="string"&&t.startsWith("/")&&!t.includes("\x00")&&O.has(H(t))}function h(t){let e=new Set,n=[];for(let r of t){if(e.has(r))continue;e.add(r),n.push(r)}return n}function _i(t,e=process.platform){let n=e==="win32",r=t.split(`
|
|
3
|
+
`).at(-1)??"",o=[];for(let i of r.split(n?";":":")){let s=i.trim();if(n?!u.isAbsolute(s):!s.startsWith("/"))continue;if(s.includes("\x00"))continue;if(L(s))continue;o.push(s)}return h(o)}function Do(t){let e=t?.home??g(),n=t?.directoryExists??p,r=b.map((o)=>f(e,...o)).filter((o)=>{try{return n(o)}catch{return!1}});return h([...r,...process.platform==="win32"?_i(process.env.PATH??process.env.Path??""):[],...P]).join(E)}async function C(t){let e=t?.shell??process.env.SHELL,n=()=>({path:Do({home:t?.home,directoryExists:t?.directoryExists}),source:"fallback"});if(process.platform==="win32"||!w(e))return n();let r;try{r=await(t?.runLoginShell??x)(e,["-lic",'printf %s "$PATH"'])}catch{return n()}if(Buffer.byteLength(r,"utf8")>S)return n();let o=_i(r);if(o.length===0)return n();return{path:h([...o,...P]).join(":"),source:"login_shell"}}function lc(t){let e=null;return()=>(e??=C(t),e)}function l(t){if(t===void 0||t.includes("\x00")||Buffer.byteLength(t,"utf8")>32768)return;return t}function je(t){let e=t.source??process.env,n={HOME:t.home,PATH:t.path??Ft,TMPDIR:t.temporaryDirectory,SHELL:l(e.SHELL)??"/bin/zsh",LANG:l(e.LANG)??"C.UTF-8",LC_ALL:l(e.LC_ALL)??l(e.LANG)??"C.UTF-8"},r=l(e.LC_CTYPE),o=l(e.TERM),i=l(e.COLORTERM);if(r)n.LC_CTYPE=r;if(o)n.TERM=o;if(i)n.COLORTERM=i;if(process.platform==="win32"){for(let s of I){let a=l(e[s]);if(a)n[s]=a}n.TEMP=n.TMP=t.temporaryDirectory,n.SHELL=Y()??n.SHELL,n.PATH=Oo(n.PATH)}return n}function Oo(t,e=f(g(),".reason","python3")){let n=(i)=>t.split(u.delimiter).filter((s)=>s&&!/[\\/]WindowsApps[\\/]?$/i.test(s)).map((s)=>u.join(s,i)).find((s)=>p(s)),r=n("python.exe");if(n("python3.exe")||!r)return t;let o=`#!/bin/sh
|
|
4
4
|
exec "${r.replaceAll("\\","/")}" "$@"
|
|
5
5
|
`;try{let i=f(e,"python3");if(!p(i)||_(i,"utf8")!==o)T(e,{recursive:!0}),A(i,o)}catch{return t}return[e,t].join(u.delimiter)}var I=["SystemRoot","SystemDrive","windir","ComSpec","PATHEXT","USERPROFILE","USERNAME","USERDOMAIN","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","CommonProgramFiles","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"];
|
|
6
|
-
export{Ft,
|
|
6
|
+
export{Ft,_i,Do,lc,je,Oo};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{xr,w}from"./vm-hands-entry-lite-
|
|
2
|
+
import{xr,w}from"./vm-hands-entry-lite-0xfme8gg.js";import{De}from"./vm-hands-entry-lite-peyr9y6z.js";import{chmodSync as Y,existsSync as R,mkdirSync as X,readlinkSync as C,readFileSync as S,renameSync as Q,unlinkSync as Z,writeFileSync as nn}from"fs";import{homedir as u}from"os";import{basename as _,dirname as h,isAbsolute as p,join as o,normalize as b,relative as A,resolve as O}from"path";var c=3,N=1,P=2,D=1,x=1,T="Reason may read and write files and run commands in this signed-in OS account, subject to saved restrictions and operating system permissions.",ol="Reason may later execute on this computer inside a Reason sandbox, limited to folders explicitly attached by the user.",L=[ol,"Ara may later execute on this computer inside an Ara sandbox, limited to folders explicitly attached by the user."];function M(n){return typeof n==="string"&&L.includes(n)}var F=["future_device","updates_only","cli_only"];function f(n){return typeof n==="string"&&F.some((t)=>t===n)}function B(n=process.env,t=u()){return n.XDG_CONFIG_HOME?.trim()||o(t,".config")}function ot(n=process.env,t=u()){let r=w({env:n}),e=B(n,t);return o(e,De(e).state==="kept"?"ara":"reason",...r==="staging"?["staging"]:[],"installation.json")}function a(n){return typeof n==="string"&&n.trim().length>0}var U=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function V(n){return typeof n==="string"&&U.test(n)}function l(n){return a(n)&&p(n)&&b(n)===n}function y(n){if(!n||typeof n!=="object"||Array.isArray(n))return!1;let t=n;return l(t.path)&&(t.role==="launcher"&&(t.kind==="file"||t.kind==="symlink")||t.role==="worker_root"&&t.kind==="directory"||t.role==="alias"&&t.kind==="symlink"&&l(t.target))}function vc(n){return n==="staging"?["reason-staging","ara-staging"]:["reason","ara"]}var Pl=["reason","ara"];function cs(n){let t=n.owned_paths.filter((e)=>e.role==="launcher").map((e)=>e.path),[r]=vc(n.channel);return t.find((e)=>_(e)===r)??t[0]??null}function g(n){let[t,r]=vc(n.channel==="staging"?"staging":"production"),e=[[t,r],[r,t]];return n.owned_paths?.every((i)=>i.role!=="alias"||n.installer==="shell"&&e.some(([s,v])=>i.path===o(n.install_dir,s)&&i.target===o(n.install_dir,v))&&n.owned_paths?.some((s)=>s.role==="launcher"&&s.path===i.target))??!1}function d(n,t){try{return O(h(n),C(n))===t}catch{return!1}}function Mi(n){let t=_(n),r=t==="ara"?"reason":t==="ara-staging"?"reason-staging":null;if(!r)return n;let e=o(h(n),r);return d(e,n)||d(n,e)?e:n}function m(n,t){let r=A(n,t);return r.length>0&&!r.startsWith("..")&&!p(r)}function I(n){if(n===null)return!0;if(!n||typeof n!=="object"||Array.isArray(n))return!1;let t=n;return(t.kind==="shell_profile"||t.kind==="windows_user_path")&&a(t.location)&&a(t.value)&&(typeof t.added_by_installer==="boolean"||typeof t.added_by_ara==="boolean")&&(t.added_by_installer===void 0||typeof t.added_by_installer==="boolean")&&(t.added_by_ara===void 0||typeof t.added_by_ara==="boolean")}function E(n,t){if(t===null)return n==="cli_only";if(!t||typeof t!=="object"||Array.isArray(t))return!1;let r=t;if(r.version!==D||!a(r.recorded_at))return!1;if(n==="future_device")return r.decision==="authorized"&&M(r.scope);return r.scope===null&&r.decision===(n==="updates_only"?"ask":"disabled")}function K(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let t=n;if(t.schema_version!==N||!xr.includes(t.channel)||t.install_method!=="curl"||t.installer!=="shell"&&t.installer!=="powershell"||!a(t.installed_at)||!a(t.version)||!a(t.target)||!l(t.install_dir)||!Array.isArray(t.owned_paths)||!t.owned_paths.every(y)||!t.owned_paths.every((r)=>m(t.install_dir,r.path))||!g(t)||!I(t.path_entry))return null;return{...t,schema_version:c,installation_id:null,background_mode:"cli_only",device_consent:null}}function z(n){if(!n||typeof n!=="object"||Array.isArray(n))return null;let t=n;if(t.schema_version!==P||!k(t)||!f(t.background_mode)||!E(t.background_mode,t.device_consent))return null;return{...t,schema_version:c,installation_id:null}}function k(n){return xr.includes(n.channel)&&(n.install_method==="curl"&&(n.installer==="shell"||n.installer==="powershell")||n.install_method==="desktop"&&n.installer==="desktop"&&Array.isArray(n.owned_paths)&&n.owned_paths.length===0&&n.path_entry===null)&&a(n.installed_at)&&a(n.version)&&a(n.target)&&l(n.install_dir)&&Array.isArray(n.owned_paths)&&n.owned_paths.every(y)&&n.owned_paths.every((t)=>m(n.install_dir,t.path))&&g(n)&&I(n.path_entry)}function G(n){let t=K(n);if(t)return t;let r=z(n);if(r)return r;if(!n||typeof n!=="object"||Array.isArray(n))return null;let e=n;if(e.schema_version!==c||!V(e.installation_id)||!k(e)||!f(e.background_mode)||!E(e.background_mode,e.device_consent)||e.desktop_account_access!==void 0&&(e.desktop_account_access===null||typeof e.desktop_account_access!=="object"||Array.isArray(e.desktop_account_access)||e.desktop_account_access.version!==x||e.desktop_account_access.scope!==T||!a(e.desktop_account_access.recorded_at)||!Number.isFinite(Date.parse(e.desktop_account_access.recorded_at))))return null;return e}function We(n=ot()){if(!R(n))return null;try{return G(JSON.parse(S(n,"utf8")))}catch{return null}}export{ol,ot,vc,Pl,cs,Mi,We};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{us,ds,Mc,On}from"./vm-hands-entry-lite-hh0kba1y.js";import{A}from"./vm-hands-entry-lite-vedb5r12.js";import{Ue,wr,br}from"./vm-hands-entry-lite-g0bpdyfz.js";import{qr}from"./vm-hands-entry-lite-t3k90kdn.js";import{Go,Kt,_c,Ko,Jo,Xo,Jt}from"./vm-hands-entry-lite-b3mfma12.js";import{vi}from"./vm-hands-entry-lite-3594pdj0.js";import{Se}from"./vm-hands-entry-lite-1as6h9ed.js";import{s}from"./vm-hands-entry-lite-tzv8s0e7.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as se,spawn as ce}from"child_process";import{randomBytes as qe}from"crypto";import{chmodSync as Ce,existsSync as ne,lstatSync as Ge,mkdirSync as Oe,readFileSync as S,rmSync as ae,writeFileSync as R}from"fs";import{connect as he}from"net";import{join as p}from"path";var B=32,N=76;var M="./desktop-wallpaper-fd8f2wb2.jpg";var v="./dock-browser-y53t41cx.png";var Z="./dock-files-cp52htdw.png";var V="./dock-terminal-1es514yq.png";var z="./grok-wallpaper-71zwn2pj.jpg";var W="./grok-dock-browser-pzw59wnd.png";var j="./grok-dock-files-eckq444x.png";var U="./grok-dock-terminal-hcpz3e43.png";var ee=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
|
|
3
3
|
# The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
|
|
4
4
|
# python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
|
|
5
5
|
# Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
|
|
@@ -141,10 +141,10 @@ Type=Application
|
|
|
141
141
|
Categories=System;FileManager;
|
|
142
142
|
`;var te={"wallpaper.jpg":M,"dock-browser.png":v,"dock-terminal.png":V,"dock-files.png":Z,"grok-wallpaper.jpg":z,"grok-dock-browser.png":W,"grok-dock-terminal.png":U,"grok-dock-files.png":j},Ke=ee,Fe='set_wallpaper() { if command -v feh >/dev/null 2>&1; then feh --bg-fill "$1"; else python3 "$2" "$1"; fi; }';function $e(e){let D=(I)=>I.replaceAll("DISPLAY=:99",`DISPLAY=${e.display}`).replaceAll("/tmp/ara-",`${e.root}/ara-`),n=e.look==="grok",d=new Set(e.absent??[]),t=d.has("files")&&e.filesViewerExec?e.filesViewerExec:null;if(t)d.delete("files");let c=(n?Ye:Pe).split(`
|
|
143
143
|
`).filter((I)=>!(d.has("terminal")&&I.endsWith("/ara-terminal.desktop"))&&!(d.has("files")&&I.endsWith("/ara-files.desktop"))).join(`
|
|
144
|
-
`),a=(I)=>n?I.replace("/tmp/ara-dock-","/tmp/ara-grok-dock-"):I,o=t?De.replace(/^Exec=.*$/m,`Exec=${t}`).replace("Categories=System;FileManager;","Categories=Utility;Viewer;"):De,f=n?"ara-grok-wallpaper.jpg":"ara-wallpaper.jpg",i={"openbox/rc.xml":Ae(e.screen),"tint2/tint2rc":D(c),"picom/picom.conf":Ne,...d.has("terminal")?{}:{"ara-terminal.desktop":D(a(ge))},...d.has("files")?{}:{"ara-files.desktop":D(a(o))},"ara-chromium.desktop":D(a(Re)).replace("chromium --no-sandbox %U",e.browserExec),"ara-set-root-wallpaper.py":Ke},X=[...u.slice(0,3),Fe,`[ ! -f "$ROOT/${f}" ] || set_wallpaper "$ROOT/${f}" "$ROOT/ara-set-root-wallpaper.py" || true`,'if alive tint2 && ! cmp -s "$ROOT/tint2/tint2rc" "$ROOT/tint2/applied"; then read -r pid _ <"$ROOT/tint2.pid"; kill -USR1 "$pid" 2>/dev/null || true; fi','cp "$ROOT/tint2/tint2rc" "$ROOT/tint2/applied" 2>/dev/null || true',...u.slice(3)];return{files:i,start:X}}var u=['ticks() { line=$(cat "/proc/$1/stat" 2>/dev/null) || return 1; rest=${line##*) }; case $rest in Z*|X*) return 1;; esac; printf "%s" "$rest" | cut -d " " -f20; }','alive() { [ -f "$ROOT/$1.pid" ] || return 1; read -r pid start <"$ROOT/$1.pid"; current=$(ticks "$pid") || return 1; [ "$current" = "$start" ] && kill -0 "$pid" 2>/dev/null; }','launch() { name=$1; shift; "$@" 9>&- >"$ROOT/$name.log" 2>&1 & pid=$!; start=$(ticks "$pid"); printf "%s %s\\n" "$pid" "$start" >"$ROOT/$name.pid"; }','if [ -f "$ROOT/tint2/tint2rc" ] && ! alive tint2 && command -v tint2 >/dev/null 2>&1; then launch tint2 tint2 -c "$ROOT/tint2/tint2rc"; fi','if [ -f "$ROOT/picom/picom.conf" ] && ! alive picom && command -v picom >/dev/null 2>&1; then launch picom picom --config "$ROOT/picom/picom.conf"; fi'];var Je=43200000,y=":99",Qe=60000,Y=15000,g={width:1280,height:800},ke=/^[A-Za-z0-9._:-]{1,160}$/;function _e(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}var we=["video","viewer","viewer_same_network","viewer_network","look"];function me(e,D=Date.now()){let n=["relay_url","session_id","expires_at"];if(!_e(e)||n.some((f)=>!(f in e))||Object.keys(e).some((f)=>!n.includes(f)&&!we.includes(f)))throw new r("invalid_display_request","Reason desktop request is malformed.");let d="video"in e?Mc(e.video):void 0,t="viewer"in e?
|
|
144
|
+
`),a=(I)=>n?I.replace("/tmp/ara-dock-","/tmp/ara-grok-dock-"):I,o=t?De.replace(/^Exec=.*$/m,`Exec=${t}`).replace("Categories=System;FileManager;","Categories=Utility;Viewer;"):De,f=n?"ara-grok-wallpaper.jpg":"ara-wallpaper.jpg",i={"openbox/rc.xml":Ae(e.screen),"tint2/tint2rc":D(c),"picom/picom.conf":Ne,...d.has("terminal")?{}:{"ara-terminal.desktop":D(a(ge))},...d.has("files")?{}:{"ara-files.desktop":D(a(o))},"ara-chromium.desktop":D(a(Re)).replace("chromium --no-sandbox %U",e.browserExec),"ara-set-root-wallpaper.py":Ke},X=[...u.slice(0,3),Fe,`[ ! -f "$ROOT/${f}" ] || set_wallpaper "$ROOT/${f}" "$ROOT/ara-set-root-wallpaper.py" || true`,'if alive tint2 && ! cmp -s "$ROOT/tint2/tint2rc" "$ROOT/tint2/applied"; then read -r pid _ <"$ROOT/tint2.pid"; kill -USR1 "$pid" 2>/dev/null || true; fi','cp "$ROOT/tint2/tint2rc" "$ROOT/tint2/applied" 2>/dev/null || true',...u.slice(3)];return{files:i,start:X}}var u=['ticks() { line=$(cat "/proc/$1/stat" 2>/dev/null) || return 1; rest=${line##*) }; case $rest in Z*|X*) return 1;; esac; printf "%s" "$rest" | cut -d " " -f20; }','alive() { [ -f "$ROOT/$1.pid" ] || return 1; read -r pid start <"$ROOT/$1.pid"; current=$(ticks "$pid") || return 1; [ "$current" = "$start" ] && kill -0 "$pid" 2>/dev/null; }','launch() { name=$1; shift; "$@" 9>&- >"$ROOT/$name.log" 2>&1 & pid=$!; start=$(ticks "$pid"); printf "%s %s\\n" "$pid" "$start" >"$ROOT/$name.pid"; }','if [ -f "$ROOT/tint2/tint2rc" ] && ! alive tint2 && command -v tint2 >/dev/null 2>&1; then launch tint2 tint2 -c "$ROOT/tint2/tint2rc"; fi','if [ -f "$ROOT/picom/picom.conf" ] && ! alive picom && command -v picom >/dev/null 2>&1; then launch picom picom --config "$ROOT/picom/picom.conf"; fi'];var Je=43200000,y=":99",Qe=60000,Y=15000,g={width:1280,height:800},ke=/^[A-Za-z0-9._:-]{1,160}$/;function _e(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}var we=["video","viewer","viewer_same_network","viewer_network","look"];function me(e,D=Date.now()){let n=["relay_url","session_id","expires_at"];if(!_e(e)||n.some((f)=>!(f in e))||Object.keys(e).some((f)=>!n.includes(f)&&!we.includes(f)))throw new r("invalid_display_request","Reason desktop request is malformed.");let d="video"in e?Mc(e.video):void 0,t="viewer"in e?us(e.viewer):null,c="look"in e?ds(e.look):null;if(d===null)throw new r("invalid_display_request","Reason desktop video request is invalid.");let a=null;try{a=typeof e.relay_url==="string"?new URL(e.relay_url):null}catch{}if(!a||a.protocol!=="wss:"&&a.protocol!=="ws:"||a.username||a.password)throw new r("invalid_display_request","Reason desktop relay URL is invalid.");if(typeof e.session_id!=="string"||!ke.test(e.session_id))throw new r("invalid_display_request","Reason desktop session identity is invalid.");let o=typeof e.expires_at==="string"?Date.parse(e.expires_at):Number.NaN;if(!Number.isFinite(o)||o<=D)throw new r("invalid_display_request","Reason desktop session has already expired.");return{relay_url:e.relay_url,session_id:e.session_id,expires_at:new Date(Math.min(o,D+Je)).toISOString(),...d?{video:d}:{},...t?{viewer:t}:{},...d&&e.viewer_same_network===!0?{viewer_same_network:!0}:{},...c?{look:c}:{}}}function dn(e=process.platform){return(e==="linux"||e==="darwin"||e==="win32")&&A()?.features.display===!0}async function Bo(){if(process.platform==="win32")return dn()&&await Jt();if(process.platform!=="darwin")return dn();return await Jt()}function Te(e){Oe(e,{recursive:!0,mode:448});let D=Ge(e);if(!D.isDirectory()||D.isSymbolicLink()||process.getuid&&D.uid!==process.getuid())throw new r("display_unavailable","Reason desktop state directory is not private.");Ce(e,448)}function Me(e,D){let n=(t)=>{let c=Buffer.alloc(2);return c.writeUInt16BE(t.length),Buffer.concat([c,t])},d=Buffer.from([255,255]);return Buffer.concat([d,n(Buffer.alloc(0)),n(Buffer.from(e)),n(Buffer.from("MIT-MAGIC-COOKIE-1")),n(D)])}function x(e,D,n=2000){return new Promise((d)=>{let t=he(e),c="",a=(o)=>{t.destroy(),d(o)};t.setTimeout(n,()=>a(!1)),t.once("error",()=>a(!1)),t.once("close",()=>a(!1)),t.once("connect",()=>{if(!D)a(!0)}),t.on("data",(o)=>{if(c+=o.toString("latin1"),c.length>=4)a(c.startsWith("RFB "))})})}async function Q(e,D){let n=Date.now()+D;while(Date.now()<n){if(await e())return!0;await new Promise((d)=>setTimeout(d,100))}return!1}function K(e,D,n,d=!1){return new Promise((t)=>{let c=ce(e,D,{detached:!0,stdio:"ignore",env:n});if(d)Ue(c.pid);c.once("error",()=>t(-1)),c.once("exit",(a)=>t(a)),c.unref(),setTimeout(()=>t(null),Y).unref()})}var J=null;function jt(e=s()){return J??=ve(e).finally(()=>{J=null}),J}async function ve(e){let D=A({home:e});if(!D?.xvfb||!D.x11vnc||!D.openbox)throw new r("display_unavailable","Run `reason desktop install` on this machine to enable its desktop.");qr({root:D.root,automation:D.automation,extensionDir:D.extensionDir});let n=p(D.root,"display");Te(n);let d=await ze(e,n,D.x11vnc);if(d)return d;let t={display:y,xauthority:p(n,"Xauthority"),rfbSocket:p(n,"rfb.sock")},c=p(n,"pulse"),a=(async()=>{try{Te(c)}catch{return null}return await _c(c,D.pulseaudio)})();Te(p(n,"home"));let o=k(n,t,D.pulseaudio),f=async()=>({...t,sound:await a});if(await x({path:t.rfbSocket},!0))return pe(p(n,"theme"),u,o),await f();if(!ne(t.xauthority))R(t.xauthority,Me(y.slice(1),qe(16)),{mode:384,flag:"wx"});let i=T(p(n,"theme"),t.display,g,e),X={path:`/tmp/.X11-unix/X${y.slice(1)}`};if(!await x(X,!1)){let I=`${g.width}x${g.height}`,L;if(D.xvnc)ae(t.rfbSocket,{force:!0}),L=K(D.xvnc,[t.display,"-geometry",I,"-depth","24","-nolisten","tcp","-auth",t.xauthority,"-rfbport","-1","-rfbunixpath",t.rfbSocket,"-SecurityTypes","None","-UseBlacklist=0","-AlwaysShared","-desktop","Reason"],o,!0);else L=K(D.xvfb,[t.display,"-screen","0",`${I}x24`,"-nolisten","tcp","-auth",t.xauthority],o,!0);if(!await Q(()=>x(X,!1),Y)||D.xvnc&&!await Q(()=>x({path:t.rfbSocket},!0),Y)){if(await L!==null&&Ze())wr("display");throw new r("display_unavailable","Reason could not start the virtual display.")}K(D.openbox,["--config-file",i.openboxConfig],o,!0)}if(await _(i,o),!await oe(D.x11vnc,t,n,"x11vnc.log",o))throw new r("display_unavailable","Reason could not start the desktop server.");return await f()}function Ze(){let e=0;try{e=Number(S(`/tmp/.X${y.slice(1)}-lock`,"utf8").trim())}catch{return!1}if(!Number.isSafeInteger(e)||e<=1)return!1;try{return process.kill(e,0),!0}catch(D){return D.code==="EPERM"}}function k(e,D,n){let d={HOME:p(e,"home"),PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:D.display,XAUTHORITY:D.xauthority};if(n)d.PULSE_SERVER=Kt(Go(p(e,"pulse")));return d}async function oe(e,D,n,d,t){if(await x({path:D.rfbSocket},!0))return!0;ae(D.rfbSocket,{force:!0});let c=await K(e,["-display",D.display,"-auth",D.xauthority,"-rfbport","0","-rfbportv6","-1","-unixsock",D.rfbSocket,"-nopw","-forever","-shared","-noxdamage","-sb","0","-rfbversion","3.7","-quiet","-bg","-o",p(n,d)],t);if(c!==null&&c!==0)return!1;if(!await Q(()=>x({path:D.rfbSocket},!0),Y))return!1;return br("x11vnc",D.rfbSocket),!0}async function Ve(){let e=["DISPLAY","XAUTHORITY","WAYLAND_DISPLAY","XDG_SESSION_TYPE"],D=(n)=>Object.fromEntries(e.flatMap((d)=>n[d]?[[d,n[d]]]:[]));if(process.env.DISPLAY)return D(process.env);try{let n=await new Promise((d,t)=>se("systemctl",["--user","show-environment"],{encoding:"utf8",timeout:2000},(c,a)=>c?t(c):d(a)));return D(Object.fromEntries(n.split(`
|
|
145
145
|
`).flatMap((d)=>{let t=d.indexOf("=");return t>0?[[d.slice(0,t),d.slice(t+1)]]:[]})))}catch{return{}}}var de=new Set;async function ze(e,D,n){let d=await Ve(),t=/^:(\d+)(?:\.\d+)?$/.exec(d.DISPLAY??"")?.[1];if(!t||`:${t}`===y||d.WAYLAND_DISPLAY||d.XDG_SESSION_TYPE==="wayland")return null;let c={display:`:${t}`,xauthority:d.XAUTHORITY??p(e,".Xauthority"),rfbSocket:p(D,`rfb-${t}.sock`)},a=`${c.display} ${c.xauthority}`;if(de.has(a)||!await x({path:`/tmp/.X11-unix/X${t}`},!1))return null;let o={HOME:e,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:c.display,XAUTHORITY:c.xauthority};if(await oe(n,c,D,`x11vnc-${t}.log`,o))return{...c,sound:null};return de.add(a),process.stderr.write(`Reason worker: your screen ${c.display} could not be served; using the virtual desktop
|
|
146
|
-
`),null}var ie="look";function fe(e){try{return
|
|
146
|
+
`),null}var ie="look";function fe(e){try{return ds(S(p(e,ie),"utf8").trim())??"reason"}catch{return"reason"}}function T(e,D,n,d,t=fe(e)){let c=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,a=[["terminal","xterm"],["files","pcmanfm"]].filter(([,i])=>!ne(`/usr/bin/${i}`)).map(([i])=>i),o=`${c.replace(/ %U$/,"")} --app=file://${p(d,".reason","workspace")}/`,f=$e({root:e,display:D,screen:n,browserExec:c,absent:a,look:t,filesViewerExec:o});for(let i of["","openbox","tint2","picom"])Te(p(e,i));R(p(e,ie),`${t}
|
|
147
147
|
`,{mode:384});for(let[i,X]of Object.entries(f.files))R(p(e,i),X,{mode:384});for(let[i,X]of Object.entries(te))R(p(e,`ara-${i}`),S(X),{mode:384});return{root:e,openboxConfig:p(e,"openbox","rc.xml"),start:f.start}}function _(e,D){return pe(e.root,[...e.start,"openbox --reconfigure >/dev/null 2>&1 || true"],D)}function pe(e,D,n){let d=[`ROOT=${JSON.stringify(e)}`,...D].join(`
|
|
148
148
|
`);return new Promise((t)=>{let c=ce("/bin/sh",["-c",d],{stdio:"ignore",env:{...n,PATH:"/usr/bin:/bin"}}),a=setTimeout(()=>{c.kill(),t()},Y);c.once("error",()=>{clearTimeout(a),t()}),c.once("exit",()=>{clearTimeout(a),t()})})}var We=2073600,je=320;function er(e,D){let n=Math.min(1,Math.sqrt(We/(e.width*e.height))),d=(t,c)=>Math.min(Math.floor(c/8)*8,Math.max(je,Math.round(t*n/8)*8));return{width:d(e.width,D.width),height:d(e.height,D.height)}}function w(e,D,n){return new Promise((d)=>se(e,D,{env:n,encoding:"utf8",timeout:5000},(t,c)=>d(t?null:c)))}function Ie(e){let D=/current (\d+) x (\d+), maximum (\d+) x (\d+)/.exec(e),n=e.split(`
|
|
149
|
-
`),d=n.findIndex((c)=>/^\S+ connected/.test(c));if(!D||d<0)return null;let t=[];for(let c of n.slice(d+1)){let a=/^\s+(\d+x\d+)\s/.exec(c);if(!a)break;t.push(a[1])}return{current:{width:Number(D[1]),height:Number(D[2])},maximum:{width:Number(D[3]),height:Number(D[4])},output:n[d].split(" ")[0],modes:t}}async function rr(e,D,n){if(e.display!==y)return null;let d={PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority},t=(f)=>w("xrandr",f,d),c=Ie(await t(["--query"])??"");if(!c||c.maximum.width<=c.current.width&&c.maximum.height<=c.current.height)return null;let a=er(D,c.maximum);if(a.width===c.current.width&&a.height===c.current.height)return{size:a,changed:!1};let o=`${a.width}x${a.height}`;if(!c.modes.includes(o)){if(await t(["--newmode",o,"60",...[a.width,a.width,a.width,a.width,a.height,a.height,a.height,a.height].map(String)]),await t(["--addmode",c.output,o])===null)return null}return n(),await t(["--output",c.output,"--mode",o])===null?null:{size:a,changed:!0}}async function Dr(e,D){let n=s(),d=A({home:n});if(!d)return;let t=p(d.root,"display"),c=k(t,e,d.pulseaudio);await _(T(p(t,"theme"),e.display,D,n),c);let a=D.width-B*2,o=D.height-B-N;await w("xdotool",["search","--onlyvisible","--class","Chromium","windowsize","%@",String(a),String(o),"windowmove","%@",String(B),String(B)],{...c,PATH:"/usr/bin:/bin"})}var F=Promise.resolve();function tr(e,D,n=()=>{}){let d=F.then(()=>rr(e,D,n));return F=d.then((t)=>t?.changed?Dr(e,t.size):void 0).catch(()=>{}),d.then((t)=>t?.size??null,()=>null)}function $r(e,D){if(e.display!==y)return Promise.resolve();let n=F.then(async()=>{let d=s(),t=A({home:d});if(!t)return;let c=p(t.root,"display"),a=p(c,"theme");if(fe(a)===D)return;let o=k(c,e,t.pulseaudio),f=Ie(await w("xrandr",["--query"],{PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority})??"");await _(T(a,e.display,f?.current??g,d,D),o)});return F=n.catch(()=>{}),n.catch(()=>{})}async function
|
|
150
|
-
export{
|
|
149
|
+
`),d=n.findIndex((c)=>/^\S+ connected/.test(c));if(!D||d<0)return null;let t=[];for(let c of n.slice(d+1)){let a=/^\s+(\d+x\d+)\s/.exec(c);if(!a)break;t.push(a[1])}return{current:{width:Number(D[1]),height:Number(D[2])},maximum:{width:Number(D[3]),height:Number(D[4])},output:n[d].split(" ")[0],modes:t}}async function rr(e,D,n){if(e.display!==y)return null;let d={PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority},t=(f)=>w("xrandr",f,d),c=Ie(await t(["--query"])??"");if(!c||c.maximum.width<=c.current.width&&c.maximum.height<=c.current.height)return null;let a=er(D,c.maximum);if(a.width===c.current.width&&a.height===c.current.height)return{size:a,changed:!1};let o=`${a.width}x${a.height}`;if(!c.modes.includes(o)){if(await t(["--newmode",o,"60",...[a.width,a.width,a.width,a.width,a.height,a.height,a.height,a.height].map(String)]),await t(["--addmode",c.output,o])===null)return null}return n(),await t(["--output",c.output,"--mode",o])===null?null:{size:a,changed:!0}}async function Dr(e,D){let n=s(),d=A({home:n});if(!d)return;let t=p(d.root,"display"),c=k(t,e,d.pulseaudio);await _(T(p(t,"theme"),e.display,D,n),c);let a=D.width-B*2,o=D.height-B-N;await w("xdotool",["search","--onlyvisible","--class","Chromium","windowsize","%@",String(a),String(o),"windowmove","%@",String(B),String(B)],{...c,PATH:"/usr/bin:/bin"})}var F=Promise.resolve();function tr(e,D,n=()=>{}){let d=F.then(()=>rr(e,D,n));return F=d.then((t)=>t?.changed?Dr(e,t.size):void 0).catch(()=>{}),d.then((t)=>t?.size??null,()=>null)}function $r(e,D){if(e.display!==y)return Promise.resolve();let n=F.then(async()=>{let d=s(),t=A({home:d});if(!t)return;let c=p(t.root,"display"),a=p(c,"theme");if(fe(a)===D)return;let o=k(c,e,t.pulseaudio),f=Ie(await w("xrandr",["--query"],{PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority})??"");await _(T(a,e.display,f?.current??g,d,D),o)});return F=n.catch(()=>{}),n.catch(()=>{})}async function pn(e,D={}){let n=D.now??Date.now,d=me(e.payload,n());if(e.signal.throwIfAborted(),!d.video)throw new r("display_video_required","Reason desktops stream as video now; this request came without it.");let t=D.platform??process.platform;if(t!=="linux"&&t!=="darwin"&&t!=="win32")throw new r("display_video_unsupported","This machine does not serve desktop video.");let{video:c,look:a}=d,o=(D.video?.desktop??(t==="darwin"?async()=>Ko:t==="win32"?async()=>Jo:async()=>{let f=await jt();if(a)await $r(f,a);return f}))();return await dr(e.signal,d,D,n,(f)=>Xo(f,{request:c,desktop:o,...d.viewer?{viewer:d.viewer}:{},viewerSameNetwork:d.viewer_same_network===!0},{resizeDesktop:tr,...D.video}),(f)=>On({type:"error",code:f}))}function dr(e,D,n,d,t,c){let a=d();return new Promise((o,f)=>{let i=null,X=!1,I=!1,L,q,P,C=!1,l=null,E=(b)=>{if(I)return;if(l)b=l.outcome;I=!0,clearTimeout(L),clearTimeout(q),e.removeEventListener("abort",O),P?.close();try{i?.close(1000,"display_session_over")}catch{}if("error"in b){f(b.error);return}o({reason:b.reason,...P?.summary(),duration_ms:Math.max(0,d()-a)})},G=()=>E({error:new r("display_relay_unavailable","Reason could not reach the desktop relay.")}),O=()=>{let b=e.reason;E({error:b instanceof r?b:new r("cancelled","Reason closed the desktop session.")})},m=()=>{if(!l||!i)return;let{outcome:b}=l,H=!("error"in b)?b.reason:b.error instanceof r?b.error.code:"display_unavailable";if(!l.told)try{i.send(c(H))}catch{}E(b)};if(P=t({get done(){return I||l!==null},get open(){return X&&!I&&l===null},get bufferedAmount(){return i?.bufferedAmount??0},send(b){if(I||l||!X||!i)return;try{i.send(b)}catch{E({reason:"relay_closed"})}},end:(b)=>{if(I||l)return;if(!("error"in b)&&C&&X){E(b);return}if(l={outcome:b,told:!("error"in b)&&X},C&&X)m()}}),I){P.close();return}if(e.aborted){O();return}e.addEventListener("abort",O,{once:!0}),L=setTimeout(()=>E({reason:"session_expired"}),Math.max(1,Date.parse(D.expires_at)-d())),q=setTimeout(()=>E({reason:"viewer_absent"}),n.viewerWaitMs??Qe);try{i=(n.connect??vi)(D.relay_url,(n.loadProxy??Se)()?.url)}catch{G();return}i.binaryType="arraybuffer",i.onopen=()=>{if(I||!i)return;X=!0,P?.opened()},i.onmessage=(b)=>{if(I)return;let H=b.data,h=H instanceof ArrayBuffer?new Uint8Array(H):ArrayBuffer.isView(H)?new Uint8Array(H.buffer,H.byteOffset,H.byteLength):null;if(!h||h.byteLength===0)return;if(clearTimeout(q),C=!0,l){m();return}P?.received(h)},i.onclose=()=>{if(I)return;if(!X){G();return}E({reason:"relay_closed"})},i.onerror=()=>{if(I||X)return;G()}})}
|
|
150
|
+
export{dn,Bo,Te,jt,pn};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Pr,Rr}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Pr,Rr}from"./vm-hands-entry-lite-hh0kba1y.js";import{g}from"./vm-hands-entry-lite-crjaacc2.js";import{Bc,st,Yt,Tr,Ln}from"./vm-hands-entry-lite-tv5mcw97.js";import{L}from"./vm-hands-entry-lite-hpe54h0b.js";import{s,Et}from"./vm-hands-entry-lite-tzv8s0e7.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 Fi=(e,t)=>{if(d)R(d);let r=B(e,Bc);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(Et(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 xc(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 Cc(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 sl(e=s()){let t=Tr(e);if(t.length>0)return{state:"ready",path:S(S(S(t[0]))),prefix:t};let r=
|
|
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 sl(e=s()){let t=Tr(e);if(t.length>0)return{state:"ready",path:S(S(S(t[0]))),prefix:t};let r=Ln(t,e)??"computer_use_identity_unavailable";return{state:r,path:st(e),detail:ae(r,e)}}function E(){return{identity:()=>sl(),grants:(e)=>Pr(e),request:(e,t)=>Rr(e,t),worker:async()=>(await import("./status-2s3zjapg.js")).connectionMacState(),open:(e)=>{se("/usr/bin/open",e,{stdio:"ignore",timeout:1e4})},tile:Fi,restartConnection:async()=>(await import("./connect-cli-jc4m755k.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 Ac(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 Rl(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 al(e,t){let r=t.host??E(),{io:n}=t,i=await Ac(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}
|
|
@@ -49,4 +49,4 @@ ${G}`),1;if(n.command==="help")return r.stdout.write(G),0;if(n.command==="protec
|
|
|
49
49
|
`).join(""):`No protected paths are allowed on this computer.
|
|
50
50
|
`),0}catch(r){return t.stderr.write(`${r instanceof Error?r.message:String(r)}
|
|
51
51
|
`),1}}
|
|
52
|
-
export{
|
|
52
|
+
export{Fi,xc,Cc,sl,Ac,Rl,al,Tl};
|