@reason-machines/cli-linux-x64 0.2.508 → 0.2.509
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/reason +1 -1
- package/bin/vm-hands/api-credentials-87hn92f0.js +2 -0
- package/bin/vm-hands/api-yg04rftf.js +2 -0
- package/bin/vm-hands/connect-cli-f1hg3trw.js +2 -0
- package/bin/vm-hands/{credentials-drj5ktpt.js → credentials-zsgek373.js} +1 -1
- package/bin/vm-hands/{custom-endpoint-device-j1x988g0.js → custom-endpoint-device-0a5wjyh6.js} +1 -1
- package/bin/vm-hands/desktop-account-ythxv2x5.js +2 -0
- package/bin/vm-hands/{fsevents-8zxmv89w.js → fsevents-x66t2ncp.js} +1 -1
- package/bin/vm-hands/{hands-worker-source-atg5dc7b.js → hands-worker-source-5sk272dx.js} +1 -1
- package/bin/vm-hands/{index-ttmxy9nd.js → index-rdm4a3y7.js} +2 -2
- package/bin/vm-hands/{install-receipt-6v65enmf.js → install-receipt-d5489knb.js} +1 -1
- package/bin/vm-hands/local-automation-627gg3ya.js +2 -0
- package/bin/vm-hands/local-capabilities-1tap81zp.js +2 -0
- package/bin/vm-hands/local-desktop-users-gham2z3k.js +2 -0
- package/bin/vm-hands/local-display-session-q2vbnpr2.js +2 -0
- package/bin/vm-hands/local-display-video-4kcndnqg.js +2 -0
- package/bin/vm-hands/local-managed-process-nzpq335j.js +2 -0
- package/bin/vm-hands/{local-pty-session-5yh2a63r.js → local-pty-session-7yr8cm6d.js} +1 -1
- package/bin/vm-hands/managed-runtime-ptn52m9d.js +2 -0
- package/bin/vm-hands/network-contract-cvqgd243.js +2 -0
- package/bin/vm-hands/package-datdmd5r.js +2 -0
- package/bin/vm-hands/permissions-xp4389xm.js +2 -0
- package/bin/vm-hands/serve-service-5q4prte5.js +2 -0
- package/bin/vm-hands/{status-5xwn7txy.js → status-dqabww8t.js} +1 -1
- package/bin/vm-hands/version-q9df1yye.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-ypsgm6ek.js → vm-hands-entry-lite-12r5xwkb.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-d2c2hr0j.js → vm-hands-entry-lite-18cpkdc1.js} +16 -16
- package/bin/vm-hands/{vm-hands-entry-lite-zjcan28e.js → vm-hands-entry-lite-1kkqgavp.js} +18 -18
- package/bin/vm-hands/{vm-hands-entry-lite-vmhkg070.js → vm-hands-entry-lite-3c5n0wm3.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-hmaazqdr.js → vm-hands-entry-lite-3zeavsfr.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-439wxzv9.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-wnt1695y.js → vm-hands-entry-lite-4483nna7.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-k40j4vwe.js → vm-hands-entry-lite-4kp6abst.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-wn9vrkqj.js → vm-hands-entry-lite-51y3fyms.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-rzr2ncf5.js → vm-hands-entry-lite-8pgdcdsm.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-5geb03sz.js → vm-hands-entry-lite-as5c1hre.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-ztv9msdv.js → vm-hands-entry-lite-bw9g69x1.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-77j164ps.js → vm-hands-entry-lite-c67nmnex.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-qpdpzg8g.js → vm-hands-entry-lite-cswyn85b.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-mk5ayds8.js → vm-hands-entry-lite-f5501hn3.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-x39tmj7j.js → vm-hands-entry-lite-fzbqk2qx.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-8wcyveeh.js → vm-hands-entry-lite-h3r57pgb.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-tebh7dcm.js → vm-hands-entry-lite-hqm76r37.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-psywfz8m.js → vm-hands-entry-lite-hyv23rd9.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-3sjkzhf6.js → vm-hands-entry-lite-js4cr7bc.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-v9qq2cgv.js → vm-hands-entry-lite-kkfefpq6.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-6kns28gv.js → vm-hands-entry-lite-p62aaxk9.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-ewr54tpc.js → vm-hands-entry-lite-pdn0nt11.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-qvvvg5jg.js → vm-hands-entry-lite-rzpg99eh.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-qmk05xmy.js → vm-hands-entry-lite-t5r1sy9z.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-cjm54bxv.js → vm-hands-entry-lite-t6f1f51j.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-aj4bv3wr.js → vm-hands-entry-lite-t8c42p62.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-ncbzy69k.js → vm-hands-entry-lite-tvgb94jk.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-87vmbt38.js → vm-hands-entry-lite-vph99v9r.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-5tbntcyq.js → vm-hands-entry-lite-vx0ht58w.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-6x1an7es.js → vm-hands-entry-lite-w1958mev.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-gvjffc5t.js → vm-hands-entry-lite-w2n56kvf.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-f69t48dj.js → vm-hands-entry-lite-x1b0sm48.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-y2khvb5c.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-fjn8verv.js → vm-hands-entry-lite-yg9zb1nr.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
- package/bin/vm-hands/{vm-hands-executor-1ts90rmh.js → vm-hands-executor-6ex6edrw.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-bhpqejtr.js → vm-hands-op-runner-p3h06gcq.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-zca3gekb.js → vm-hands-runtime-c68t42yc.js} +3 -3
- package/bin/vm-hands/worker-preview-readiness-5myda114.js +2 -0
- package/bin/vm-hands/worker-sandbox-phfz1pj5.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/api-credentials-sbhjbnav.js +0 -2
- package/bin/vm-hands/api-nqz67ppf.js +0 -2
- package/bin/vm-hands/connect-cli-76jsvdgq.js +0 -2
- package/bin/vm-hands/desktop-account-4525j7h3.js +0 -2
- package/bin/vm-hands/local-automation-3w40a7x4.js +0 -2
- package/bin/vm-hands/local-capabilities-6zej0ngm.js +0 -2
- package/bin/vm-hands/local-desktop-users-9dqayaej.js +0 -2
- package/bin/vm-hands/local-display-session-40m49yjn.js +0 -2
- package/bin/vm-hands/local-display-video-d5kd6mt9.js +0 -2
- package/bin/vm-hands/local-managed-process-kgwxtgwj.js +0 -2
- package/bin/vm-hands/managed-runtime-2e5x5c60.js +0 -2
- package/bin/vm-hands/network-contract-rzw769gw.js +0 -2
- package/bin/vm-hands/package-r7sgmw4t.js +0 -2
- package/bin/vm-hands/permissions-pct5sdhg.js +0 -2
- package/bin/vm-hands/serve-service-3sa1ty9g.js +0 -2
- package/bin/vm-hands/version-wrccch8z.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-kz26rfcv.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-swrymqj9.js +0 -3
- package/bin/vm-hands/worker-preview-readiness-7xtgxsar.js +0 -2
- package/bin/vm-hands/worker-sandbox-s9pyac8p.js +0 -2
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{H}from"./vm-hands-entry-lite-38g65s5x.js";import{ht}from"./vm-hands-entry-lite-5gevvgec.js";import{Kt}from"./vm-hands-entry-lite-wrvz9jxy.js";import{j}from"./vm-hands-entry-lite-
|
|
3
|
-
export{Or,qt,Ir,
|
|
2
|
+
import{H}from"./vm-hands-entry-lite-38g65s5x.js";import{ht}from"./vm-hands-entry-lite-5gevvgec.js";import{Kt}from"./vm-hands-entry-lite-wrvz9jxy.js";import{j}from"./vm-hands-entry-lite-8pgdcdsm.js";import{ie}from"./vm-hands-entry-lite-y2khvb5c.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{$e}from"./vm-hands-entry-lite-mcjca0ez.js";import{existsSync as D,realpathSync as q,statSync as K}from"fs";import{platform as h}from"os";import{isAbsolute as z,sep as G}from"path";import{existsSync as X}from"fs";import{createRequire as Y}from"module";var k=$e(Kt)(()=>Y(import.meta.url)("bun:ffi"),X);function E(){return process.platform==="win32"&&typeof globalThis.Bun<"u"&&k.available()}function C(e=process.env){return k.defaultShell(e)}function M(e){return k.shellArgs(e)}function N(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 Or=43200000,qt=ht,Ir=4,Q=/^[A-Za-z0-9._:-]{1,160}$/,V=1000;function I(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(V,Math.max(1,Math.floor(e)))}function Z(e,n=Date.now()){let o=["relay_url","session_id","expires_at"],t=new Set([...o,"cols","rows","cwd","workspace"]);if(!I(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"||!Q.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:H(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+Or)).toISOString(),cols:P(e.cols,80),rows:P(e.rows,24),...e.cwd===void 0?{}:{cwd:e.cwd},...a?{workspace:a}:{}}}function ee(e,n){if(h()==="win32")[e,n]=[e.toLowerCase(),n.toLowerCase()];return n===e||n.startsWith(e+G)}function W(e,n){if(n===void 0)return e;if(!z(n))throw new r("pty_cwd_invalid","Reason terminal working directory must be absolute.");let o;try{o=q(n)}catch{throw new r("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!ee(e,o))throw new r("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!K(o).isDirectory())throw new r("pty_cwd_invalid","Reason terminal working directory is not a directory.");return o}function os(e=process.env){if(h()==="win32")return C(e);let n=e.SHELL;if(n&&z(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 ne(){let e=globalThis.Bun;if(!e)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");return e.spawn}function Un(){if(h()==="win32")return E();return typeof globalThis.Bun<"u"}var re=(e)=>{if(h()==="win32")try{return N({...e,file:e.shell,args:M(e.shell),environment:{...e.environment,TERM:"xterm-256color"}})}catch{throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}let n=ne()({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)}},Dr=(e,n)=>n===void 0?new WebSocket(e):new WebSocket(e,{proxy:n}),v=new Set;function te(e){if(v.size>=Ir||v.has(e))return null;v.add(e);let n=!1;return()=>{if(n)return;n=!0,v.delete(e)}}async function Hn(e,n={}){let o=n.now??Date.now,t=Z(e.payload,o()),c=te(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?ie(e.root,t.workspace):void 0;g=a?W(D(a.boundary)?q(a.boundary):a.boundary,a.path):W(e.root,t.cwd),d=n.environment??process.env,p=n.shellPath??os(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 F=(s)=>{if(U+=s.byteLength,!S||!i){if(O.push(s),R+=s.byteLength,R>qt)l({kind:"resolved",reason:"output_backpressure"});return}try{i.send(s)}catch{l({kind:"resolved",reason:"relay_closed"});return}if(i.bufferedAmount>qt)l({kind:"resolved",reason:"output_backpressure"})};try{w=(n.spawnPty??re)({shell:p,args:["-i","-l"],cwd:g,cols:t.cols,rows:t.rows,environment:d,onData:(s)=>{if(!y)F(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??j)()?.url;try{i=(n.connect??Dr)(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(!I(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{Or,qt,Ir,os,Un,Dr,Hn};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var l=Object.create;var{getPrototypeOf:m,defineProperty:h,getOwnPropertyNames:n}=Object;var k=Object.prototype.hasOwnProperty;function o(a){return this[a]}var p,q,Li=(a,b,c)=>{var d=a!=null&&typeof a==="object";if(d){var i=b?p??=new WeakMap:q??=new WeakMap,j=i.get(a);if(j)return j}c=a!=null?l(m(a)):{};let f=b||!a||!a.__esModule||!k.call(a,"default")?h(c,"default",{value:a,enumerable:!0}):c;if(a&&typeof a==="object"||typeof a==="function"){for(let g of n(a))if(!k.call(f,g))h(f,g,{get:o.bind(a,g),enumerable:!0})}if(d)i.set(a,f);return f};var he=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var r=(a)=>a;function s(a,b){this[a]=r.bind(null,b)}var
|
|
3
|
-
export{Li,he,
|
|
2
|
+
var l=Object.create;var{getPrototypeOf:m,defineProperty:h,getOwnPropertyNames:n}=Object;var k=Object.prototype.hasOwnProperty;function o(a){return this[a]}var p,q,Li=(a,b,c)=>{var d=a!=null&&typeof a==="object";if(d){var i=b?p??=new WeakMap:q??=new WeakMap,j=i.get(a);if(j)return j}c=a!=null?l(m(a)):{};let f=b||!a||!a.__esModule||!k.call(a,"default")?h(c,"default",{value:a,enumerable:!0}):c;if(a&&typeof a==="object"||typeof a==="function"){for(let g of n(a))if(!k.call(f,g))h(f,g,{get:o.bind(a,g),enumerable:!0})}if(d)i.set(a,f);return f};var he=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var r=(a)=>a;function s(a,b){this[a]=r.bind(null,b)}var ps=(a,b)=>{for(var c in b)h(a,c,{get:b[c],enumerable:!0,configurable:!0,set:s.bind(b,c)})};var hs=(a,b,c)=>()=>{if(a)try{b=a(a=0)}catch(d){c=[d]}if(c)throw c[0];return b};var e=import.meta.require;
|
|
3
|
+
export{Li,he,ps,hs,e};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{_e,ye,we}from"./vm-hands-entry-lite-
|
|
2
|
+
import{_e,ye,we}from"./vm-hands-entry-lite-hyv23rd9.js";import{De,Ne,Le}from"./vm-hands-entry-lite-vph99v9r.js";import{spawn as A}from"child_process";import{randomUUID as s}from"crypto";import{basename as C}from"path";import{fileURLToPath as E}from"url";function S(){let p=C(process.execPath).startsWith("bun");return{command:process.execPath,args:[...p?["--no-env-file",E(new URL("./worker-candidate-entry.ts",import.meta.url))]:[],"worker","__preview-probe"]}}async function bs(p,a,m=S()){if(a.aborted||!["darwin","linux","win32"].includes(process.platform)||process.platform==="win32"&&!ye())return!1;let n=new AbortController,o=()=>n.abort();a.addEventListener("abort",o,{once:!0});let y=setTimeout(o,5000),t=A(m.command,m.args,{cwd:p,...Ne(),stdio:["pipe","pipe","ignore"],env:De()});Le(t);let l=!1,b=new Promise((e)=>t.once("close",()=>{l=!0,e()}));t.on("error",o);let f,w,k=new Promise((e)=>{f=e}),I=new Promise((e)=>{w=e}),v=new Promise((e)=>n.signal.addEventListener("abort",()=>e(null),{once:!0})),i="",g=0,P=!1;t.stdout.setEncoding("utf8"),t.stdout.on("data",(e)=>{if(g+=Buffer.byteLength(e),i+=e,g>512){o();return}while(i.includes(`
|
|
3
3
|
`)){let c=i.indexOf(`
|
|
4
4
|
`),d=i.slice(0,c);i=i.slice(c+1);try{if(!P){let r=JSON.parse(d);if(!r||Object.keys(r).length!==2||!Number.isInteger(r.port)||r.port<1024||r.port>65535||typeof r.token!=="string"||!/^[a-zA-Z0-9_-]{43}$/.test(r.token))throw Error("probe_receipt_invalid");P=!0,f({port:r.port,token:r.token})}else if(d==="ready")w(!0);else o()}catch{o()}}}),b.then(o);let h,u=!1;try{let e=await Promise.race([k,v]);if(!e||!t.pid||n.signal.aborted||a.aborted)return!1;let c=Date.now()+4500,d=s(),r={organizationId:s(),userId:s(),runId:s(),deviceId:s(),rootId:s(),attachmentRevision:0,grantRevision:1,jobId:"readiness",generation:1,fenceId:s(),port:e.port,expiresAtMs:c},L={binding:r,executorLaunchId:d,job:{jobId:r.jobId,state:"running",startedAtMs:Date.now(),finishedAtMs:null,leaseExpiresAtMs:c,exitCode:null,inputSequence:0,output:[],firstCursor:1,nextCursor:0,truncated:!1,process:{pid:t.pid,processGroupId:t.pid,executorLaunchId:d}}},x=we({binding:r,deniedPorts:new Set,readCurrentJob:async()=>!l&&!n.signal.aborted?L:null});h=await _e({binding:r,deviceRelayUrl:`ws://127.0.0.1:${e.port}/device/readiness/${e.token}`,port:x,signal:n.signal}),u=await Promise.race([I,v])===!0&&!n.signal.aborted&&!a.aborted}catch{u=!1}finally{if(clearTimeout(y),a.removeEventListener("abort",o),h?.close(),n.abort(),t.stdin.destroy(),!l)t.kill("SIGKILL");await b}return u&&l}
|
|
5
|
-
export{
|
|
5
|
+
export{bs};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{t,o,i,W,ee,s,n}from"./vm-hands-entry-lite-
|
|
2
|
+
import{t,o,i,W,ee,s,n}from"./vm-hands-entry-lite-w2n56kvf.js";var lt=32768,Lt=67108864,Cr=16384,E=204800,kn=600000,_=["content-type","anthropic-version","user-agent"],m=s(["openai-completions","openai-responses","anthropic-messages"]),f=new Set(_),C=ee(t(),t().max(2048)).refine((e)=>Object.keys(e).every((r)=>f.has(r))&&Object.values(e).every((r)=>!/[\r\n\0]/.test(r)),"Only non-secret custom endpoint request headers are permitted");function u(e){try{let r=new URL(e);return["http:","https:"].includes(r.protocol)&&!r.username&&!r.password&&!r.search&&!r.hash?r:null}catch{return null}}function Ar(e,r){let c=u(e.baseUrl),l=u(r.baseUrl),a=u(e.url);if(!c||!l||!a||e.method!=="POST"||r.execution!=="device")return!1;let d=(p)=>p.origin+p.pathname.replace(/\/+$/,"");if(d(c)!==d(l)||a.origin!==c.origin)return!1;let h=r.api==="openai-completions"?"/chat/completions":r.api==="openai-responses"?"/responses":"/v1/messages";return a.pathname===c.pathname.replace(/\/+$/,"")+h}var Cn=i({baseUrl:t().max(2048),url:t().max(4096),method:n("POST"),body:t().refine((e)=>new TextEncoder().encode(e).byteLength<=E).optional(),headers:C,credentialOrganizationId:t().uuid(),accountKey:t().min(1).max(256).optional()}).strict().refine((e)=>m.options.some((r)=>Ar(e,{baseUrl:e.baseUrl,api:r,execution:"device"})),"Invalid custom endpoint inference URL"),x=i({status:o().int().min(200).max(599),statusText:t().max(256).refine((e)=>!/[\r\n\0]/.test(e)),headers:ee(t(),t().max(4096)).refine((e)=>Object.keys(e).every((r)=>["content-type","retry-after","x-request-id","request-id"].includes(r))&&Object.values(e).every((r)=>!/[\r\n\0]/.test(r)))}).strict(),D=W([i({eof:n(!0)}).strict(),i({eof:n(!1),data:t().max(Math.ceil(lt/3)*4).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/).refine((e)=>e.length>0&&e.length*3/4-(e.endsWith("==")?2:e.endsWith("=")?1:0)<=lt)}).strict()]),y=i({bytes:o().int().min(0).max(Lt),chunks:o().int().min(0).max(Cr)}).strict(),An=i({apiKey:t().min(1).max(16384).refine((e)=>!/[\r\n\0]/.test(e)),api:m}).strict(),S=["custom_endpoint_host_not_found","custom_endpoint_connection_failed","custom_endpoint_tls_failed"];function Pn(e){return typeof e==="string"&&S.includes(e)}var O="Ollama listens only on 127.0.0.1 unless it is started with OLLAMA_HOST=0.0.0.0.",g={custom_endpoint_host_not_found:"Your computer couldn't resolve your model server's hostname. Check the hostname in the Base URL, and that this computer is on the network or tailnet that resolves it.",custom_endpoint_connection_failed:`Your computer's connection to your model server was refused or timed out. Check that the server is running and listening on the Base URL's address and port. ${O}`,custom_endpoint_tls_failed:"Your computer couldn't make a secure (TLS) connection to your model server. Check the server's https certificate, or use an http:// Base URL for a server on your computer or private network.",401:"Your model server refused the request (HTTP 401). Check the API key saved for it in Models.",403:"Your model server refused the request (HTTP 403). Ollama refuses requests addressed to a hostname other than localhost, such as a *.ts.net name from tailscale serve or funnel: restart it with OLLAMA_HOST=0.0.0.0, or use http://localhost:11434/v1 when it runs on the session's computer. For another server, check the API key and its access rules.",404:"Your model server answered HTTP 404 (not found). Check that the Base URL is the API root (for Ollama, http://localhost:11434/v1) and that each model ID is one the server lists."};var I=new Set(Object.values(g));export{lt,Lt,Cr,kn,Ar,Cn,An,Pn};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{E}from"./vm-hands-entry-lite-txd50spx.js";import{fe,Ie,Ne,Le,Me}from"./vm-hands-entry-lite-
|
|
2
|
+
import{E}from"./vm-hands-entry-lite-txd50spx.js";import{fe,Ie,Ne,Le,Me}from"./vm-hands-entry-lite-vph99v9r.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 m}from"os";import{basename as H,delimiter as g,join as f,win32 as u}from"path";var Er=process.platform==="win32"?Ie("win32"):"/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",P=Er.split(g),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],{...Ne(),stdio:["ignore","pipe","ignore"]}),Le(o)}catch(c){r(c);return}let i=[],s=0,a=null,L=(c)=>{a??=Error(c);try{if(o.pid!==void 0)Me(o.pid,"SIGKILL")}catch{}},d=setTimeout(()=>L("login_shell_timeout"),R);o.stdout?.on("data",(c)=>{if(s+=c.length,s>S)L("login_shell_output_too_large");else i.push(c)}),o.once("error",(c)=>{clearTimeout(d),r(c)}),o.once("close",(c)=>{if(clearTimeout(d),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 xr(t,e=process.platform){let n=e==="win32",r=t.split(`
|
|
3
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(E(s))continue;o.push(s)}return h(o)}function vn(t){let e=t?.home??m(),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"?xr(process.env.PATH??process.env.Path??""):[],...P]).join(g)}async function C(t){let e=t?.shell??process.env.SHELL,n=()=>({path:vn({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=xr(r);if(o.length===0)return n();return{path:h([...o,...P]).join(":"),source:"login_shell"}}function oo(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 He(t){let e=t.source??process.env,n={HOME:t.home,PATH:t.path??Er,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=fe()??n.SHELL,n.PATH=Sn(n.PATH)}return n}function Sn(t,e=f(m(),".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"];
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{Ie,De}from"./vm-hands-entry-lite-
|
|
2
|
+
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{Ie,De}from"./vm-hands-entry-lite-vph99v9r.js";import{request as Ce}from"http";import{pipeline as Ne}from"stream";import{constants as te,createBrotliCompress as $e,createGzip as Me}from"zlib";import{WebSocket as U}from"ws";import{randomBytes as Re,timingSafeEqual as Be}from"crypto";import{createServer as Le}from"net";var p={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000,window:8};function Z(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function L(e,t,n=Number.MAX_SAFE_INTEGER){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=t&&e<=n}function pe(e){return typeof e==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(e)}function fe(e,t){let n=Buffer.from(e,"latin1");return Buffer.concat([Buffer.from([n.length]),n,t])}function C(e){if(!Z(e)||Object.keys(e).length!==12||![e.organizationId,e.userId,e.runId,e.deviceId,e.rootId,e.jobId,e.fenceId].every(pe)||!L(e.attachmentRevision,0)||!L(e.grantRevision,1)||!L(e.generation,1)||!L(e.port,1024,65535)||!L(e.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...e})}function ze(e,t){return Object.keys(e).every((n)=>e[n]===t[n])}function H(e){if(e.length>4096||!e.startsWith("/")||e.startsWith("//")||/[\\\x00-\x20\x7f#]/.test(e))throw Error("preview_path_invalid");let t=decodeURIComponent(e);if(t.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(t))throw Error("preview_path_invalid");return e}function ue(e){return Array.isArray(e)&&e.length<=64&&e.every((t)=>Array.isArray(t)&&t.length===2&&typeof t[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(t[0])&&typeof t[1]==="string"&&t[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(t[1]))}function z(e,t=p.chunk){if(e.length>Math.ceil(t/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw Error("preview_data_invalid");let n=Buffer.from(e,"base64");if(n.length>t)throw Error("preview_data_too_large");return n}function me(e){if(Array.isArray(e))return Buffer.concat(e);if(typeof e==="string")return Buffer.from(e,"utf8");if(e instanceof ArrayBuffer)return Buffer.from(e);return e}function ge(e){if(Buffer.byteLength(e)>p.upload*1.4+300000)throw Error("preview_frame_too_large");let t=JSON.parse(e);if(!Z(t))throw Error("preview_frame_invalid");if(t.type==="hello")return{type:"hello",binding:C(t.binding),...L(t.messages,p.chunk,p.upload)?{messages:t.messages}:{},...L(t.window,1,p.window)?{window:t.window}:{},...t.bytes===!0?{bytes:!0}:{}};if(t.type==="refused"&&typeof t.reason==="string"&&/^[a-z_]{1,32}$/.test(t.reason))return{type:"refused",binding:C(t.binding),reason:t.reason};if(!pe(t.id))throw Error("preview_frame_invalid");if(t.type==="end"||t.type==="cancel"||t.type==="credit")return{type:t.type,id:t.id};if(t.type==="ws"&&typeof t.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(t.protocol))return{type:"ws",id:t.id,protocol:t.protocol};if(t.type==="data"&&typeof t.data==="string"&&typeof t.binary==="boolean")return z(t.data,p.upload),{type:"data",id:t.id,data:t.data,binary:t.binary};if(t.type==="head"&&L(t.status,200,599)&&ue(t.headers))return{type:"head",id:t.id,status:t.status,headers:t.headers};if(t.type==="request"&&typeof t.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(t.method)&&typeof t.path==="string"&&ue(t.headers)&&typeof t.body==="string"&&typeof t.upgrade==="boolean")return z(t.body,p.upload),{type:"request",id:t.id,method:t.method,path:H(t.path),headers:t.headers,body:t.body,upgrade:t.upgrade};throw Error("preview_frame_invalid")}function ee(e){let t=[...e],n=new Set(t.filter(([s])=>s.toLowerCase()==="connection").flatMap(([,s])=>s.toLowerCase().split(",").map((i)=>i.trim()))),o=new Set(["authorization","proxy-authorization","cookie","set-cookie","host","origin","referer","connection","upgrade","keep-alive","transfer-encoding","te","trailer","content-length","forwarded","alt-svc","service-worker-allowed","clear-site-data","refresh"]);return t.filter(([s])=>!o.has(s.toLowerCase())&&!n.has(s.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(s))}async function re(e){let t;try{return await Promise.race([Promise.resolve().then(e).then((n)=>n===!0||(n===!1?!1:void 0),()=>{return}),new Promise((n)=>{t=setTimeout(()=>n(void 0),p.authorizationMs)})])}finally{clearTimeout(t)}}async function Dt(e){return await re(e)===!0}function J(e,t){let n=new URL(e);if(n.username||n.password||n.search||n.hash||!(n.protocol==="wss:"||n.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(n.hostname))||!new RegExp(`^/${t}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(n.pathname))throw Error("preview_relay_invalid");return n.href}function ct(e){if(!Z(e)||Object.keys(e).length!==2||typeof e.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:C(e.binding),deviceRelayUrl:J(e.deviceRelayUrl,"device")}}function so(e){if(!Z(e)||Object.keys(e).length!==1||!("binding"in e))throw Error("preview_close_invalid");return{binding:C(e.binding)}}var be="x-preview-connection";async function he(e,t){if(t.aborted)throw Error("preview_closed");let n=Re(32).toString("base64url"),o=new Set,s=!1,i=Le((c)=>{if(s||t.aborted||o.size>=p.streams*2)return c.destroy();o.add(c);let d=new AbortController;c.once("close",()=>{o.delete(c),d.abort()}),c.on("error",()=>c.destroy()),c.setTimeout(2000,()=>c.destroy());let b=Buffer.alloc(0),m=(g)=>{b=Buffer.concat([b,g]);let w=b.indexOf(`\r
|
|
3
3
|
\r
|
|
4
4
|
`);if(w<0){if(b.length>16384)c.destroy();return}if(c.pause(),c.off("data",m),w>16384||b.length>p.upload+16384)return c.destroy();l(b,w).catch(()=>c.destroy())};c.on("data",m);async function l(g,w){let y=g.subarray(0,w).toString("latin1").split(`\r
|
|
5
5
|
`),_=/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) (\S+) HTTP\/1\.1$/.exec(y.shift()??"");if(!_)throw Error("preview_request_invalid");H(_[2]);let k=!1,O=0,T=[];for(let B of y){let S=/^([a-zA-Z0-9-]+):[ \t]*([^\x00-\x08\x0a-\x1f\x7f]*)$/.exec(B);if(!S)throw Error("preview_header_invalid");if(S[1].toLowerCase()===be){O++;let N=Buffer.from(S[2].trim());k=N.length===n.length&&Be(N,Buffer.from(n))}else if(S[1].toLowerCase()!=="host")T.push(B)}if(!k||O!==1||s||d.signal.aborted)throw Error("preview_connection_denied");let v=await e.connect(d.signal);if(s||d.signal.aborted)throw v.destroy(),Error("preview_closed");o.add(v),v.on("error",()=>c.destroy()),v.once("close",()=>{o.delete(v),c.destroy()}),c.once("close",()=>v.destroy()),c.setTimeout(0);let P=[`${_[1]} ${_[2]} HTTP/1.1`,`Host: 127.0.0.1:${v.remotePort}`,...T,"",""].join(`\r
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Hi,zi}from"./vm-hands-entry-lite-
|
|
3
|
-
export{
|
|
2
|
+
import{Hi,zi}from"./vm-hands-entry-lite-w1958mev.js";function ys(o=process.platform){if(Hi(),o==="linux"||o==="win32")zi("strict")}
|
|
3
|
+
export{ys};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-
|
|
3
|
-
`).flatMap((n)=>{let s=/^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(n);return s&&Number(s[2])===e?[{pid:Number(s[1]),command:s[3]}]:[]})}async function
|
|
4
|
-
export{xt,
|
|
2
|
+
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-vph99v9r.js";import{execFileSync as h}from"child_process";import{mkdirSync as k,readdirSync as D,readFileSync as w,rmSync as g,statSync as x,writeFileSync as L}from"fs";import{join as p,sep as y}from"path";import{setTimeout as _}from"timers/promises";var P=3000,u=null;function S(e){return p(e,"users")}function xt(e){if(u?.root===e.root)return;let o=S(e.root);k(o,{recursive:!0,mode:448}),L(p(o,String(process.pid)),"",{mode:384}),u=e}function ga(){if(!u)return;g(p(S(u.root),String(process.pid)),{force:!0}),u=null}function m(e){try{return process.kill(e,0),!0}catch(o){return o instanceof Error&&"code"in o&&o.code==="EPERM"}}function E(){let e=process.getuid?.();if(process.platform==="linux")return D("/proc").flatMap((n)=>{if(!/^\d+$/.test(n))return[];try{if(x(`/proc/${n}`).uid!==e)return[];let s=w(`/proc/${n}/cmdline`).toString("utf8").split("\x00").join(" ").trim();return s?[{pid:Number(n),command:s}]:[]}catch{return[]}});if(process.platform==="win32")return h(C("powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.CommandLine)" }'],{encoding:"utf8",maxBuffer:16777216,windowsHide:!0}).split(/\r?\n/).flatMap((s)=>{let l=/^(\d+) (.+)$/.exec(s.trim());return l?[{pid:Number(l[1]),command:l[2]}]:[]});return h("/bin/ps",["-axww","-o","pid=,uid=,command="],{encoding:"utf8",maxBuffer:16777216}).split(`
|
|
3
|
+
`).flatMap((n)=>{let s=/^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(n);return s&&Number(s[2])===e?[{pid:Number(s[1]),command:s[3]}]:[]})}async function _a(){let e=u;if(!e)return{released:"unused",stopped:0};let o=S(e.root);g(p(o,String(process.pid)),{force:!0}),u=null;let n=!1;for(let t of D(o)){let c=Number(t);if(Number.isSafeInteger(c)&&c>0&&m(c))n=!0;else g(p(o,t),{force:!0})}if(n)return{released:"shared",stopped:0};let s=E().filter((t)=>t.pid!==process.pid&&(t.command.includes(`${e.root}${y}`)||t.command.includes(`${e.automation}${y}`)||t.command.includes(e.extensionDir))),l=(t,c)=>{try{process.kill(t,c)}catch{}};for(let t of s)l(t.pid,"SIGTERM");for(let t=Date.now()+P;Date.now()<t&&s.some((c)=>m(c.pid));)await new Promise((c)=>setTimeout(c,100));for(let t of s)if(m(t.pid))l(t.pid,"SIGKILL");return{released:"stopped",stopped:s.length}}var M=20000,N=30000,O=100,a=new Map,i=null,b=0,f=[];function Mi(e){a.set(e,(a.get(e)??0)+1);let o=!1;return()=>{if(o)return;o=!0;let n=(a.get(e)??1)-1;if(n>0){a.set(e,n);return}if(a.delete(e),i?.run===e)i.idleUntil=0}}function T(){return new r("automation_desktop_busy","Another Session, or another agent of this Session, is using this worker's desktop. Retry after it finishes.")}function U(e,o){return i!==null&&i.run!==e&&(i.calls>0||o<i.idleUntil)}async function $i(e,o,n=Date.now,s="run"){let l=Symbol(e);f.push(l);try{let d=n()+N;for(;;){if(b===0&&!U(e,n())&&(i?.run===e||f[0]===l))break;if(n()>=d)throw T();await _(O,void 0,{signal:o}).catch(()=>o.throwIfAborted())}}finally{f.splice(f.indexOf(l),1)}if(s==="call"&&!(i?.run===e&&(i.calls>0||n()<i.idleUntil))){b+=1;let d=!1;return()=>{if(d)return;d=!0,b-=1}}if(i?.run!==e)i={run:e,calls:0,idleUntil:0};let t=i;t.calls+=1;let c=!1;return()=>{if(c)return;c=!0,t.calls-=1,t.idleUntil=n()+M}}
|
|
4
|
+
export{xt,ga,_a,Mi,$i};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{H}from"./vm-hands-entry-lite-38g65s5x.js";import{D,R,b}from"./vm-hands-entry-lite-
|
|
3
|
-
`)}).finally(()=>{if(c.get(w.port)===L)c.delete(w.port)})},dispose(){for(let _ of c.values())_.abort();c.clear()}}}class it extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var fe=256,B=new Map,he="preview.serve.v1",V=new Map;function be(e){let c=V.get(e.operation_id);if(c){if(c.claim!==e)throw M("process_authority_lost");return c}if(V.size>=fe)throw M("process_journal_capacity");let _={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return V.set(e.operation_id,_),_}function pe(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ue=(e)=>new Promise((c)=>setTimeout(c,e)),M=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function ze(e=a(),c=Ge()){let _=Ue(Lr({},e)),l=qe(tr(e),_),[C,...w]=l.split(Je);return{directory:j(c,l,"processes"),previous:[j(_,"processes"),...C==="reason"?[j(c,"ara",...w,"processes")]:[]]}}function Ge(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=
|
|
4
|
-
export{Wi,Vi,fn,Gi,mn,Ki,it,dr,
|
|
2
|
+
import{H}from"./vm-hands-entry-lite-38g65s5x.js";import{D,R,b}from"./vm-hands-entry-lite-c67nmnex.js";import{je,hr,fr,wn,bn,st}from"./vm-hands-entry-lite-1kkqgavp.js";import{Lr}from"./vm-hands-entry-lite-8pgdcdsm.js";import{p,ct,xn,_e,we}from"./vm-hands-entry-lite-hyv23rd9.js";import{v,h}from"./vm-hands-entry-lite-x1b0sm48.js";import{a,tr,Bo}from"./vm-hands-entry-lite-y2khvb5c.js";import{nn,y,t,k,o,d,ls,Oe,Ni,u,i,W,g,ee,s,n,on}from"./vm-hands-entry-lite-w2n56kvf.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{se,A}from"./vm-hands-entry-lite-vph99v9r.js";import{randomUUID as Q}from"crypto";import{spawn as Le}from"child_process";import{existsSync as Z,lstatSync as me,mkdirSync as We,readFileSync as Ne,realpathSync as G,rmSync as Ve,writeFileSync as He}from"fs";import{dirname as Ue,join as j,relative as qe,sep as Je}from"path";var Se=["process.run.v1","process.full.v1"],xe=600000,Pe=1800000,Ee=20000,ne="process.cancel.v1",ie=i({action:n("start"),request_id:t().uuid(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),cwd:t().min(1).max(4096).refine((e)=>!e.includes("\x00")&&!e.startsWith("/")&&!e.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:s(["host","confined"]).default("host"),timeout_ms:o().int().min(1000).max(Pe).default(xe).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),K={device_id:t().uuid(),root_id:t().uuid()},Re=g("action",[ie.extend(K),i({...K,action:n("inspect"),process_id:t().uuid(),after:o().int().min(0).default(0),wait_ms:o().int().min(0).max(Ee).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),i({...K,action:n("cancel"),process_id:t().uuid()}).strict()]),Fe=nn(Re,{io:"input"}),Ke=ie.extend({process_brain_fence:t().uuid(),process_expires_at:y.datetime()}).strict(),J=i({version:n(1),process_id:t().uuid(),state:s(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:o().int().nullable(),first_cursor:o().int().min(0),next_cursor:o().int().min(0),truncated:d(),observed_at:y.datetime(),output:u(i({cursor:o().int().min(1),stream:s(["stdout","stderr"]),text:t().max(32768)}).strict()).max(128)}).strict().refine((e)=>{if(Buffer.byteLength(JSON.stringify(e))>1e5||e.next_cursor<e.first_cursor-1)return!1;if((e.state==="starting"||e.state==="running"||e.state==="uncertain")&&e.exit_code!==null)return!1;if(e.state==="exited"&&(e.exit_code===null||e.exit_code<0||e.exit_code>255))return!1;if(e.state==="cancelled"&&e.exit_code!==130||e.state==="expired"&&e.exit_code!==124)return!1;let _=e.first_cursor-1;for(let l of e.output){if(l.cursor<=_||l.cursor>e.next_cursor)return!1;_=l.cursor}return!0});function ae(e){return Se.includes(e)}var Xe=i({operation_constraints:ee(t(),Oe())}),Ye=i({ready:n(!0),version:n(1),execution_mode:s(["host","confined"]),max_timeout_ms:o().int().min(1000).optional()});var Ie=i({version:n(1),process_id:t().uuid(),state:s(["queued","cancelled_before_start","not_started"]),exit_code:ls(),output:u(Ni()).length(0),first_cursor:n(0),next_cursor:n(0),truncated:n(!1),cancellation_requested:n(!1),reason_code:s(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),De=i({...J.shape,state:s(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:y.datetime().optional(),expires_at:y.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:d(),reason_code:t().nullable().optional(),execution_authority:n("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:i({cause:n("brain_generation_changed"),terminal_confirmed:d(),next_step:s(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:J.shape.state.or(n("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),$e=nn(De),Qe=W([J,Ie.refine((e)=>e.state==="cancelled_before_start")]),X=i({version:n(1),process_id:t().uuid(),state:s(["exited","cancelled","expired"]),exit_code:o().int().min(0).max(255),observed_at:y.datetime()}).strict().refine((e)=>(e.state!=="cancelled"||e.exit_code===130)&&(e.state!=="expired"||e.exit_code===124)),Ze=i({process_terminal_observation:X}).strict();var Wi="preview.serve.v1",Vi=43200000;var ce="preview.open.v1",de=1,fn="gid_proxy_v1",Gi="egress",mn=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,Ce=i({version:n(fn),allowed_domains:u(t().max(260).regex(mn)).max(1024)}).strict(),Ae=on((e)=>H(e)!==null,"invalid workspace"),ke=i({version:n(1),request_id:k(),session_id:k(),command:t().min(1).max(16000).refine((e)=>!e.includes("\x00")),port:o().int().min(1024).max(65535),workspace:Ae,egress:Ce.optional()}).strict(),Ki=ke.extend({expires_at:y.datetime()}).strict();var Me=4,Te=5000;function Y(e,c,_){let l=null;try{l=ct(e)}catch{}xn({deviceRelayUrl:l?.deviceRelayUrl??"",binding:l?.binding??null,jobId:c,port:l?.binding.port??0,reason:l?_:"binding_invalid"})}function le(e){let c=new Map;return{open(_){let l=(x)=>Y(_,e.claim.operation_id,x),C;try{C=ct(_)}catch{return l("binding_invalid")}let{binding:w,deviceRelayUrl:z}=C,E=e.claim.owner;if(!E||w.organizationId!==E.organization_id||w.userId!==E.user_id||w.deviceId!==E.device_id||w.rootId!==e.claim.root_id||w.jobId!==e.claim.operation_id||w.fenceId!==e.claim.operation_id||w.generation!==de||w.expiresAtMs>Math.min(Date.now()+p.lifetimeMs+Te,e.expiresAtMs))return l("binding_mismatch");if(w.expiresAtMs<=Date.now())return l("binding_expired");if(c.get(w.port)?.abort(),c.delete(w.port),c.size>=Me)return l("preview_capacity");let L=new AbortController;c.set(w.port,L);let P=we({binding:w,deniedPorts:e.deniedPorts,readCurrentJob:async()=>{if(L.signal.aborted)return null;let x=await e.inspect();return x?{binding:w,executorLaunchId:e.executorLaunchId,job:x}:null}});_e({binding:w,deviceRelayUrl:z,port:P,signal:L.signal}).then((x)=>x.closed,(x)=>{let I=x instanceof Error?x.message:"preview_failed";if(I!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:w.jobId,port:w.port,reason_code:I})}
|
|
3
|
+
`)}).finally(()=>{if(c.get(w.port)===L)c.delete(w.port)})},dispose(){for(let _ of c.values())_.abort();c.clear()}}}class it extends r{observation;constructor(e){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=e}}var fe=256,B=new Map,he="preview.serve.v1",V=new Map;function be(e){let c=V.get(e.operation_id);if(c){if(c.claim!==e)throw M("process_authority_lost");return c}if(V.size>=fe)throw M("process_journal_capacity");let _={claim:e,executing:!1,cancelRequested:!1,phase:"pending"};return V.set(e.operation_id,_),_}function pe(e){return{version:1,process_id:e,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var ue=(e)=>new Promise((c)=>setTimeout(c,e)),M=(e="process_outcome_uncertain")=>new r(e,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function ze(e=a(),c=Ge()){let _=Ue(Lr({},e)),l=qe(tr(e),_),[C,...w]=l.split(Je);return{directory:j(c,l,"processes"),previous:[j(_,"processes"),...C==="reason"?[j(c,"ara",...w,"processes")]:[]]}}function Ge(){if(process.platform!=="darwin")throw new r("process_unavailable","Managed Mac process execution is unavailable.");let e=Bo();if(!e)throw new r("process_unavailable","The private per-user process directory is unavailable.");return e}async function dr(e){if(!e.claim.owner||e.signal.aborted||e.expiresAtMs<=Date.now())throw M("process_authority_lost");let c=be(e.claim);if(c.executing)throw M("process_busy");if(c.executing=!0,c.cancelRequested)return c.phase="settling",pe(e.claim.operation_id);c.phase="starting";let _=e.journals??ze();We(_.directory,{recursive:!0,mode:448});let l=hr({runtimeDirectory:G(_.directory),previousRuntimeDirectories:(_.previous??[]).filter((m)=>Z(m)).map((m)=>G(m)),root:e.root,runId:JSON.stringify([e.claim.owner,e.claim.run_id,e.claim.root_id,e.claim.operation_id]),maxScopes:fe});try{for(let m of[e.root,e.cwd])if(!je(G(m),l.journalDirectory))throw new r("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(m){throw l.disposeSocket(),m}let C=me(l.journalDirectory),w=e.claim.capability===he,z=()=>B.set(e.claim.operation_id,{path:l.journalDirectory,ino:C.ino,dev:C.dev,anyCompletion:w}),E=l.launchDirectory,L=j(E,"config.json"),P={url:"",transport:"local_job_ipc",directShell:{mode:e.mode,executable:e.shell,jobId:e.claim.operation_id},workerVersion:D,protocolVersion:2,workerArtifactSha256:b,workerEntrypoint:R,targetGeneration:1,fenceId:Q(),...process.platform==="win32"?{bashExecutable:se()}:{},workRoot:e.root,workspaceAliasPath:e.root,repoPath:e.cwd,jobEnvPath:j(E,"unused.env"),replSocketPath:j(E,"unused.sock"),readyPath:j(E,"ready.json"),directTerminalReceiptPath:j(E,"terminal.json"),launchId:Q(),expiresAtMs:e.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:l.journalDirectory,scopeId:l.scopeId},jobControlSocketPath:l.socketPath,...e.prefix?{bashCommandPrefix:e.prefix}:{},...e.jobsUser?{jobsUser:e.jobsUser}:{}},x;try{He(L,JSON.stringify(P),{mode:384});let m=wn({configPath:L,root:e.cwd,grantedRoot:e.root,workRoot:e.root,temporaryDirectory:E});x=e.spawnWorker?.(L,P)??Le(m.command,m.args,{...m.options,env:e.environment,stdio:[bn,"ignore","ignore"]})}catch(m){throw l.disposeSocket(),m}let I=!1,F=new Promise((m,S)=>{x.once("exit",(f)=>{I=!0,m(f)}),x.once("error",(f)=>{I=!0,S(f)})});F.catch(()=>{});let ge={root:e.root,runId:e.claim.run_id,scopeId:l.scopeId,socketPath:l.socketPath,generation:1,fenceId:P.fenceId,executorLaunchId:P.launchId,expiresAtMs:P.expiresAtMs},N=async(m)=>{let S=await fr(ge,{type:"job",version:2,generation:1,id:Q(),jobId:e.claim.operation_id,...m==="start"?{action:m,input:{script:e.command,leaseExpiresAtMs:e.expiresAtMs}}:m==="inspect"?{action:m,input:{after:0}}:m==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:m,input:{}}},new AbortController().signal);if(!S.ok)throw M(S.error);return S.job},U=!1,q=!1,te,re=()=>{U=!0,st(x,"SIGTERM")};e.signal.addEventListener("abort",re,{once:!0});let T,oe=0,ve=async(m)=>{let S=[...m.output],f={version:1,process_id:e.claim.operation_id,state:m.state,exit_code:m.exitCode,first_cursor:m.firstCursor,next_cursor:m.nextCursor,truncated:m.truncated,output:S,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(f))>90000&&S.length)S.shift(),f.truncated=!0,f.first_cursor=S[0]?.cursor??f.next_cursor+1;T=J.parse(f),await e.emit(T),oe=Date.now()};try{let m=Math.min(Date.now()+1e4,e.expiresAtMs);while(!Z(P.readyPath)){if(I)throw new r("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if(e.signal.aborted||Date.now()>=m)throw M("process_start_unconfirmed");await ue(25)}let S=JSON.parse(Ne(P.readyPath,"utf8"));if(S.launchId!==P.launchId||S.fenceId!==P.fenceId||S.workerArtifactSha256!==b)throw M();if(e.signal.throwIfAborted(),c.cancelRequested)return pe(e.claim.operation_id);let f;try{q=!0,f=await N("start")}catch(O){if(!(O instanceof r)||O.code!=="hands_job_result_unknown")throw O;f=await N("inspect")}if(c.phase="running",c.cancel=async()=>{await N("cancel")},w&&e.preview)c.tunnels=le({claim:e.claim,executorLaunchId:P.launchId,expiresAtMs:e.expiresAtMs,deniedPorts:e.preview.deniedPorts,inspect:async()=>c.phase==="running"&&!I?await N("probe"):null});if(c.cancelRequested)await c.cancel(),f=await N("inspect");for(;;){if(!["starting","running"].includes(f.state))c.phase="settling",c.cancel=void 0;if(!T||T.state!==f.state||T.next_cursor!==f.nextCursor&&Date.now()-oe>=5000)await ve(f);if(!["starting","running"].includes(f.state))break;if(e.signal.aborted||I)throw M();await ue(1000);try{f=await N("inspect"),te=void 0}catch(O){if(!(O instanceof r)||O.code!=="hands_job_result_unknown"||e.signal.aborted||I||Date.now()-(te??=Date.now())>120000)throw O}}if(!T||T.state==="uncertain")throw M();return T}finally{if(c.phase="settling",c.cancel=void 0,c.tunnels?.dispose(),c.tunnels=void 0,await c.cancelInFlight?.catch(()=>{}),e.signal.removeEventListener("abort",re),!I&&!U)st(x,"SIGTERM");let m,S=await Promise.race([F.then((f)=>({code:f})),new Promise((f)=>{m=setTimeout(()=>f(null),6000)})]).finally(()=>{clearTimeout(m)});if(!S){try{st(x,"SIGKILL")}catch{}try{await F}finally{if(I)l.disposeSocket()}throw M("process_cleanup_unconfirmed")}try{if((U||e.signal.aborted)&&S.code===0&&q){v(E);let f=JSON.parse(h(P.directTerminalReceiptPath)),O=X.safeParse(f.observation);if(Object.keys(f).length===4&&f.launch_id===P.launchId&&f.fence_id===P.fenceId&&f.scope_id===l.scopeId&&O.success&&O.data.process_id===e.claim.operation_id){if(w)z();throw new it(O.data)}}}catch(f){if(f instanceof it)throw f}finally{if(I)l.disposeSocket()}if(S.code!==0&&!U&&q)throw M("process_cleanup_unconfirmed");if(!U&&S.code===0&&(T&&["exited","cancelled","expired"].includes(T.state)||!q&&c.cancelRequested)||w&&S.code===0&&!q)z()}}async function Ns(e,c){if(c.kind===ce&&e.capability===he){let C=V.get(e.operation_id);if(C?.claim===e&&C.tunnels)C.tunnels.open(c.payload);else Y(c.payload,e.operation_id,"server_not_running");return!0}if(c.kind!==ne||!ae(e.capability)||!e.owner||c.payload.process_id!==e.operation_id)return!1;let _=V.get(e.operation_id);if(_&&_.claim!==e)return!1;let l=be(e);if(l.cancelRequested=!0,l.phase==="running"&&l.cancel)l.cancelInFlight??=l.cancel(),await l.cancelInFlight;return!0}function Ls(e,c){V.delete(e);let _=B.get(e);if(!_||c!=="succeeded"&&!_.anyCompletion)return B.delete(e),!1;try{let l=me(_.path);if(!l.isDirectory()||l.isSymbolicLink()||l.ino!==_.ino||l.dev!==_.dev||!A(l)||G(_.path)!==_.path||Z(j(_.path,"owner.lock")))return!1;return Ve(_.path,{recursive:!0}),B.delete(e),!0}catch{return!1}}
|
|
4
|
+
export{Wi,Vi,fn,Gi,mn,Ki,it,dr,Ns,Ls};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{he}from"./vm-hands-entry-lite-
|
|
2
|
+
import{he}from"./vm-hands-entry-lite-f5501hn3.js";var un=he(function(t,e){e.exports={name:"playwright-core",version:"1.60.0",description:"A high-level API to automate web browsers",repository:{type:"git",url:"git+https://github.com/microsoft/playwright.git"},homepage:"https://playwright.dev",engines:{node:">=18"},author:{name:"Microsoft Corporation"},license:"Apache-2.0",exports:{".":{types:"./index.d.ts",import:"./index.mjs",require:"./index.js",default:"./index.js"},"./package.json":"./package.json","./lib/bootstrap":"./lib/bootstrap.js","./lib/coreBundle":"./lib/coreBundle.js","./lib/utilsBundle":"./lib/utilsBundle.js","./lib/tools/cli-client/program":"./lib/tools/cli-client/program.js"},bin:{"playwright-core":"cli.js"},types:"types/types.d.ts"}});
|
|
3
3
|
export{un};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$n,Eo,zt}from"./vm-hands-entry-lite-eabever7.js";import{On,Ve,po,In,Dn,Nn,Pr,x}from"./vm-hands-entry-lite-
|
|
2
|
+
import{$n,Eo,zt}from"./vm-hands-entry-lite-eabever7.js";import{On,Ve,po,In,Dn,Nn,Pr,x}from"./vm-hands-entry-lite-t6f1f51j.js";import{xt}from"./vm-hands-entry-lite-kkfefpq6.js";import{Dr}from"./vm-hands-entry-lite-cswyn85b.js";import{j}from"./vm-hands-entry-lite-8pgdcdsm.js";import{a}from"./vm-hands-entry-lite-y2khvb5c.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as z,spawn as H}from"child_process";import{randomBytes as Qe}from"crypto";import{chmodSync as De,existsSync as I,lstatSync as _e,mkdirSync as we,readFileSync as Re,rmSync as ee,writeFileSync as g}from"fs";import{connect as de}from"net";import{join as y}from"path";var S=32,w=76;var B="./desktop-wallpaper-0pjhgyfk.jpg";var O="./dock-browser-afp005mt.png";var F="./dock-files-rywdm96b.png";var k="./dock-terminal-s41cj1jp.png";var K=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
|
|
3
3
|
# The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
|
|
4
4
|
# python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
|
|
5
5
|
# Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
|
|
@@ -120,9 +120,9 @@ Type=Application
|
|
|
120
120
|
Categories=System;FileManager;
|
|
121
121
|
`;var V={"wallpaper.jpg":B,"dock-browser.png":O,"dock-terminal.png":k,"dock-files.png":F},Te=K,he='set_wallpaper() { if command -v feh >/dev/null 2>&1; then feh --bg-fill "$1"; else python3 "$2" "$1"; fi; }';function v(e){let s=(i)=>i.replaceAll("DISPLAY=:99",`DISPLAY=${e.display}`).replaceAll("/tmp/ara-",`${e.root}/ara-`),p=new Set(e.absent??[]),n=le.split(`
|
|
122
122
|
`).filter((i)=>!(p.has("terminal")&&i.endsWith("/ara-terminal.desktop"))&&!(p.has("files")&&i.endsWith("/ara-files.desktop"))).join(`
|
|
123
|
-
`),t={"openbox/rc.xml":ye(e.screen),"tint2/tint2rc":s(n),"picom/picom.conf":ue,...p.has("terminal")?{}:{"ara-terminal.desktop":s(Xe)},...p.has("files")?{}:{"ara-files.desktop":s(fe)},"ara-chromium.desktop":s(Se).replace("chromium --no-sandbox %U",e.browserExec),"ara-set-root-wallpaper.py":Te},o=[...R.slice(0,3),he,'[ ! -f "$ROOT/ara-wallpaper.jpg" ] || set_wallpaper "$ROOT/ara-wallpaper.jpg" "$ROOT/ara-set-root-wallpaper.py" || true',...R.slice(3)];return{files:t,start:o}}var R=['ticks() { line=$(cat "/proc/$1/stat" 2>/dev/null) || return 1; rest=${line##*) }; case $rest in Z*|X*) return 1;; esac; printf "%s" "$rest" | cut -d " " -f20; }','alive() { [ -f "$ROOT/$1.pid" ] || return 1; read -r pid start <"$ROOT/$1.pid"; current=$(ticks "$pid") || return 1; [ "$current" = "$start" ] && kill -0 "$pid" 2>/dev/null; }','launch() { name=$1; shift; "$@" 9>&- >"$ROOT/$name.log" 2>&1 & pid=$!; start=$(ticks "$pid"); printf "%s %s\\n" "$pid" "$start" >"$ROOT/$name.pid"; }','if [ -f "$ROOT/tint2/tint2rc" ] && ! alive tint2 && command -v tint2 >/dev/null 2>&1; then launch tint2 tint2 -c "$ROOT/tint2/tint2rc"; fi','if [ -f "$ROOT/picom/picom.conf" ] && ! alive picom && command -v picom >/dev/null 2>&1; then launch picom picom --config "$ROOT/picom/picom.conf"; fi'];var Ae=43200000,D=":99",Ee=60000,_=15000,C={width:1280,height:800},Ne=/^[A-Za-z0-9._:-]{1,160}$/;function Le(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}var Je=["video","viewer","viewer_same_network","viewer_network"];function Ce(e,s=Date.now()){let p=["relay_url","session_id","expires_at"];if(!Le(e)||p.some((c)=>!(c in e))||Object.keys(e).some((c)=>!p.includes(c)&&!Je.includes(c)))throw new r("invalid_display_request","Reason desktop request is malformed.");let n="video"in e?Eo(e.video):void 0,t="viewer"in e?$n(e.viewer):null;if(n===null)throw new r("invalid_display_request","Reason desktop video request is invalid.");let o=null;try{o=typeof e.relay_url==="string"?new URL(e.relay_url):null}catch{}if(!o||o.protocol!=="wss:"&&o.protocol!=="ws:"||o.username||o.password)throw new r("invalid_display_request","Reason desktop relay URL is invalid.");if(typeof e.session_id!=="string"||!Ne.test(e.session_id))throw new r("invalid_display_request","Reason desktop session identity is invalid.");let i=typeof e.expires_at==="string"?Date.parse(e.expires_at):Number.NaN;if(!Number.isFinite(i)||i<=s)throw new r("invalid_display_request","Reason desktop session has already expired.");return{relay_url:e.relay_url,session_id:e.session_id,expires_at:new Date(Math.min(i,s+Ae)).toISOString(),...n?{video:n}:{},...t?{viewer:t}:{},...n&&e.viewer_same_network===!0?{viewer_same_network:!0}:{}}}function $t(e=process.platform){return(e==="linux"||e==="darwin"||e==="win32")&&x()?.features.display===!0}async function
|
|
123
|
+
`),t={"openbox/rc.xml":ye(e.screen),"tint2/tint2rc":s(n),"picom/picom.conf":ue,...p.has("terminal")?{}:{"ara-terminal.desktop":s(Xe)},...p.has("files")?{}:{"ara-files.desktop":s(fe)},"ara-chromium.desktop":s(Se).replace("chromium --no-sandbox %U",e.browserExec),"ara-set-root-wallpaper.py":Te},o=[...R.slice(0,3),he,'[ ! -f "$ROOT/ara-wallpaper.jpg" ] || set_wallpaper "$ROOT/ara-wallpaper.jpg" "$ROOT/ara-set-root-wallpaper.py" || true',...R.slice(3)];return{files:t,start:o}}var R=['ticks() { line=$(cat "/proc/$1/stat" 2>/dev/null) || return 1; rest=${line##*) }; case $rest in Z*|X*) return 1;; esac; printf "%s" "$rest" | cut -d " " -f20; }','alive() { [ -f "$ROOT/$1.pid" ] || return 1; read -r pid start <"$ROOT/$1.pid"; current=$(ticks "$pid") || return 1; [ "$current" = "$start" ] && kill -0 "$pid" 2>/dev/null; }','launch() { name=$1; shift; "$@" 9>&- >"$ROOT/$name.log" 2>&1 & pid=$!; start=$(ticks "$pid"); printf "%s %s\\n" "$pid" "$start" >"$ROOT/$name.pid"; }','if [ -f "$ROOT/tint2/tint2rc" ] && ! alive tint2 && command -v tint2 >/dev/null 2>&1; then launch tint2 tint2 -c "$ROOT/tint2/tint2rc"; fi','if [ -f "$ROOT/picom/picom.conf" ] && ! alive picom && command -v picom >/dev/null 2>&1; then launch picom picom --config "$ROOT/picom/picom.conf"; fi'];var Ae=43200000,D=":99",Ee=60000,_=15000,C={width:1280,height:800},Ne=/^[A-Za-z0-9._:-]{1,160}$/;function Le(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}var Je=["video","viewer","viewer_same_network","viewer_network"];function Ce(e,s=Date.now()){let p=["relay_url","session_id","expires_at"];if(!Le(e)||p.some((c)=>!(c in e))||Object.keys(e).some((c)=>!p.includes(c)&&!Je.includes(c)))throw new r("invalid_display_request","Reason desktop request is malformed.");let n="video"in e?Eo(e.video):void 0,t="viewer"in e?$n(e.viewer):null;if(n===null)throw new r("invalid_display_request","Reason desktop video request is invalid.");let o=null;try{o=typeof e.relay_url==="string"?new URL(e.relay_url):null}catch{}if(!o||o.protocol!=="wss:"&&o.protocol!=="ws:"||o.username||o.password)throw new r("invalid_display_request","Reason desktop relay URL is invalid.");if(typeof e.session_id!=="string"||!Ne.test(e.session_id))throw new r("invalid_display_request","Reason desktop session identity is invalid.");let i=typeof e.expires_at==="string"?Date.parse(e.expires_at):Number.NaN;if(!Number.isFinite(i)||i<=s)throw new r("invalid_display_request","Reason desktop session has already expired.");return{relay_url:e.relay_url,session_id:e.session_id,expires_at:new Date(Math.min(i,s+Ae)).toISOString(),...n?{video:n}:{},...t?{viewer:t}:{},...n&&e.viewer_same_network===!0?{viewer_same_network:!0}:{}}}function $t(e=process.platform){return(e==="linux"||e==="darwin"||e==="win32")&&x()?.features.display===!0}async function js(){if(process.platform==="win32")return $t()&&await Pr();if(process.platform!=="darwin")return $t();return await Pr()}function G(e){we(e,{recursive:!0,mode:448});let s=_e(e);if(!s.isDirectory()||s.isSymbolicLink()||process.getuid&&s.uid!==process.getuid())throw new r("display_unavailable","Reason desktop state directory is not private.");De(e,448)}function Ue(e,s){let p=(t)=>{let o=Buffer.alloc(2);return o.writeUInt16BE(t.length),Buffer.concat([o,t])},n=Buffer.from([255,255]);return Buffer.concat([n,p(Buffer.alloc(0)),p(Buffer.from(e)),p(Buffer.from("MIT-MAGIC-COOKIE-1")),p(s)])}function T(e,s,p=2000){return new Promise((n)=>{let t=de(e),o="",i=(c)=>{t.destroy(),n(c)};t.setTimeout(p,()=>i(!1)),t.once("error",()=>i(!1)),t.once("close",()=>i(!1)),t.once("connect",()=>{if(!s)i(!0)}),t.on("data",(c)=>{if(o+=c.toString("latin1"),o.length>=4)i(o.startsWith("RFB "))})})}async function m(e,s){let p=Date.now()+s;while(Date.now()<p){if(await e())return!0;await new Promise((n)=>setTimeout(n,100))}return!1}function d(e,s,p){return new Promise((n)=>{let t=H(e,s,{detached:!0,stdio:"ignore",env:p});t.once("error",()=>n(-1)),t.once("exit",(o)=>n(o)),t.unref(),setTimeout(()=>n(null),_).unref()})}var U=null;function qe(e=a()){return U??=ge(e).finally(()=>{U=null}),U}async function ge(e){let s=x({home:e});if(!s?.xvfb||!s.x11vnc||!s.openbox)throw new r("display_unavailable","Run `reason desktop install` on this machine to enable its desktop.");xt({root:s.root,automation:s.automation,extensionDir:s.extensionDir});let p=y(s.root,"display");G(p);let n=await Me(e,p,s.x11vnc);if(n)return n;let t={display:D,xauthority:y(p,"Xauthority"),rfbSocket:y(p,"rfb.sock")},o=y(p,"pulse"),i=(async()=>{try{G(o)}catch{return null}return await po(o,s.pulseaudio)})();G(y(p,"home"));let c=re(p,t,s.pulseaudio),h=async()=>({...t,sound:await i});if(await T({path:t.rfbSocket},!0))return pe(y(p,"theme"),R,c),await h();if(!I(t.xauthority))g(t.xauthority,Ue(D.slice(1),Qe(16)),{mode:384,flag:"wx"});let l=te(y(p,"theme"),t.display,C),q={path:`/tmp/.X11-unix/X${D.slice(1)}`};if(!await T(q,!1)){let u=`${C.width}x${C.height}`;if(s.xvnc)ee(t.rfbSocket,{force:!0}),d(s.xvnc,[t.display,"-geometry",u,"-depth","24","-nolisten","tcp","-auth",t.xauthority,"-rfbport","-1","-rfbunixpath",t.rfbSocket,"-SecurityTypes","None","-UseBlacklist=0","-AlwaysShared","-desktop","Reason"],c);else d(s.xvfb,[t.display,"-screen","0",`${u}x24`,"-nolisten","tcp","-auth",t.xauthority],c);if(!await m(()=>T(q,!1),_)||s.xvnc&&!await m(()=>T({path:t.rfbSocket},!0),_))throw new r("display_unavailable","Reason could not start the virtual display.");d(s.openbox,["--config-file",l.openboxConfig],c)}if(await ne(l,c),!await se(s.x11vnc,t,p,"x11vnc.log",c))throw new r("display_unavailable","Reason could not start the desktop server.");return await h()}function re(e,s,p){let n={HOME:y(e,"home"),PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:s.display,XAUTHORITY:s.xauthority};if(p)n.PULSE_SERVER=Ve(On(y(e,"pulse")));return n}async function se(e,s,p,n,t){if(await T({path:s.rfbSocket},!0))return!0;ee(s.rfbSocket,{force:!0});let o=await d(e,["-display",s.display,"-auth",s.xauthority,"-rfbport","0","-rfbportv6","-1","-unixsock",s.rfbSocket,"-nopw","-forever","-shared","-noxdamage","-sb","0","-rfbversion","3.7","-quiet","-bg","-o",y(p,n)],t);if(o!==null&&o!==0)return!1;return await m(()=>T({path:s.rfbSocket},!0),_)}async function me(){let e=["DISPLAY","XAUTHORITY","WAYLAND_DISPLAY","XDG_SESSION_TYPE"],s=(p)=>Object.fromEntries(e.flatMap((n)=>p[n]?[[n,p[n]]]:[]));if(process.env.DISPLAY)return s(process.env);try{let p=await new Promise((n,t)=>z("systemctl",["--user","show-environment"],{encoding:"utf8",timeout:2000},(o,i)=>o?t(o):n(i)));return s(Object.fromEntries(p.split(`
|
|
124
124
|
`).flatMap((n)=>{let t=n.indexOf("=");return t>0?[[n.slice(0,t),n.slice(t+1)]]:[]})))}catch{return{}}}var Z=new Set;async function Me(e,s,p){let n=await me(),t=/^:(\d+)(?:\.\d+)?$/.exec(n.DISPLAY??"")?.[1];if(!t||`:${t}`===D||n.WAYLAND_DISPLAY||n.XDG_SESSION_TYPE==="wayland")return null;let o={display:`:${t}`,xauthority:n.XAUTHORITY??y(e,".Xauthority"),rfbSocket:y(s,`rfb-${t}.sock`)},i=`${o.display} ${o.xauthority}`;if(Z.has(i)||!await T({path:`/tmp/.X11-unix/X${t}`},!1))return null;let c={HOME:e,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:o.display,XAUTHORITY:o.xauthority};if(await se(p,o,s,`x11vnc-${t}.log`,c))return{...o,sound:null};return Z.add(i),process.stderr.write(`Reason worker: your screen ${o.display} could not be served; using the virtual desktop
|
|
125
125
|
`),null}function te(e,s,p){let n=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,t=[["terminal","xterm"],["files","pcmanfm"]].filter(([,i])=>!I(`/usr/bin/${i}`)).map(([i])=>i),o=v({root:e,display:s,screen:p,browserExec:n,absent:t});for(let i of["","openbox","tint2","picom"])G(y(e,i));for(let[i,c]of Object.entries(o.files))g(y(e,i),c,{mode:384});for(let[i,c]of Object.entries(V))g(y(e,`ara-${i}`),Re(c),{mode:384});return{root:e,openboxConfig:y(e,"openbox","rc.xml"),start:o.start}}function ne(e,s){return pe(e.root,[...e.start,"openbox --reconfigure >/dev/null 2>&1 || true"],s)}function pe(e,s,p){let n=[`ROOT=${JSON.stringify(e)}`,...s].join(`
|
|
126
126
|
`);return new Promise((t)=>{let o=H("/bin/sh",["-c",n],{stdio:"ignore",env:{...p,PATH:"/usr/bin:/bin"}}),i=setTimeout(()=>{o.kill(),t()},_);o.once("error",()=>{clearTimeout(i),t()}),o.once("exit",()=>{clearTimeout(i),t()})})}var We=2073600,je=320;function Be(e,s){let p=Math.min(1,Math.sqrt(We/(e.width*e.height))),n=(t,o)=>Math.min(Math.floor(o/8)*8,Math.max(je,Math.round(t*p/8)*8));return{width:n(e.width,s.width),height:n(e.height,s.height)}}function oe(e,s,p){return new Promise((n)=>z(e,s,{env:p,encoding:"utf8",timeout:5000},(t,o)=>n(t?null:o)))}function Oe(e){let s=/current (\d+) x (\d+), maximum (\d+) x (\d+)/.exec(e),p=e.split(`
|
|
127
127
|
`),n=p.findIndex((o)=>/^\S+ connected/.test(o));if(!s||n<0)return null;let t=[];for(let o of p.slice(n+1)){let i=/^\s+(\d+x\d+)\s/.exec(o);if(!i)break;t.push(i[1])}return{current:{width:Number(s[1]),height:Number(s[2])},maximum:{width:Number(s[3]),height:Number(s[4])},output:p[n].split(" ")[0],modes:t}}async function Fe(e,s,p){if(e.display!==D)return null;let n={PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority},t=(h)=>oe("xrandr",h,n),o=Oe(await t(["--query"])??"");if(!o||o.maximum.width<=o.current.width&&o.maximum.height<=o.current.height)return null;let i=Be(s,o.maximum);if(i.width===o.current.width&&i.height===o.current.height)return{size:i,changed:!1};let c=`${i.width}x${i.height}`;if(!o.modes.includes(c)){if(await t(["--newmode",c,"60",...[i.width,i.width,i.width,i.width,i.height,i.height,i.height,i.height].map(String)]),await t(["--addmode",o.output,c])===null)return null}return p(),await t(["--output",o.output,"--mode",c])===null?null:{size:i,changed:!0}}async function ke(e,s){let p=x({home:a()});if(!p)return;let n=y(p.root,"display"),t=re(n,e,p.pulseaudio);await ne(te(y(n,"theme"),e.display,s),t);let o=s.width-S*2,i=s.height-S-w;await oe("xdotool",["search","--onlyvisible","--class","Chromium","windowsize","%@",String(o),String(i),"windowmove","%@",String(S),String(S)],{...t,PATH:"/usr/bin:/bin"})}var Y=Promise.resolve();function Ge(e,s,p=()=>{}){let n=Y.then(()=>Fe(e,s,p));return Y=n.then((t)=>t?.changed?ke(e,t.size):void 0).catch(()=>{}),n.then((t)=>t?.size??null,()=>null)}async function Bt(e,s={}){let p=s.now??Date.now,n=Ce(e.payload,p());if(e.signal.throwIfAborted(),!n.video)throw new r("display_video_required","Reason desktops stream as video now; this request came without it.");let t=s.platform??process.platform;if(t!=="linux"&&t!=="darwin"&&t!=="win32")throw new r("display_video_unsupported","This machine does not serve desktop video.");let o=n.video,i=(s.video?.desktop??(t==="darwin"?async()=>In:t==="win32"?async()=>Dn:qe))();return await Ke(e.signal,n,s,p,(c)=>Nn(c,{request:o,desktop:i,...n.viewer?{viewer:n.viewer}:{},viewerSameNetwork:n.viewer_same_network===!0},{resizeDesktop:Ge,...s.video}),(c)=>zt({type:"error",code:c}))}function Ke(e,s,p,n,t,o){let i=n();return new Promise((c,h)=>{let l=null,q=!1,u=!1,M,A,Q,E=!1,P=null,X=(b)=>{if(u)return;if(P)b=P.outcome;u=!0,clearTimeout(M),clearTimeout(A),e.removeEventListener("abort",L),Q?.close();try{l?.close(1000,"display_session_over")}catch{}if("error"in b){h(b.error);return}c({reason:b.reason,...Q?.summary(),duration_ms:Math.max(0,n()-i)})},N=()=>X({error:new r("display_relay_unavailable","Reason could not reach the desktop relay.")}),L=()=>{let b=e.reason;X({error:b instanceof r?b:new r("cancelled","Reason closed the desktop session.")})},W=()=>{if(!P||!l)return;let{outcome:b}=P,f=!("error"in b)?b.reason:b.error instanceof r?b.error.code:"display_unavailable";if(!P.told)try{l.send(o(f))}catch{}X(b)};if(Q=t({get done(){return u||P!==null},get open(){return q&&!u&&P===null},get bufferedAmount(){return l?.bufferedAmount??0},send(b){if(u||P||!q||!l)return;try{l.send(b)}catch{X({reason:"relay_closed"})}},end:(b)=>{if(u||P)return;if(!("error"in b)&&E&&q){X(b);return}if(P={outcome:b,told:!("error"in b)&&q},E&&q)W()}}),u){Q.close();return}if(e.aborted){L();return}e.addEventListener("abort",L,{once:!0}),M=setTimeout(()=>X({reason:"session_expired"}),Math.max(1,Date.parse(s.expires_at)-n())),A=setTimeout(()=>X({reason:"viewer_absent"}),p.viewerWaitMs??Ee);try{l=(p.connect??Dr)(s.relay_url,(p.loadProxy??j)()?.url)}catch{N();return}l.binaryType="arraybuffer",l.onopen=()=>{if(u||!l)return;q=!0,Q?.opened()},l.onmessage=(b)=>{if(u)return;let f=b.data,J=f instanceof ArrayBuffer?new Uint8Array(f):ArrayBuffer.isView(f)?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):null;if(!J||J.byteLength===0)return;if(clearTimeout(A),E=!0,P){W();return}Q?.received(J)},l.onclose=()=>{if(u)return;if(!q){N();return}X({reason:"relay_closed"})},l.onerror=()=>{if(u||q)return;N()}})}
|
|
128
|
-
export{$t,
|
|
128
|
+
export{$t,js,G,qe,Bt};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{Do}from"./vm-hands-entry-lite-nqdstx24.js";import{Fe,an,Tt,cn}from"./vm-hands-entry-lite-f62fvme8.js";import{Qn}from"./vm-hands-entry-lite-kz26rfcv.js";import{t,o,d,u,i,cs,W,g,s,n}from"./vm-hands-entry-lite-gvjffc5t.js";var M=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function k(e){let r=typeof e==="string"?M.exec(e):null;return r?{major:Number(r[1]),minor:Number(r[2])}:null}var E=25,v=1e5,L=/^[0-9a-f]{64}$/,N=i({day:t().regex(/^\d{4}-\d{2}-\d{2}$/),sent:o().int().min(0).max(v),received:o().int().min(0).max(v)}),xe=i({machine:t().min(1).max(200),person:t().min(1).max(200),team:t().min(1).max(200),team_id:t().min(1).max(200).optional(),workspace:d().optional(),version:t().max(64).optional(),wait_seconds:o().int().min(0).max(E).optional(),message_counts:u(N).max(14).optional().catch(void 0),endpoint:t().regex(L).optional().catch(void 0)}),D=g("kind",[i({id:t(),kind:n("who"),all:d().optional()}),i({id:t(),kind:n("send"),to:t(),body:t(),from_name:t(),from_agent:t(),wake:d(),reply_to:t().max(100).optional(),notify:d().optional()})]),P=i({job:D.nullable(),retry_after_seconds:o().optional()}),H=i({address:t(),person:t(),machine:t(),agent:t(),repo:t().nullable(),branch:t().nullable(),status:t(),since:o().nullable(),doing:t().nullable(),worker:d(),tier:t().max(10).optional()}),B=i({person:t(),machine:t(),online:d()}),F=i({team:t().nullable(),sessions:u(H).max(2000),machines:u(B).max(500),all:d().optional()}),J=i({address:t().max(300),state:t().max(40),note:t().max(500)}),Ie=W([i({who:F}),i({sent:i({ids:u(t().max(100)).max(500),recipients:u(t().max(300)).max(500),from:t().max(300),deliveries:u(J).max(500).optional()})}),i({error:t().min(1).max(2000)})]),G=i({id:t().max(100),from:t().max(300),from_agent:t().max(100).nullable(),to:t().max(300),reply_to:t().max(100).nullable(),body:t().max(64000),sent_at:o()}),Ce=i({messages:u(G).max(100),team:t().min(1).max(200).optional(),team_id:t().min(1).max(200).optional(),workspace:d().optional()});var x=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var Be=x.filter((e)=>e!=="network:read"&&e!=="network:write");class R extends Error{oauthCode;constructor(e,r=null){super(e);this.oauthCode=r;this.name="LoginError"}}function Q(e,r){let a=typeof e.error==="string"?e.error:null,l=typeof e.error_description==="string"?e.error_description:a?a:r;return new R(l,a)}async function K(e,r,a,l){let c=await a(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:r,signal:l}),m=await c.json().catch(()=>({}));if(!c.ok)throw Q(m,`OAuth token request failed (${c.status})`);return m}var V=1e4;async function Y(e,r={}){let a=r.fetchImpl??fetch,l=await K(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),a,AbortSignal.timeout(V)).catch((m)=>{if(m instanceof Error&&m.name==="TimeoutError")throw new R("Reason did not answer the login refresh in time. Check the network and retry.");throw m});if(typeof l.access_token!=="string"||typeof l.refresh_token!=="string"||typeof l.expires_in!=="number")throw new R("Reason returned an incomplete refreshed login.");let c={...e,accessToken:l.access_token,refreshToken:l.refresh_token,expiresAt:new Date(Date.now()+l.expires_in*1000).toISOString(),scopes:typeof l.scope==="string"?l.scope.split(/\s+/).filter(Boolean):e.scopes};return an(c,r.path??Fe()),c}var b=new Map,X=2000,Z=100;function C(e,r){if(!r)return e;if(r.aborted)return Promise.reject(r.reason);return new Promise((a,l)=>{let c=()=>l(r.reason);r.addEventListener("abort",c,{once:!0}),e.then(a,l).finally(()=>r.removeEventListener("abort",c))})}async function Pt(e={}){let r=e.path??Fe(),a=Tt(r);if(!a)return null;let l=e.apiOrigin??T(process.env,"REASON_API_URL")?.trim();if(l&&!Do(a.apiOrigin,new URL(l).origin))return null;if(!(Date.parse(a.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&a.accessToken!==e.refused))return a;let m=[r,a.apiOrigin,a.clientId,a.refreshToken].join("\x00"),p=b.get(m);if(p)return C(p,e.signal);let f;return f=Y(a,{fetchImpl:e.fetchImpl,path:r}).catch(async(y)=>{if(!(y instanceof R)||y.oauthCode!=="invalid_grant"&&y.oauthCode!=="invalid_client")throw y;let S=(_)=>_!==null&&(y.oauthCode==="invalid_client"?_.clientId!==a.clientId:_.refreshToken!==a.refreshToken),z=Date.now()+X;while(!S(Tt(r))&&Date.now()<z)await new Promise((_)=>setTimeout(_,Z));if(S(Tt(r)))return Pt({fetchImpl:e.fetchImpl,path:r});return cn(r),null}).finally(()=>{if(b.get(m)===f)b.delete(m)}),b.set(m,f),C(f,e.signal)}var ee=i({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:d().nullable()}),ne=i({groups:u(i({selectable:d().optional(),accounts:u(i({source_id:t().min(1),model_ids:u(t().min(1)).optional()}))}))});function te(e){let r=ne.safeParse(e);if(!r.success)return;return r.data.groups.some((a)=>a.selectable!==!1&&a.accounts.some((l)=>l.model_ids===void 0||l.model_ids.length>0))}class I extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor(e,r,a,l,c,m){super(a);this.status=e;this.code=r;this.suggestedModel=l;this.retryAfterMs=c;this.resolutionReason=m;this.name="ApiError"}static rateLimitDelayMs(e,r){if(!(e instanceof I)||e.status!==429)return null;return Math.min(60000,Math.max(r,e.retryAfterMs??0))}}var se=["minimal","low","medium","high","xhigh","max"],oe=i({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:d(),compatible:d().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:u(i({id:t().min(1),label:t()}))}),re=i({devices:u(oe),end_cursor:t().nullish(),has_next_page:d().optional()}),ie=i({id:t().min(1),name:t()}),ae=i({items:u(ie)}),le=i({id:t().min(1),name:t(),main:d(),mine:d(),session_id:t().nullish(),appearance:i({color:t().nullish()}).nullish().catch(null)}),ce=i({items:u(le)}),de=i({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:u(t()).default([]),is_enabled:d().default(!0)}),me=i({items:u(de).default([])}),ue=i({id:t().min(1),kind:t(),enabled:d(),schedule:i({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:i({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),U=i({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:d(),triggers:u(ue).default([])}),ge=i({items:u(U).default([]),end_cursor:t().nullish(),has_next_page:d().optional()}),he=i({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:d()}),pe=i({items:u(he).default([])}),fe=i({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),A=i({tags:u(t()).default([])}),ye=s(["linux","macos"]),q=i({id:t().min(1),name:t().min(1),platform:ye.nullable(),workers:i({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:i({queued:o().int(),running:o().int()})}),_e=i({machines:u(q)}),Re=i({machine:q}),be=i({deleted:n(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),we=i({token:i({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),O=cs({machine_id:t().min(1),machine_name:t().min(1)}),Se=O.extend({organization_id:t().min(1)}),Ye=i({id:t().min(1),name:t().min(1),state:s(["waiting","placed"]),queue_position:o().int().nullable()});var Xe=W([i({kind:n("cloud")}),i({kind:s(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function h(e,r,a){let l=e.safeParse(r);if(!l.success)throw new I(502,a,"Reason returned an unexpected response.");return l.data}var ke=i({error:i({type:t(),message:t()})});function w(e,r,a){let l=ke.safeParse(r),c=typeof r.error==="string"?r.error:l.success?l.data.error.type:`http_${e}`,m=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:l.success?l.data.error.message:`Reason request failed (${e}${typeof r.error==="string"?` ${r.error}`:""})`,p=c==="github_connection_required"&&typeof r.connect_url==="string"&&/^https?:\/\//.test(r.connect_url)?` Connect it at ${r.connect_url}`:"",f=a===null||a.trim()===""?NaN:Number(a);return new I(e,c,`${m}${p}`,typeof r.suggested_model==="string"?r.suggested_model:void 0,Number.isFinite(f)&&f>=0?f*1000:void 0,typeof r.resolution_reason==="string"?r.resolution_reason:void 0)}async function bs(e){let r=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),a=await r.json().catch(()=>({}));if(!r.ok)throw w(r.status,a,r.headers.get("retry-after"));return h(Se,a,"invalid_machine_ticket")}class Ko{options;credentials;constructor(e,r={}){this.options=r;this.credentials=e}trackEvent(e,r={}){}async request(e,r={}){let{status:a,headers:l,json:c}=await this.exchange(e,r);if(a<200||a>299)throw w(a,c,l.get("retry-after"));return c}async exchange(e,r={},a=!1){let l=this.options.fetchImpl??fetch,c=await l(`${this.credentials.apiOrigin}/v3${e}`,{method:r.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Qn,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...r.raw?{"content-type":r.raw.contentType}:r.body===void 0?{}:{"content-type":"application/json"},...r.headers,...r.ifNoneMatch?{"if-none-match":r.ifNoneMatch}:{}},body:r.raw?r.raw.bytes:r.body===void 0?void 0:JSON.stringify(r.body),signal:r.signal,redirect:r.ifNoneMatch?"manual":"error"}),m=await c.json().catch(()=>({}));if(c.status===401&&!a&&r.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let p=await Pt({fetchImpl:l,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:r.signal});if(p)return this.credentials=p,this.exchange(e,r,!0)}return{status:c.status,headers:c.headers,json:m}}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(r){if(r instanceof I&&(r.status===404||r.status===405||r.status===403&&r.code==="endpoint_not_available"))return null;throw r}}addDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(r)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,r=""){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?a:`${a}/${encodeURIComponent(e)}${r}`}async listMachines(){return h(_e,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let r=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return h(Re,r,"invalid_machine").machine}async deleteMachine(e){let r=await this.request(this.machinePath(e),{method:"DELETE"});return h(be,r,"invalid_machine_deletion")}async createMachineToken(e){let r=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return h(we,r,"invalid_machine_token")}async createMachineEnrollmentTicket(e,r){let a=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:r,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return h(O,a,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:r});return h(P,a,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((r)=>typeof r.email==="string"?[{email:r.email,role:typeof r.role==="string"?r.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,r,a={}){let l=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:a.retryUnauthorized,signal:a.signal,body:{...l,...r?{account_key:r}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((r)=>{let a=typeof r.full_name==="string"?r.full_name:typeof r.repo_full_name==="string"?r.repo_full_name:null;if(!a)return[];return[{repo_id:typeof r.repo_id==="string"?r.repo_id:void 0,full_name:a,provider:r.provider==="gitlab"?"gitlab":"github",default_branch:typeof r.default_branch==="string"?r.default_branch:null,private:typeof r.private==="boolean"?r.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),r=ae.safeParse(e);if(!r.success)throw new I(502,"invalid_project_list","Reason returned an unexpected project list.");return r.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return h(ce,e,"invalid_reason_list").items}async openReasonConversation(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return h(i({session_id:t().min(1)}),r,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return h(me,e,"invalid_skill_list").items}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${r?`?after=${encodeURIComponent(r)}`:""}`),c=re.safeParse(l);if(!c.success)throw new I(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...c.data.devices),r=c.data.has_next_page?c.data.end_cursor??null:null,!r)break}return e}async listModels(){try{let r=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((c)=>c.hidden!==!0),a=r.filter((c)=>c.available!==!1).map(({reasoning_efforts:c,hidden:m,available:p,...f})=>({...f,...Array.isArray(c)?{reasoning_efforts:se.filter((y)=>c.includes(y))}:{}})),l=new Set(a.map((c)=>c.detail));return{models:a.length>1&&l.size===1?a.map(({detail:c,...m})=>m):a,runnable:a.length>0||r.length===0}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let r=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return k(r.reason_version)?r.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=ee.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let r;try{r=te(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:r}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let r=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)r.set("origin",e.origin);r.set("fields",e.fields.join(","));let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${r.toString()}`,{status:l,headers:c,json:m}=await this.exchange(a,e.etag?{ifNoneMatch:e.etag}:{});if(l===304)return null;if(l<200||l>299)throw w(l,m,c.get("retry-after"));return{items:Array.isArray(m.items)?m.items:[],etag:c.get("etag")}}async listSessions(e=50,r,a={}){let l=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:a.status??"active"});if(r)l.set("project_id",r);if(a.origin)l.set("origin",a.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${l.toString()}`)).items??[]}getSession(e,r){let a=r?.fields.length?`?fields=${encodeURIComponent(r.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${a}`)}async prestartSession(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return r?.status==="starting"||r?.status==="ready"}async createSession(e){let r=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(r||e.runtimeProfile){let c=await this.request("/deployment");if(r&&(!Array.isArray(c.session_modes)||!c.session_modes.includes(e.mode??"standard")||!Array.isArray(c.workspace_ownerships)||!c.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(c.experimental_runtime_profiles)||!c.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),l=await this.getSession(a.session_id);if(r){let c=l.session_policy,m=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!c||c.version!==1||c.mode!==(e.mode??"standard")||c.workspaceOwnership!==(e.workspaceOwnership??"managed")||!c.components||m.some((p)=>c.components[p]!==!0))throw await this.cancelSession(a.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&l.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(a.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return l}async getEvents(e,r=-1,a={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${r}&limit=500${a.waitMs?`&wait_ms=${a.waitMs}`:""}`,a.signal?{signal:a.signal}:{})}catch(l){if(!(l instanceof I)||l.status!==403&&l.status!==404)throw l;return{session:await this.getSession(e),items:[],next_seq:r}}}async getMessages(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${r===void 0?"":`&after_seq=${r}`}`)}async getAttachments(e,r){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${r?`?view=${r}`:""}`)).items??[]}catch(a){if(a instanceof I&&(a.status===403||a.status===404))return[];throw a}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let r=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,a=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,l=[r,a].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${l?` (${l})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,r,a={}){if(a.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:r,...a.attachments?.length?{attachments:a.attachments}:{},...a.model?{model:a.model}:{},...a.reasoningEffort?{reasoning_effort:a.reasoningEffort}:{},...a.target?{target:a.target}:{},...a.delivery?{delivery:a.delivery}:{}}})}async steerQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/queued`,{method:"DELETE"})}async getConversation(e){let r=[],a=null;for(let l=0;l<50;l+=1){let c=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${a?`?after=${encodeURIComponent(a)}`:""}`);if(r.push(...c.items??[]),!c.has_next_page||!c.end_cursor)break;a=c.end_cursor}return r}createSharedLink(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:r.url,...r.label?{label:r.label}:{},...r.expiresInSeconds!==void 0?{expires_in_seconds:r.expiresInSeconds}:{}}})}sessionAction(e,r,a={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${r}`,{method:"POST",body:a})}renameSession(e,r){return this.sessionAction(e,"rename",{title:r||null})}moveSessionToProject(e,r){return this.sessionAction(e,"project",{project_id:r})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,r){return this.sessionAction(e,"rewind",{message_id:r.messageId,content:r.content,request_id:r.requestId})}forkSession(e,r){return this.sessionAction(e,"fork",{...r.message?{message:r.message}:{},client_session_id:r.clientSessionId})}cancelSession(e,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:r.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,r=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return h(A,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,r){let a=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:r}});return h(A,a,"invalid_session_tags").tags}async sessionInsight(e,r=!1){let a=await this.request(this.sessionPath(e,r?"/insights/generate":"/insights"),r?{method:"POST",body:{}}:{});return h(fe,a,"invalid_session_insight")}async listAutomations(){let e=[],r=null;for(let a=0;a<20;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${r?`&after=${encodeURIComponent(r)}`:""}`),c=h(ge,l,"invalid_automation_list");if(e.push(...c.items),r=c.has_next_page?c.end_cursor??null:null,!r)break}return e}async createScheduledAutomation(e,r){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,l=h(U,await this.request(a,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${a}/${encodeURIComponent(l.id)}/triggers`,{method:"POST",body:r})}catch(c){throw await this.deleteAutomation(l.id).catch(()=>{return}),c}return l}async setAutomationEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:r}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:r}});return h(i({transcript:t()}),a,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return h(pe,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:r}})}}
|
|
3
|
-
export{Pt,I,
|
|
2
|
+
import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{Do}from"./vm-hands-entry-lite-nqdstx24.js";import{Fe,an,Tt,cn}from"./vm-hands-entry-lite-f62fvme8.js";import{Qn}from"./vm-hands-entry-lite-439wxzv9.js";import{t,o,d,u,i,us,W,g,s,n}from"./vm-hands-entry-lite-w2n56kvf.js";var M=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function k(e){let r=typeof e==="string"?M.exec(e):null;return r?{major:Number(r[1]),minor:Number(r[2])}:null}var E=25,v=1e5,L=/^[0-9a-f]{64}$/,N=i({day:t().regex(/^\d{4}-\d{2}-\d{2}$/),sent:o().int().min(0).max(v),received:o().int().min(0).max(v)}),xe=i({machine:t().min(1).max(200),person:t().min(1).max(200),team:t().min(1).max(200),team_id:t().min(1).max(200).optional(),workspace:d().optional(),version:t().max(64).optional(),wait_seconds:o().int().min(0).max(E).optional(),message_counts:u(N).max(14).optional().catch(void 0),endpoint:t().regex(L).optional().catch(void 0)}),D=g("kind",[i({id:t(),kind:n("who"),all:d().optional()}),i({id:t(),kind:n("send"),to:t(),body:t(),from_name:t(),from_agent:t(),wake:d(),reply_to:t().max(100).optional(),notify:d().optional()})]),P=i({job:D.nullable(),retry_after_seconds:o().optional()}),H=i({address:t(),person:t(),machine:t(),agent:t(),repo:t().nullable(),branch:t().nullable(),status:t(),since:o().nullable(),doing:t().nullable(),worker:d(),tier:t().max(10).optional()}),B=i({person:t(),machine:t(),online:d()}),F=i({team:t().nullable(),sessions:u(H).max(2000),machines:u(B).max(500),all:d().optional()}),J=i({address:t().max(300),state:t().max(40),note:t().max(500)}),Ie=W([i({who:F}),i({sent:i({ids:u(t().max(100)).max(500),recipients:u(t().max(300)).max(500),from:t().max(300),deliveries:u(J).max(500).optional()})}),i({error:t().min(1).max(2000)})]),G=i({id:t().max(100),from:t().max(300),from_agent:t().max(100).nullable(),to:t().max(300),reply_to:t().max(100).nullable(),body:t().max(64000),sent_at:o()}),Ce=i({messages:u(G).max(100),team:t().min(1).max(200).optional(),team_id:t().min(1).max(200).optional(),workspace:d().optional()});var x=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var Be=x.filter((e)=>e!=="network:read"&&e!=="network:write");class R extends Error{oauthCode;constructor(e,r=null){super(e);this.oauthCode=r;this.name="LoginError"}}function Q(e,r){let a=typeof e.error==="string"?e.error:null,l=typeof e.error_description==="string"?e.error_description:a?a:r;return new R(l,a)}async function K(e,r,a,l){let c=await a(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:r,signal:l}),m=await c.json().catch(()=>({}));if(!c.ok)throw Q(m,`OAuth token request failed (${c.status})`);return m}var V=1e4;async function Y(e,r={}){let a=r.fetchImpl??fetch,l=await K(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),a,AbortSignal.timeout(V)).catch((m)=>{if(m instanceof Error&&m.name==="TimeoutError")throw new R("Reason did not answer the login refresh in time. Check the network and retry.");throw m});if(typeof l.access_token!=="string"||typeof l.refresh_token!=="string"||typeof l.expires_in!=="number")throw new R("Reason returned an incomplete refreshed login.");let c={...e,accessToken:l.access_token,refreshToken:l.refresh_token,expiresAt:new Date(Date.now()+l.expires_in*1000).toISOString(),scopes:typeof l.scope==="string"?l.scope.split(/\s+/).filter(Boolean):e.scopes};return an(c,r.path??Fe()),c}var b=new Map,X=2000,Z=100;function C(e,r){if(!r)return e;if(r.aborted)return Promise.reject(r.reason);return new Promise((a,l)=>{let c=()=>l(r.reason);r.addEventListener("abort",c,{once:!0}),e.then(a,l).finally(()=>r.removeEventListener("abort",c))})}async function Pt(e={}){let r=e.path??Fe(),a=Tt(r);if(!a)return null;let l=e.apiOrigin??T(process.env,"REASON_API_URL")?.trim();if(l&&!Do(a.apiOrigin,new URL(l).origin))return null;if(!(Date.parse(a.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&a.accessToken!==e.refused))return a;let m=[r,a.apiOrigin,a.clientId,a.refreshToken].join("\x00"),p=b.get(m);if(p)return C(p,e.signal);let f;return f=Y(a,{fetchImpl:e.fetchImpl,path:r}).catch(async(y)=>{if(!(y instanceof R)||y.oauthCode!=="invalid_grant"&&y.oauthCode!=="invalid_client")throw y;let S=(_)=>_!==null&&(y.oauthCode==="invalid_client"?_.clientId!==a.clientId:_.refreshToken!==a.refreshToken),z=Date.now()+X;while(!S(Tt(r))&&Date.now()<z)await new Promise((_)=>setTimeout(_,Z));if(S(Tt(r)))return Pt({fetchImpl:e.fetchImpl,path:r});return cn(r),null}).finally(()=>{if(b.get(m)===f)b.delete(m)}),b.set(m,f),C(f,e.signal)}var ee=i({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:d().nullable()}),ne=i({groups:u(i({selectable:d().optional(),accounts:u(i({source_id:t().min(1),model_ids:u(t().min(1)).optional()}))}))});function te(e){let r=ne.safeParse(e);if(!r.success)return;return r.data.groups.some((a)=>a.selectable!==!1&&a.accounts.some((l)=>l.model_ids===void 0||l.model_ids.length>0))}class I extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor(e,r,a,l,c,m){super(a);this.status=e;this.code=r;this.suggestedModel=l;this.retryAfterMs=c;this.resolutionReason=m;this.name="ApiError"}static rateLimitDelayMs(e,r){if(!(e instanceof I)||e.status!==429)return null;return Math.min(60000,Math.max(r,e.retryAfterMs??0))}}var se=["minimal","low","medium","high","xhigh","max"],oe=i({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:d(),compatible:d().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:u(i({id:t().min(1),label:t()}))}),re=i({devices:u(oe),end_cursor:t().nullish(),has_next_page:d().optional()}),ie=i({id:t().min(1),name:t()}),ae=i({items:u(ie)}),le=i({id:t().min(1),name:t(),main:d(),mine:d(),session_id:t().nullish(),appearance:i({color:t().nullish()}).nullish().catch(null)}),ce=i({items:u(le)}),de=i({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:u(t()).default([]),is_enabled:d().default(!0)}),me=i({items:u(de).default([])}),ue=i({id:t().min(1),kind:t(),enabled:d(),schedule:i({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:i({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),U=i({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:d(),triggers:u(ue).default([])}),ge=i({items:u(U).default([]),end_cursor:t().nullish(),has_next_page:d().optional()}),he=i({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:d()}),pe=i({items:u(he).default([])}),fe=i({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),A=i({tags:u(t()).default([])}),ye=s(["linux","macos"]),q=i({id:t().min(1),name:t().min(1),platform:ye.nullable(),workers:i({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:i({queued:o().int(),running:o().int()})}),_e=i({machines:u(q)}),Re=i({machine:q}),be=i({deleted:n(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),we=i({token:i({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),O=us({machine_id:t().min(1),machine_name:t().min(1)}),Se=O.extend({organization_id:t().min(1)}),Ye=i({id:t().min(1),name:t().min(1),state:s(["waiting","placed"]),queue_position:o().int().nullable()});var Xe=W([i({kind:n("cloud")}),i({kind:s(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function h(e,r,a){let l=e.safeParse(r);if(!l.success)throw new I(502,a,"Reason returned an unexpected response.");return l.data}var ke=i({error:i({type:t(),message:t()})});function w(e,r,a){let l=ke.safeParse(r),c=typeof r.error==="string"?r.error:l.success?l.data.error.type:`http_${e}`,m=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:l.success?l.data.error.message:`Reason request failed (${e}${typeof r.error==="string"?` ${r.error}`:""})`,p=c==="github_connection_required"&&typeof r.connect_url==="string"&&/^https?:\/\//.test(r.connect_url)?` Connect it at ${r.connect_url}`:"",f=a===null||a.trim()===""?NaN:Number(a);return new I(e,c,`${m}${p}`,typeof r.suggested_model==="string"?r.suggested_model:void 0,Number.isFinite(f)&&f>=0?f*1000:void 0,typeof r.resolution_reason==="string"?r.resolution_reason:void 0)}async function Ss(e){let r=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),a=await r.json().catch(()=>({}));if(!r.ok)throw w(r.status,a,r.headers.get("retry-after"));return h(Se,a,"invalid_machine_ticket")}class Zo{options;credentials;constructor(e,r={}){this.options=r;this.credentials=e}trackEvent(e,r={}){}async request(e,r={}){let{status:a,headers:l,json:c}=await this.exchange(e,r);if(a<200||a>299)throw w(a,c,l.get("retry-after"));return c}async exchange(e,r={},a=!1){let l=this.options.fetchImpl??fetch,c=await l(`${this.credentials.apiOrigin}/v3${e}`,{method:r.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Qn,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...r.raw?{"content-type":r.raw.contentType}:r.body===void 0?{}:{"content-type":"application/json"},...r.headers,...r.ifNoneMatch?{"if-none-match":r.ifNoneMatch}:{}},body:r.raw?r.raw.bytes:r.body===void 0?void 0:JSON.stringify(r.body),signal:r.signal,redirect:r.ifNoneMatch?"manual":"error"}),m=await c.json().catch(()=>({}));if(c.status===401&&!a&&r.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let p=await Pt({fetchImpl:l,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:r.signal});if(p)return this.credentials=p,this.exchange(e,r,!0)}return{status:c.status,headers:c.headers,json:m}}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(r){if(r instanceof I&&(r.status===404||r.status===405||r.status===403&&r.code==="endpoint_not_available"))return null;throw r}}addDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(r)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,r=""){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?a:`${a}/${encodeURIComponent(e)}${r}`}async listMachines(){return h(_e,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let r=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return h(Re,r,"invalid_machine").machine}async deleteMachine(e){let r=await this.request(this.machinePath(e),{method:"DELETE"});return h(be,r,"invalid_machine_deletion")}async createMachineToken(e){let r=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return h(we,r,"invalid_machine_token")}async createMachineEnrollmentTicket(e,r){let a=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:r,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return h(O,a,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:r});return h(P,a,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((r)=>typeof r.email==="string"?[{email:r.email,role:typeof r.role==="string"?r.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,r,a={}){let l=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:a.retryUnauthorized,signal:a.signal,body:{...l,...r?{account_key:r}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((r)=>{let a=typeof r.full_name==="string"?r.full_name:typeof r.repo_full_name==="string"?r.repo_full_name:null;if(!a)return[];return[{repo_id:typeof r.repo_id==="string"?r.repo_id:void 0,full_name:a,provider:r.provider==="gitlab"?"gitlab":"github",default_branch:typeof r.default_branch==="string"?r.default_branch:null,private:typeof r.private==="boolean"?r.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),r=ae.safeParse(e);if(!r.success)throw new I(502,"invalid_project_list","Reason returned an unexpected project list.");return r.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return h(ce,e,"invalid_reason_list").items}async openReasonConversation(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return h(i({session_id:t().min(1)}),r,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return h(me,e,"invalid_skill_list").items}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${r?`?after=${encodeURIComponent(r)}`:""}`),c=re.safeParse(l);if(!c.success)throw new I(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...c.data.devices),r=c.data.has_next_page?c.data.end_cursor??null:null,!r)break}return e}async listModels(){try{let r=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((c)=>c.hidden!==!0),a=r.filter((c)=>c.available!==!1).map(({reasoning_efforts:c,hidden:m,available:p,...f})=>({...f,...Array.isArray(c)?{reasoning_efforts:se.filter((y)=>c.includes(y))}:{}})),l=new Set(a.map((c)=>c.detail));return{models:a.length>1&&l.size===1?a.map(({detail:c,...m})=>m):a,runnable:a.length>0||r.length===0}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let r=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return k(r.reason_version)?r.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=ee.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let r;try{r=te(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:r}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let r=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)r.set("origin",e.origin);r.set("fields",e.fields.join(","));let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${r.toString()}`,{status:l,headers:c,json:m}=await this.exchange(a,e.etag?{ifNoneMatch:e.etag}:{});if(l===304)return null;if(l<200||l>299)throw w(l,m,c.get("retry-after"));return{items:Array.isArray(m.items)?m.items:[],etag:c.get("etag")}}async listSessions(e=50,r,a={}){let l=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:a.status??"active"});if(r)l.set("project_id",r);if(a.origin)l.set("origin",a.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${l.toString()}`)).items??[]}getSession(e,r){let a=r?.fields.length?`?fields=${encodeURIComponent(r.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${a}`)}async prestartSession(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return r?.status==="starting"||r?.status==="ready"}async createSession(e){let r=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(r||e.runtimeProfile){let c=await this.request("/deployment");if(r&&(!Array.isArray(c.session_modes)||!c.session_modes.includes(e.mode??"standard")||!Array.isArray(c.workspace_ownerships)||!c.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(c.experimental_runtime_profiles)||!c.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),l=await this.getSession(a.session_id);if(r){let c=l.session_policy,m=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!c||c.version!==1||c.mode!==(e.mode??"standard")||c.workspaceOwnership!==(e.workspaceOwnership??"managed")||!c.components||m.some((p)=>c.components[p]!==!0))throw await this.cancelSession(a.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&l.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(a.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return l}async getEvents(e,r=-1,a={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${r}&limit=500${a.waitMs?`&wait_ms=${a.waitMs}`:""}`,a.signal?{signal:a.signal}:{})}catch(l){if(!(l instanceof I)||l.status!==403&&l.status!==404)throw l;return{session:await this.getSession(e),items:[],next_seq:r}}}async getMessages(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${r===void 0?"":`&after_seq=${r}`}`)}async getAttachments(e,r){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${r?`?view=${r}`:""}`)).items??[]}catch(a){if(a instanceof I&&(a.status===403||a.status===404))return[];throw a}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let r=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,a=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,l=[r,a].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${l?` (${l})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,r,a={}){if(a.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:r,...a.attachments?.length?{attachments:a.attachments}:{},...a.model?{model:a.model}:{},...a.reasoningEffort?{reasoning_effort:a.reasoningEffort}:{},...a.target?{target:a.target}:{},...a.delivery?{delivery:a.delivery}:{}}})}async steerQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/queued`,{method:"DELETE"})}async getConversation(e){let r=[],a=null;for(let l=0;l<50;l+=1){let c=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${a?`?after=${encodeURIComponent(a)}`:""}`);if(r.push(...c.items??[]),!c.has_next_page||!c.end_cursor)break;a=c.end_cursor}return r}createSharedLink(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:r.url,...r.label?{label:r.label}:{},...r.expiresInSeconds!==void 0?{expires_in_seconds:r.expiresInSeconds}:{}}})}sessionAction(e,r,a={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${r}`,{method:"POST",body:a})}renameSession(e,r){return this.sessionAction(e,"rename",{title:r||null})}moveSessionToProject(e,r){return this.sessionAction(e,"project",{project_id:r})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,r){return this.sessionAction(e,"rewind",{message_id:r.messageId,content:r.content,request_id:r.requestId})}forkSession(e,r){return this.sessionAction(e,"fork",{...r.message?{message:r.message}:{},client_session_id:r.clientSessionId})}cancelSession(e,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:r.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,r=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return h(A,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,r){let a=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:r}});return h(A,a,"invalid_session_tags").tags}async sessionInsight(e,r=!1){let a=await this.request(this.sessionPath(e,r?"/insights/generate":"/insights"),r?{method:"POST",body:{}}:{});return h(fe,a,"invalid_session_insight")}async listAutomations(){let e=[],r=null;for(let a=0;a<20;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${r?`&after=${encodeURIComponent(r)}`:""}`),c=h(ge,l,"invalid_automation_list");if(e.push(...c.items),r=c.has_next_page?c.end_cursor??null:null,!r)break}return e}async createScheduledAutomation(e,r){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,l=h(U,await this.request(a,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${a}/${encodeURIComponent(l.id)}/triggers`,{method:"POST",body:r})}catch(c){throw await this.deleteAutomation(l.id).catch(()=>{return}),c}return l}async setAutomationEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:r}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:r}});return h(i({transcript:t()}),a,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return h(pe,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:r}})}}
|
|
3
|
+
export{Pt,I,Ss,Zo};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{S,zt,Bn,Ge,Fn,jn}from"./vm-hands-entry-lite-eabever7.js";import{Yn}from"./vm-hands-entry-lite-
|
|
2
|
+
import{S,zt,Bn,Ge,Fn,jn}from"./vm-hands-entry-lite-eabever7.js";import{Yn}from"./vm-hands-entry-lite-yg9zb1nr.js";import{Mn}from"./vm-hands-entry-lite-tvgb94jk.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as ys,spawn as qe}from"child_process";import{existsSync as ws}from"fs";import{connect as xs}from"net";function pn(){let e=new Set,t=null,n=(s)=>({holder:t?.viewer??null,you:t===s,same_user:Boolean(t?.viewer&&s.viewer&&t.viewer.user_id===s.viewer.user_id)}),o=()=>{for(let s of e)s.notify(n(s))};return{join(s){return e.add(s),s.notify(n(s)),()=>{if(!e.delete(s))return;if(t!==s)return;t=null,o()}},claim(s){if(t===s||!e.has(s))return;t=s,o()}}}var ut=pn();import{createHash as St}from"crypto";import{once as Sn}from"events";import{createWriteStream as vn,existsSync as mr,mkdirSync as gr,mkdtempSync as hr,readFileSync as le,readdirSync as br,renameSync as yr,realpathSync as En,rmSync as Pn,statSync as Ne,writeFileSync as wr}from"fs";import{delimiter as _r,dirname as vt,join as b}from"path";import{finished as Cn}from"stream/promises";var We="omljlfpmafedpplnpkkahegadhkimdje",uo="https://chromewebstore.google.com/detail/reason/omljlfpmafedpplnpkkahegadhkimdje";var O={ocu:{repository:"https://github.com/iFurySt/open-codex-computer-use.git",revision:"386a260d1ab8b690adbbb27f7471595cf0c2b752",version:"0.3.5"},obu:{repository:"https://github.com/iFurySt/open-browser-use.git",revision:"ac015846df75928fbcf0f3a0f3ba3a210ce1a507",version:"0.1.42"}},H={version:"155.0.8059.84",macArm64Sha256:"13b9e98ce56f5ce18e100a009f455c9285f399e7c9dc8a76fdf2f3a9755bb5f2",linux64Sha256:"cf0f049892dea22e6a6db26d47ed0d7776b7158edcbec4634086633df8bafcbc",win64Sha256:"507f2a031441d10c62b5e3d4e863f09ac1198a571c1419976cbd8387f639afde"};var J={ocu:{url:`https://registry.npmjs.org/open-computer-use/-/open-computer-use-${O.ocu.version}.tgz`,sha256:"7c16a87c8cd357787b02c0ebd040dd5f93880c1fb51c1901caa2e0c05d063130",size_bytes:5844280},obu:{url:`https://registry.npmjs.org/open-browser-use/-/open-browser-use-${O.obu.version}.tgz`,sha256:"9386d8ce0a147b3f55e1807b68edf736836378807541c457c9b5f6ca2cabaa4e",size_bytes:21372018},extension:{url:`https://github.com/iFurySt/open-browser-use/releases/download/v${O.obu.version}/open-browser-use-chrome-extension-${O.obu.version}.zip`,sha256:"c9c07bec1175e12ea6985b0e7784a5ef01fd03f014b958224a1e17dcd838a241",size_bytes:31070}},F="pnbmoicbkopffjjgfgfglopechaiemkp";import{spawn as Me}from"child_process";import{createRequire as fn}from"module";import{join as mn}from"path";var gn=30000,hn=1048576;function Te(){return process.env.SystemRoot??"C:\\Windows"}function bn(){return mn(Te(),"System32","WindowsPowerShell","v1.0","powershell.exe")}var yn=String.raw`
|
|
3
3
|
$ErrorActionPreference = "Stop"
|
|
4
4
|
Add-Type -TypeDefinition @"
|
|
5
5
|
using System;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var Qt={name:"github-native-engineer-device-worker-production",version:"0.2.
|
|
2
|
+
var Qt={name:"github-native-engineer-device-worker-production",version:"0.2.509",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@agentclientprotocol/sdk":"1.9.0","@anthropic-ai/sandbox-runtime":"^0.0.80","@earendil-works/pi-tui":"1.0.0","@reason/runtime-distribution":"workspace:*",diff:"8.0.4","open-browser-use-sdk":"0.1.42","playwright-core":"1.60.0",toml:"4.2.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.1",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^4.2.0",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
|
|
3
3
|
export{Qt};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{a}from"./vm-hands-entry-lite-
|
|
3
|
-
`)){let e=s.split(":");if(e.length<7||Number(e[2])!==t||!/^\d+$/.test(e[2])||!/^\d+$/.test(e[3]))continue;let n=e[5];if(!/^[a-z_][a-z0-9_-]*$/i.test(e[0])||!l(n)||i(n)!==n||n==="/")return null;return{username:e[0],uid:t,gid:Number(e[3]),home:n}}return null}function
|
|
4
|
-
export{
|
|
2
|
+
import{a}from"./vm-hands-entry-lite-y2khvb5c.js";import{readFileSync as c}from"fs";import{isAbsolute as l,normalize as i}from"path";var m="REASON_WORKER_DESKTOP_USER",u=null;function p(t,o){for(let s of o.split(`
|
|
3
|
+
`)){let e=s.split(":");if(e.length<7||Number(e[2])!==t||!/^\d+$/.test(e[2])||!/^\d+$/.test(e[3]))continue;let n=e[5];if(!/^[a-z_][a-z0-9_-]*$/i.test(e[0])||!l(n)||i(n)!==n||n==="/")return null;return{username:e[0],uid:t,gid:Number(e[3]),home:n}}return null}function Us(t={}){let o="value"in t?t.value:process.env[m];if(u=null,o===void 0||o==="")return null;let s=t.platform??process.platform,e="euid"in t?t.euid:process.geteuid?.(),n=/^[1-9]\d{0,9}$/.test(o)?Number(o):NaN,r=s==="linux"&&e===0&&Number.isSafeInteger(n)?p(n,(t.passwd??(()=>c("/etc/passwd","utf8")))()):null;if(!r||r.gid===0)throw Error("worker_desktop_user_invalid");return u=r,r}function K(){return u}function Mn(){return u?.home??a()}
|
|
4
|
+
export{Us,K,Mn};
|