@reason-machines/cli-linux-arm64-musl 0.2.320 → 0.2.322
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/ara +1 -1
- package/bin/vm-hands/{connect-cli-xnzjcb3e.js → connect-cli-cyt0kpyr.js} +1 -1
- package/bin/vm-hands/{local-automation-6bxsfea4.js → local-automation-5wj4326w.js} +1 -1
- package/bin/vm-hands/{local-capabilities-cen359s5.js → local-capabilities-aya670gj.js} +1 -1
- package/bin/vm-hands/{local-display-session-vhe31z68.js → local-display-session-2y9fgh2a.js} +1 -1
- package/bin/vm-hands/{permissions-5hh1663f.js → permissions-dfbchv02.js} +1 -1
- package/bin/vm-hands/{status-aej4363b.js → status-ghjnryz1.js} +2 -2
- package/bin/vm-hands/{version-yds2dewc.js → version-rkf1f8kn.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-dajv3b6q.js → vm-hands-entry-lite-1gbvtqgy.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-617f66dj.js → vm-hands-entry-lite-88x8hevx.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-wmbe27q2.js → vm-hands-entry-lite-b92849ds.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-2ym8pc3f.js → vm-hands-entry-lite-et7c3583.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-qg2q7w4z.js → vm-hands-entry-lite-gycydjw0.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-6fvcdr2b.js → vm-hands-entry-lite-m1c4h4me.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-ex8ayqyn.js → vm-hands-entry-lite-n2k92e7f.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-njavcwrp.js → vm-hands-entry-lite-wh9g92n9.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-c3yx2kcy.js → vm-hands-executor-bjswhqrs.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-4j1e9snb.js → vm-hands-op-runner-766rq98c.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-6q8y3a57.js → vm-hands-runtime-xa917sav.js} +2 -2
- package/package.json +1 -1
package/bin/ara
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{g as a,h as b,i as c,j as d,k as e,l as f,m as g,n as h,o as i,p as j,q as k,r as l,s as m}from"./vm-hands-entry-lite-
|
|
2
|
+
import{g as a,h as b,i as c,j as d,k as e,l as f,m as g,n as h,o as i,p as j,q as k,r as l,s as m}from"./vm-hands-entry-lite-1gbvtqgy.js";import"./vm-hands-entry-lite-xf6schkk.js";import"./vm-hands-entry-lite-88x8hevx.js";import"./vm-hands-entry-lite-gycydjw0.js";import"./vm-hands-entry-lite-q8b738zj.js";import"./vm-hands-entry-lite-93ejmwqn.js";import"./vm-hands-entry-lite-qvrnx0vk.js";import"./vm-hands-entry-lite-n07kxrd1.js";import"./vm-hands-entry-lite-b2wdaq7x.js";import"./vm-hands-entry-lite-b92849ds.js";import"./vm-hands-entry-lite-t497ewn2.js";import"./vm-hands-entry-lite-psybjyay.js";import"./vm-hands-entry-lite-m1c4h4me.js";import"./vm-hands-entry-lite-wh0qp1gf.js";import"./vm-hands-entry-lite-yhz6sv35.js";import"./vm-hands-entry-lite-wh9g92n9.js";import"./vm-hands-entry-lite-22jgncrd.js";import"./vm-hands-entry-lite-mzxhng4z.js";import"./vm-hands-entry-lite-cp1wqjs5.js";import"./vm-hands-entry-lite-ne8kkvk4.js";import"./vm-hands-entry-lite-n2k92e7f.js";import"./vm-hands-entry-lite-et7c3583.js";import"./vm-hands-entry-lite-14t846kp.js";import"./vm-hands-entry-lite-v6tkjqb1.js";import"./vm-hands-entry-lite-cxs89wzv.js";export{g as runDisconnectCli,f as runConnectCli,m as restartConnectionWhenIdle,l as restartConnection,h as logoutConnection,k as connectionUsesUserChrome,i as connectionReport,j as connectionForBrowserExtension,c as connectionDirectory,d as computerDisconnected,e as addConnectionFolder,b as DISCONNECT_HELP,a as CONNECT_HELP};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Gc as a,Hc as b,Ic as c,Jc as d,Kc as e,Lc as f,Mc as g,Nc as h,Oc as i,Pc as j,Qc as k,Rc as l}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Gc as a,Hc as b,Ic as c,Jc as d,Kc as e,Lc as f,Mc as g,Nc as h,Oc as i,Pc as j,Qc as k,Rc as l}from"./vm-hands-entry-lite-b92849ds.js";import"./vm-hands-entry-lite-t497ewn2.js";import"./vm-hands-entry-lite-psybjyay.js";import"./vm-hands-entry-lite-m1c4h4me.js";import"./vm-hands-entry-lite-wh0qp1gf.js";import"./vm-hands-entry-lite-yhz6sv35.js";import"./vm-hands-entry-lite-wh9g92n9.js";import"./vm-hands-entry-lite-22jgncrd.js";import"./vm-hands-entry-lite-mzxhng4z.js";import"./vm-hands-entry-lite-cp1wqjs5.js";import"./vm-hands-entry-lite-ne8kkvk4.js";import"./vm-hands-entry-lite-n2k92e7f.js";import"./vm-hands-entry-lite-et7c3583.js";import"./vm-hands-entry-lite-14t846kp.js";import"./vm-hands-entry-lite-v6tkjqb1.js";import"./vm-hands-entry-lite-cxs89wzv.js";export{d as runRelayed,e as runMacComputerUse,l as runLocalAutomation,k as runAutomationCallLocally,b as parseAutomationPayload,g as localUserChromeProfiles,h as localUserChromeInstance,f as localUserChromeHost,j as localBrowserProfile,c as localAutomationAvailable,i as ensureLocalBrowser,a as AUTOMATION_CHUNK_BYTES};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$ as o,P as c,Q as d,R as e,S as f,T as g,U as h,V as i,W as j,X as k,Y as l,Z as m,_ as n,aa as p,ba as q,ca as r,da as s,ea as t,fa as u}from"./vm-hands-entry-lite-
|
|
2
|
+
import{$ as o,P as c,Q as d,R as e,S as f,T as g,U as h,V as i,W as j,X as k,Y as l,Z as m,_ as n,aa as p,ba as q,ca as r,da as s,ea as t,fa as u}from"./vm-hands-entry-lite-88x8hevx.js";import"./vm-hands-entry-lite-gycydjw0.js";import"./vm-hands-entry-lite-q8b738zj.js";import"./vm-hands-entry-lite-93ejmwqn.js";import"./vm-hands-entry-lite-qvrnx0vk.js";import{Zb as b}from"./vm-hands-entry-lite-n07kxrd1.js";import"./vm-hands-entry-lite-b2wdaq7x.js";import"./vm-hands-entry-lite-b92849ds.js";import"./vm-hands-entry-lite-t497ewn2.js";import"./vm-hands-entry-lite-psybjyay.js";import"./vm-hands-entry-lite-m1c4h4me.js";import"./vm-hands-entry-lite-wh0qp1gf.js";import"./vm-hands-entry-lite-yhz6sv35.js";import"./vm-hands-entry-lite-wh9g92n9.js";import"./vm-hands-entry-lite-22jgncrd.js";import"./vm-hands-entry-lite-mzxhng4z.js";import"./vm-hands-entry-lite-cp1wqjs5.js";import"./vm-hands-entry-lite-ne8kkvk4.js";import"./vm-hands-entry-lite-n2k92e7f.js";import"./vm-hands-entry-lite-et7c3583.js";import"./vm-hands-entry-lite-14t846kp.js";import{Oh as a}from"./vm-hands-entry-lite-v6tkjqb1.js";import"./vm-hands-entry-lite-cxs89wzv.js";export{g as spawnCaptured,f as sandboxProfile,e as safeEnvironment,k as runTransferCapability,i as runFileCapability,t as rebindLocalHandsControl,j as localGithubPreviewServerLaunch,b as isProtectedLocalPath,u as executeLocalOperation,m as enrolledWorkspaceRootFingerprint,q as enrolledRootPaths,p as enrolledHomeContainedRootFingerprints,n as enrolledAccountRootPath,o as enrolledAccountRootFingerprint,s as deliverLocalHandsEnvironment,h as defaultLocalCommandRunner,d as confinedExecutionShell,r as capabilityInventoryForRoots,c as SHORT_REQUEST_CAPABILITIES,a as LocalCapabilityError,l as LOCAL_CAPABILITY_REGISTRY};
|
package/bin/vm-hands/{local-display-session-vhe31z68.js → local-display-session-2y9fgh2a.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ae as d,Be as e,Ce as f,De as g,Ee as h,xe as a,ye as b,ze as c}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ae as d,Be as e,Ce as f,De as g,Ee as h,xe as a,ye as b,ze as c}from"./vm-hands-entry-lite-m1c4h4me.js";import"./vm-hands-entry-lite-wh0qp1gf.js";import"./vm-hands-entry-lite-yhz6sv35.js";import"./vm-hands-entry-lite-wh9g92n9.js";import"./vm-hands-entry-lite-22jgncrd.js";import"./vm-hands-entry-lite-mzxhng4z.js";import"./vm-hands-entry-lite-cp1wqjs5.js";import"./vm-hands-entry-lite-ne8kkvk4.js";import"./vm-hands-entry-lite-n2k92e7f.js";import"./vm-hands-entry-lite-et7c3583.js";import"./vm-hands-entry-lite-14t846kp.js";import"./vm-hands-entry-lite-v6tkjqb1.js";import"./vm-hands-entry-lite-cxs89wzv.js";export{h as runLocalDisplayStream,f as privateDirectory,c as parseDisplayStreamPayload,e as localDisplayReady,d as localDisplayAvailable,g as ensureLinuxDesktop,a as LOCAL_DISPLAY_MAX_SESSION_MS,b as LINUX_WORKER_DISPLAY};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ag as f,Bg as g,Cg as h,Dg as i,Eg as j,vg as a,wg as b,xg as c,yg as d,zg as e}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ag as f,Bg as g,Cg as h,Dg as i,Eg as j,vg as a,wg as b,xg as c,yg as d,zg as e}from"./vm-hands-entry-lite-wh9g92n9.js";import"./vm-hands-entry-lite-22jgncrd.js";import"./vm-hands-entry-lite-cp1wqjs5.js";import"./vm-hands-entry-lite-ne8kkvk4.js";import"./vm-hands-entry-lite-n2k92e7f.js";import"./vm-hands-entry-lite-et7c3583.js";import"./vm-hands-entry-lite-v6tkjqb1.js";import"./vm-hands-entry-lite-cxs89wzv.js";export{j as runPermissionsCli,d as reasonIdentity,e as readMacPermissions,f as permissionsSummary,i as parsePermissionsArgs,c as fullDiskAccessTarget,g as formatMacPermissions,h as allowMacPermissions,a as PERMISSIONS_HELP,b as MAC_PERMISSION_IDS};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{a as Wq,b as Bq,c as bq,d as Fq,e as Dq,f as kq,i as Kq,j as Vq,o as Hq}from"./vm-hands-entry-lite-
|
|
2
|
+
import{a as Wq,b as Bq,c as bq,d as Fq,e as Dq,f as kq,i as Kq,j as Vq,o as Hq}from"./vm-hands-entry-lite-1gbvtqgy.js";import"./vm-hands-entry-lite-xf6schkk.js";import"./vm-hands-entry-lite-88x8hevx.js";import"./vm-hands-entry-lite-gycydjw0.js";import"./vm-hands-entry-lite-q8b738zj.js";import"./vm-hands-entry-lite-93ejmwqn.js";import"./vm-hands-entry-lite-qvrnx0vk.js";import"./vm-hands-entry-lite-n07kxrd1.js";import"./vm-hands-entry-lite-b2wdaq7x.js";import{pc as jq}from"./vm-hands-entry-lite-b92849ds.js";import"./vm-hands-entry-lite-t497ewn2.js";import{ee as G}from"./vm-hands-entry-lite-psybjyay.js";import"./vm-hands-entry-lite-m1c4h4me.js";import{Ie as H,Je as u,Ke as s,ff as Qq}from"./vm-hands-entry-lite-wh0qp1gf.js";import"./vm-hands-entry-lite-yhz6sv35.js";import"./vm-hands-entry-lite-wh9g92n9.js";import"./vm-hands-entry-lite-22jgncrd.js";import"./vm-hands-entry-lite-mzxhng4z.js";import{ch as l}from"./vm-hands-entry-lite-cp1wqjs5.js";import"./vm-hands-entry-lite-ne8kkvk4.js";import{Ch as R}from"./vm-hands-entry-lite-n2k92e7f.js";import"./vm-hands-entry-lite-et7c3583.js";import"./vm-hands-entry-lite-14t846kp.js";import"./vm-hands-entry-lite-v6tkjqb1.js";import{Uh as $q}from"./vm-hands-entry-lite-cxs89wzv.js";import{createHash as tq,randomBytes as sq}from"crypto";import{readFileSync as eq,realpathSync as zq,renameSync as nq,unlinkSync as aq,writeFileSync as q3}from"fs";import{dirname as x3,join as Aq}from"path";import{spawnSync as Mq}from"child_process";import{accessSync as _q,constants as wq,existsSync as L,mkdirSync as Lq,readFileSync as fq,renameSync as Sq,writeFileSync as hq}from"fs";import{homedir as Cq}from"os";import{delimiter as gq,dirname as mq,join as T}from"path";import{existsSync as Tq,readFileSync as Uq}from"fs";import{join as vq}from"path";var Eq=`---
|
|
3
3
|
name: reason
|
|
4
4
|
description: Integrate software with Reason's public REST API using a scoped API key. Use for API clients, CI, service integrations, or cloud coding-session automation.
|
|
5
5
|
---
|
|
@@ -79,7 +79,7 @@ This computer
|
|
|
79
79
|
`),b.version)x.stdout.write(`Version: ${b.version}${b.version===R?"":` (${R} is installed; \`reason connect\` restarts it on that)`}
|
|
80
80
|
`);if(x.stdout.write(`Folder: ${b.folder}
|
|
81
81
|
`),x.stdout.write(`Sessions: ${b.sessions_running===null?"":`${b.sessions_running} running, `}${b.sessions_max===1?"one at a time":`up to ${b.sessions_max} at once`}
|
|
82
|
-
`),z){let Z=z,V=await(J.readPermissionsSummary??(async()=>{let{permissionsSummary:Rq,readMacPermissions:Nq,reasonIdentity:Iq}=await import("./permissions-
|
|
82
|
+
`),z){let Z=z,V=await(J.readPermissionsSummary??(async()=>{let{permissionsSummary:Rq,readMacPermissions:Nq,reasonIdentity:Iq}=await import("./permissions-dfbchv02.js"),{macScreenStatus:Oq}=await import("./local-display-mac-9qqvjs82.js");return Rq(await Nq({identity:()=>Iq(),grants:Oq,worker:async()=>Z}))}))().catch(()=>null);if(V)x.stdout.write(`${V}
|
|
83
83
|
`);x.stdout.write(`Keep awake: ${z.keep_awake.enabled?"on":"off"}${z.keep_awake.holding?" (holding)":""}
|
|
84
84
|
`)}if(b.service)x.stdout.write(`Logs: ${b.service.logs}
|
|
85
85
|
`);for(let Z of b.workspaces??[]){let V=Z.state==="removed"?"removed from that workspace":Z.blocked?"offline (this computer is outside that workspace's allowed networks)":Z.device_id?Gq[Z.state]:"connecting";x.stdout.write(`Also in workspace ${Z.name??Z.organization_id}${Z.account?" (another Reason account's)":""}: ${V}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ch as a,Dh as b,Eh as c,Fh as d}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ch as a,Dh as b,Eh as c,Fh as d}from"./vm-hands-entry-lite-n2k92e7f.js";import"./vm-hands-entry-lite-et7c3583.js";import"./vm-hands-entry-lite-cxs89wzv.js";export{c as compareCliVersions,d as cliAndAgentVersion,b as CLI_VERSION_PATTERN,a as CLI_VERSION};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{t as d0}from"./vm-hands-entry-lite-xf6schkk.js";import{A as G5,B as B5,C as R7,D as C7,E as v3,F as i5,G as H5,H as _0,I as l$,J as p$,K as S0,L as J2,M as n5,N as n0,O as M6,P as Z3,Q as Z6,U as Q6,ba as x7,ca as E7,da as S7,ea as w7,fa as u3,y as l6,z as p6}from"./vm-hands-entry-lite-
|
|
2
|
+
import{t as d0}from"./vm-hands-entry-lite-xf6schkk.js";import{A as G5,B as B5,C as R7,D as C7,E as v3,F as i5,G as H5,H as _0,I as l$,J as p$,K as S0,L as J2,M as n5,N as n0,O as M6,P as Z3,Q as Z6,U as Q6,ba as x7,ca as E7,da as S7,ea as w7,fa as u3,y as l6,z as p6}from"./vm-hands-entry-lite-88x8hevx.js";import{Aa as K5,Ba as V5,Ca as L7,Da as D7,Fa as u,Ga as e,Ha as s,Ia as c,Ja as W5,Ka as z7,La as W$,Oa as V4,Pa as H4,Qa as CJ,Ra as PJ,Sa as IJ,Ta as y0,Ua as J0,Va as g,Wa as g3,Xa as E$,Ya as K2,Za as U0,_a as O7,db as U6,fb as h8,ha as r7,ib as u2,ka as z5,kb as a5,la as O5,lb as T3,nb as h5,oa as F5,qa as E5,rb as A7,sb as N3,ta as S5,ya as y5,za as f5}from"./vm-hands-entry-lite-gycydjw0.js";import{Ab as w5,Bb as b5,Ib as k5}from"./vm-hands-entry-lite-q8b738zj.js";import{Nb as N5}from"./vm-hands-entry-lite-93ejmwqn.js";import{Ub as s5}from"./vm-hands-entry-lite-qvrnx0vk.js";import{mc as Y5}from"./vm-hands-entry-lite-b2wdaq7x.js";import{Ac as bJ,Bc as Y4,Cc as F1,Dc as E8,Ec as G4,Ic as t5,Lc as P7,Oc as c6,Pc as s6,qc as i1,rc as G1,sc as I1,tc as L$,uc as HJ,vc as EJ,wc as SJ,xc as D$,yc as wJ,zc as e3}from"./vm-hands-entry-lite-b92849ds.js";import{Fd as X5,Ld as $$,Vd as F2,Zc as b2,bd as F7,cd as W7}from"./vm-hands-entry-lite-t497ewn2.js";import{ee as G}from"./vm-hands-entry-lite-psybjyay.js";import{Be as J6,me as xJ,ne as o2,qe as I7,te as n$,ve as tJ,we as oJ}from"./vm-hands-entry-lite-m1c4h4me.js";import{$e as e1,Fe as k0,Ge as k$,Ie as x0,Je as j4,Le as e0,Me as z0,Ne as y9,Oe as AJ,Pe as RJ,Qe as E2,Re as q2,Se as f3,Te as I8,Ue as x8,Ve as Y$,We as v$,Xe as G0,Ye as T2,Ze as y7,_e as f7,af as R4,cf as Q3,df as h1,ef as v0,ff as y$,gf as X3,jf as m1}from"./vm-hands-entry-lite-wh0qp1gf.js";import{nf as x5}from"./vm-hands-entry-lite-yhz6sv35.js";import{mg as LJ,pg as r5,qg as h3,sg as U5}from"./vm-hands-entry-lite-wh9g92n9.js";import{$g as Z2,ah as c5}from"./vm-hands-entry-lite-mzxhng4z.js";import{ch as V0,eh as V7}from"./vm-hands-entry-lite-cp1wqjs5.js";import{Ch as r}from"./vm-hands-entry-lite-n2k92e7f.js";import{Jh as j7}from"./vm-hands-entry-lite-14t846kp.js";import{Oh as g0}from"./vm-hands-entry-lite-v6tkjqb1.js";import{spawn as kJ,spawnSync as $V}from"child_process";import{closeSync as yJ,mkdirSync as JV,openSync as fJ,readdirSync as ZV,realpathSync as B1,rmSync as z$}from"fs";import{hostname as QV}from"os";import{dirname as $9,join as F0,resolve as XV}from"path";var $Z=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function U9($){let J=typeof $==="string"?$Z.exec($):null;return J?{major:Number(J[1]),minor:Number(J[2])}:null}import{createHash as KZ,randomBytes as z9}from"crypto";import{createInterface as VZ}from"readline";import{randomBytes as JZ}from"crypto";import{chmodSync as M9,existsSync as T9,lstatSync as ZZ,mkdirSync as QZ,readFileSync as _9,renameSync as XZ,unlinkSync as F9,writeFileSync as W9}from"fs";import{homedir as YZ}from"os";import{dirname as GZ,join as q9}from"path";function $1($=process.env,J=YZ()){let Z=$.XDG_CONFIG_HOME?.trim()||q9(J,".config"),X=x0({env:$})==="staging"?["staging"]:[];return q9(q2(Z,...X),"credentials.json")}function L9($,J=$1()){return QZ(GZ(J),{recursive:!0,mode:448}),W9(J,`${JSON.stringify($,null,2)}
|
|
3
3
|
`,{mode:384}),M9(J,384),J}function I$($=$1()){if(!T9($))return null;try{let J=_9($,"utf8"),Z=JSON.parse(J);if(typeof Z.apiOrigin!=="string"||typeof Z.clientId!=="string"||typeof Z.accessToken!=="string"||typeof Z.refreshToken!=="string"||typeof Z.expiresAt!=="string"||typeof Z.orgId!=="string"||!Array.isArray(Z.scopes))return null;let Q=new URL(Z.apiOrigin).origin,X=e0(Q);if(X!==Q)BZ($,J,X);return{apiOrigin:X,clientId:Z.clientId,accessToken:Z.accessToken,refreshToken:Z.refreshToken,expiresAt:Z.expiresAt,scopes:Z.scopes.filter((Y)=>typeof Y==="string"),orgId:Z.orgId}}catch{return null}}function BZ($,J,Z){let Q=`${$}.${process.pid}.${JZ(6).toString("hex")}.tmp`;try{let X=ZZ($);if(!X.isFile()||X.uid!==process.geteuid?.())return;let Y=JSON.parse(J);if(W9(Q,`${JSON.stringify({...Y,apiOrigin:Z},null,2)}
|
|
4
|
-
`,{mode:384,flag:"wx"}),M9(Q,384),_9($,"utf8")!==J)throw Error("credentials_changed");XZ(Q,$)}catch{try{F9(Q)}catch{}}}function D9($=$1()){if(!T9($))return!1;return F9($),!0}var j9=["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 pV=j9.filter(($)=>$!=="network:read"&&$!=="network:write");class x$ extends Error{oauthCode;constructor($,J=null){super($);this.oauthCode=J;this.name="LoginError"}}function A9(){let $=z9(48).toString("base64url"),J=KZ("sha256").update($).digest("base64url");return{verifier:$,challenge:J,state:z9(32).toString("base64url")}}function HZ($,J){let Z=typeof $.error==="string"?$.error:null,Q=typeof $.error_description==="string"?$.error_description:Z?Z:J;return new x$(Q,Z)}async function NZ($,J,Z,Q){let X=await Z(`${$}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:J,signal:Q}),Y=await X.json().catch(()=>({}));if(!X.ok)throw HZ(Y,`OAuth token request failed (${X.status})`);return Y}var UZ=1e4;async function qZ($,J={}){let Z=J.fetchImpl??fetch,Q=await NZ($.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:$.clientId,refresh_token:$.refreshToken}),Z,AbortSignal.timeout(UZ)).catch((Y)=>{if(Y instanceof Error&&Y.name==="TimeoutError")throw new x$("Reason did not answer the login refresh in time. Check the network and retry.");throw Y});if(typeof Q.access_token!=="string"||typeof Q.refresh_token!=="string"||typeof Q.expires_in!=="number")throw new x$("Reason returned an incomplete refreshed login.");let X={...$,accessToken:Q.access_token,refreshToken:Q.refresh_token,expiresAt:new Date(Date.now()+Q.expires_in*1000).toISOString(),scopes:typeof Q.scope==="string"?Q.scope.split(/\s+/).filter(Boolean):$.scopes};return L9(X,J.path??$1()),X}var M2=new Map;function O9($,J){if(!J)return $;if(J.aborted)return Promise.reject(J.reason);return new Promise((Z,Q)=>{let X=()=>Q(J.reason);J.addEventListener("abort",X,{once:!0}),$.then(Z,Q).finally(()=>J.removeEventListener("abort",X))})}async function k1($={}){let J=$.path??$1(),Z=I$(J);if(!Z)return null;let Q=$.apiOrigin??k0(process.env,"REASON_API_URL")?.trim();if(Q&&!z0(Z.apiOrigin,new URL(Q).origin))return null;let X=Date.parse(Z.expiresAt)<=Date.now()+60000;if(!$.forceRefresh&&!X)return Z;let Y=[J,Z.apiOrigin,Z.clientId,Z.refreshToken].join("\x00"),B=M2.get(Y);if(B)return O9(B,$.signal);let V;return V=qZ(Z,{fetchImpl:$.fetchImpl,path:J}).catch(async(K)=>{if(!(K instanceof x$)||K.oauthCode!=="invalid_grant"&&K.oauthCode!=="invalid_client")throw K;let N=I$(J),q=K.oauthCode==="invalid_client"?N?.clientId!==Z.clientId:N?.refreshToken!==Z.refreshToken;if(N&&q)return k1({fetchImpl:$.fetchImpl,path:J});return D9(J),null}).finally(()=>{if(M2.get(Y)===V)M2.delete(Y)}),M2.set(Y,V),O9(V,$.signal)}function R9($,J){return new Promise((Z)=>{let Q=VZ({input:$}),X=!1,Y=(V)=>{if(X)return;X=!0,J.removeEventListener("abort",B),Q.close(),$.pause(),Z(V)},B=()=>Y(null);J.addEventListener("abort",B,{once:!0}),Q.once("line",(V)=>Y(V)),Q.once("close",()=>Y(null))})}var MZ=G.object({label:G.string(),used_percent:G.number().min(0).max(100).nullable(),resets_at:G.string().nullable(),exhausted:G.boolean().nullable()}),TZ=G.object({groups:G.array(G.object({selectable:G.boolean().optional(),accounts:G.array(G.object({source_id:G.string().min(1),model_ids:G.array(G.string().min(1)).optional()}))}))});function _Z($){let J=TZ.safeParse($);if(!J.success)return;return J.data.groups.some((Z)=>Z.selectable!==!1&&Z.accounts.some((Q)=>Q.model_ids===void 0||Q.model_ids.length>0))}class Y0 extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor($,J,Z,Q,X,Y){super(Z);this.status=$;this.code=J;this.suggestedModel=Q;this.retryAfterMs=X;this.resolutionReason=Y;this.name="ApiError"}static rateLimitDelayMs($,J){if(!($ instanceof Y0)||$.status!==429)return null;return Math.min(60000,Math.max(J,$.retryAfterMs??0))}}var FZ=["minimal","low","medium","high","xhigh","max"],WZ=G.object({id:G.string().min(1),kind:G.string(),name:G.string(),custom_name:G.string().nullish(),status:G.string(),online:G.boolean(),compatible:G.boolean().optional(),compatibility_reason:G.string().nullish(),folder_lane_of:G.string().nullish(),roots:G.array(G.object({id:G.string().min(1),label:G.string()}))}),LZ=G.object({devices:G.array(WZ),end_cursor:G.string().nullish(),has_next_page:G.boolean().optional()}),DZ=G.object({id:G.string().min(1),name:G.string()}),jZ=G.object({items:G.array(DZ)}),zZ=G.object({id:G.string().min(1),name:G.string(),main:G.boolean(),mine:G.boolean(),session_id:G.string().nullish(),appearance:G.object({color:G.string().nullish()}).nullish().catch(null)}),OZ=G.object({items:G.array(zZ)}),AZ=G.object({skill_id:G.string().min(1),name:G.string(),description:G.string().nullish(),activation_keywords:G.array(G.string()).default([]),is_enabled:G.boolean().default(!0)}),RZ=G.object({items:G.array(AZ).default([])}),CZ=G.object({id:G.string().min(1),kind:G.string(),enabled:G.boolean(),schedule:G.object({expression:G.string().nullish(),every_seconds:G.number().nullish(),next_run_at:G.string().nullish()}).nullish(),github:G.object({event:G.string().nullish(),action:G.string().nullish(),repo:G.string().nullish()}).nullish(),last_fired_at:G.string().nullish()}),P9=G.object({id:G.string().min(1),name:G.string().nullish(),instructions:G.string().nullish(),enabled:G.boolean(),triggers:G.array(CZ).default([])}),PZ=G.object({items:G.array(P9).default([]),end_cursor:G.string().nullish(),has_next_page:G.boolean().optional()}),IZ=G.object({id:G.string().min(1),slug:G.string().nullish(),name:G.string(),description:G.string().nullish(),transport:G.string().nullish(),url:G.string().nullish(),enabled:G.boolean()}),xZ=G.object({items:G.array(IZ).default([])}),EZ=G.object({status:G.string(),summary:G.string().nullish(),category:G.string().nullish(),outcome:G.string().nullish(),message_count:G.number().nullish(),pr_url:G.string().nullish(),cost_usd:G.number().nullish(),generated_at:G.string().nullish()}),C9=G.object({tags:G.array(G.string()).default([])}),SZ=G.enum(["linux","macos"]),I9=G.object({id:G.string().min(1),name:G.string().min(1),platform:SZ.nullable(),workers:G.object({total:G.number().int(),online:G.number().int(),busy:G.number().int(),idle:G.number().int()}),sessions:G.object({queued:G.number().int(),running:G.number().int()})}),wZ=G.object({machines:G.array(I9)}),bZ=G.object({machine:I9}),kZ=G.object({deleted:G.literal(!0),revoked_workers:G.number().int(),revoked_tokens:G.number().int()}),yZ=G.object({token:G.object({id:G.string().min(1),machine_id:G.string().min(1),token_prefix:G.string()}),secret:G.string().startsWith("rmt_")}),x9=G.looseObject({machine_id:G.string().min(1),machine_name:G.string().min(1)}),fZ=x9.extend({organization_id:G.string().min(1)}),nV=G.object({id:G.string().min(1),name:G.string().min(1),state:G.enum(["waiting","placed"]),queue_position:G.number().int().nullable()});var rV=G.union([G.object({kind:G.literal("cloud")}),G.object({kind:G.enum(["mac","headless"]),device_id:G.string().min(1),root_id:G.string().min(1)})]);function P0($,J,Z){let Q=$.safeParse(J);if(!Q.success)throw new Y0(502,Z,"Reason returned an unexpected response.");return Q.data}var hZ=G.object({error:G.object({type:G.string(),message:G.string()})});function E9($,J,Z){let Q=hZ.safeParse(J),X=typeof J.error==="string"?J.error:Q.success?Q.data.error.type:`http_${$}`,Y=typeof J.detail==="string"?J.detail:typeof J.message==="string"?J.message:Q.success?Q.data.error.message:`Reason request failed (${$}${typeof J.error==="string"?` ${J.error}`:""})`,B=X==="github_connection_required"&&typeof J.connect_url==="string"&&/^https?:\/\//.test(J.connect_url)?` Connect it at ${J.connect_url}`:"",V=Z===null||Z.trim()===""?NaN:Number(Z);return new Y0($,X,`${Y}${B}`,typeof J.suggested_model==="string"?J.suggested_model:void 0,Number.isFinite(V)&&V>=0?V*1000:void 0,typeof J.resolution_reason==="string"?J.resolution_reason:void 0)}async function S9($){let J=await($.fetchImpl??fetch)(`${$.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${$.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify($.body),signal:AbortSignal.timeout(30000),redirect:"error"}),Z=await J.json().catch(()=>({}));if(!J.ok)throw E9(J.status,Z,J.headers.get("retry-after"));return P0(fZ,Z,"invalid_machine_ticket")}class U1{options;credentials;constructor($,J={}){this.options=J;this.credentials=$}trackEvent($,J={}){}async request($,J={},Z=!1){let Q=this.options.fetchImpl??fetch,X=await Q(`${this.credentials.apiOrigin}/v3${$}`,{method:J.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":"reason-cli","x-reason-agent":"Reason CLI",...J.raw?{"content-type":J.raw.contentType}:J.body===void 0?{}:{"content-type":"application/json"},...J.headers},body:J.raw?J.raw.bytes:J.body===void 0?void 0:JSON.stringify(J.body),signal:J.signal,redirect:"error"}),Y=await X.json().catch(()=>({}));if(X.status===401&&!Z&&J.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let B=await k1({fetchImpl:Q,path:this.options.credentialsPath,forceRefresh:!0,signal:J.signal});if(B)return this.credentials=B,this.request($,J,!0)}if(!X.ok)throw E9(X.status,Y,X.headers.get("retry-after"));return Y}createHeadlessDeviceEnrollmentTicket($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:$,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice($){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:$,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(J){if(J instanceof Y0&&(J.status===404||J.status===405||J.status===403&&J.code==="endpoint_not_available"))return null;throw J}}addDeviceRoot($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent($)}/roots`,{method:"POST",body:J,signal:AbortSignal.timeout(30000)})}removeDeviceRoot($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent($)}/roots/${encodeURIComponent(J)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath($,J=""){let Z=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return $===void 0?Z:`${Z}/${encodeURIComponent($)}${J}`}async listMachines(){return P0(wZ,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine($){let J=await this.request(this.machinePath(),{method:"POST",body:{name:$.name,...$.platform?{platform:$.platform}:{}}});return P0(bZ,J,"invalid_machine").machine}async deleteMachine($){let J=await this.request(this.machinePath($),{method:"DELETE"});return P0(kZ,J,"invalid_machine_deletion")}async createMachineToken($){let J=await this.request(this.machinePath($,"/tokens"),{method:"POST",body:{}});return P0(yZ,J,"invalid_machine_token")}async createMachineEnrollmentTicket($,J){let Z=await this.request(this.machinePath($,"/enrollment-tickets"),{method:"POST",body:J,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return P0(x9,Z,"invalid_machine_ticket")}self($){return this.request("/self",{signal:$})}claimExistingCliPairing($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:$}})}connectAnthropicProvider($,J,Z={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:Z.retryUnauthorized,signal:Z.signal,body:{access_token:$.access,refresh_token:$.refresh,expires_at:new Date($.expires).toISOString(),...J?{account_key:J}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((J)=>{let Z=typeof J.full_name==="string"?J.full_name:typeof J.repo_full_name==="string"?J.repo_full_name:null;if(!Z)return[];return[{repo_id:typeof J.repo_id==="string"?J.repo_id:void 0,full_name:Z,provider:J.provider==="gitlab"?"gitlab":"github",default_branch:typeof J.default_branch==="string"?J.default_branch:null,private:typeof J.private==="boolean"?J.private:void 0}]})}async listProjects(){let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),J=jZ.safeParse($);if(!J.success)throw new Y0(502,"invalid_project_list","Reason returned an unexpected project list.");return J.data.items}async listReasons(){let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return P0(OZ,$,"invalid_reason_list").items}async openReasonConversation($){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent($)}/conversation`,{method:"POST"});return P0(G.object({session_id:G.string().min(1)}),J,"invalid_reason_conversation").session_id}async listSkills(){try{let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return P0(RZ,$,"invalid_skill_list").items}catch($){if($ instanceof Y0&&($.status===403||$.status===404))return[];throw $}}async listDevices(){let $=[],J=null;for(let Z=0;Z<50;Z+=1){let Q=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${J?`?after=${encodeURIComponent(J)}`:""}`),X=LZ.safeParse(Q);if(!X.success)throw new Y0(502,"invalid_device_list","Reason returned an unexpected machine list.");if($.push(...X.data.devices),J=X.data.has_next_page?X.data.end_cursor??null:null,!J)break}return $}async listModels(){try{let J=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((X)=>X.hidden!==!0),Z=J.filter((X)=>X.available!==!1).map(({reasoning_efforts:X,hidden:Y,available:B,...V})=>({...V,...Array.isArray(X)?{reasoning_efforts:FZ.filter((K)=>X.includes(K))}:{}})),Q=new Set(Z.map((X)=>X.detail));return{models:Z.length>1&&Q.size===1?Z.map(({detail:X,...Y})=>Y):Z,runnable:Z.length>0||J.length===0}}catch($){if($ instanceof Y0&&($.status===403||$.status===404))return{models:[],runnable:!0};throw $}}async getAgentVersion($){try{let J=await this.request("/deployment",{signal:$,retryUnauthorized:!1});return U9(J.reason_version)?J.reason_version:null}catch{return null}}async getUsageQuota(){try{let $=MZ.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!$.success)return null;let J;try{J=_Z(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...$.data,own_inference:J}}catch($){if($ instanceof Y0&&($.status===403||$.status===404))return null;throw $}}async listSessions($=50,J,Z={}){let Q=new URLSearchParams({first:String(Math.min(Math.max($,1),200)),status:Z.status??"active"});if(J)Q.set("project_id",J);if(Z.origin)Q.set("origin",Z.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${Q.toString()}`)).items??[]}getSession($,J){let Z=J?.fields.length?`?fields=${encodeURIComponent(J.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}${Z}`)}async prestartSession($){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:$}});return J?.status==="starting"||J?.status==="ready"}async createSession($){let J=$.mode==="ephemeral"||$.workspaceOwnership==="externally-managed";if($.attachments?.length)await this.requireSessionAttachments();if(J||$.runtimeProfile){let X=await this.request("/deployment");if(J&&(!Array.isArray(X.session_modes)||!X.session_modes.includes($.mode??"standard")||!Array.isArray(X.workspace_ownerships)||!X.workspace_ownerships.includes($.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if($.runtimeProfile&&(!Array.isArray(X.experimental_runtime_profiles)||!X.experimental_runtime_profiles.includes($.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let Z=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:$.prompt,...$.attachments?.length?{attachments:$.attachments}:{},...$.mode?{mode:$.mode}:{},...$.workspaceOwnership?{workspace_ownership:$.workspaceOwnership}:{},...$.target?{target:$.target}:{},...$.repo?{repo:$.repo}:{},...$.provider?{provider:$.provider}:{},...$.model?{model:$.model}:{},...$.reasoningEffort?{reasoning_effort:$.reasoningEffort}:{},...$.runtimeProfile?{experimental_runtime_profile:$.runtimeProfile}:{},...$.ref?{ref:$.ref}:{},...$.branch?{branch:$.branch}:{},...$.completionMode?{completion_mode:$.completionMode}:{},...$.env&&Object.keys($.env).length>0?{env:$.env}:{},...$.clientSessionId?{client_session_id:$.clientSessionId}:{},...$.longRunning?{long_running:{enabled:!0}}:{},...$.spendLimitRcu?{spend_limit_rcu:$.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),Q=await this.getSession(Z.session_id);if(J){let X=Q.session_policy,Y=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!X||X.version!==1||X.mode!==($.mode??"standard")||X.workspaceOwnership!==($.workspaceOwnership??"managed")||!X.components||Y.some((B)=>X.components[B]!==!0))throw await this.cancelSession(Z.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if($.runtimeProfile&&Q.experimental_runtime_profile!==$.runtimeProfile)throw await this.cancelSession(Z.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return Q}async getEvents($,J=-1,Z={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/events?after_seq=${J}&limit=500${Z.waitMs?`&wait_ms=${Z.waitMs}`:""}`,Z.signal?{signal:Z.signal}:{})}catch(Q){if(!(Q instanceof Y0)||Q.status!==403&&Q.status!==404)throw Q;return{session:await this.getSession($),items:[],next_seq:J}}}async getMessages($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages?first=500${J===void 0?"":`&after_seq=${J}`}`)}async getAttachments($,J){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/attachments${J?`?view=${J}`:""}`)).items??[]}catch(Z){if(Z instanceof Y0&&(Z.status===403||Z.status===404))return[];throw Z}}async requireSessionAttachments(){let $=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if($.session_attachments!==!0){let J=typeof $.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test($.reason_version)?`Agent ${$.reason_version}`:null,Z=typeof $.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test($.commit_sha)?`server ${$.commit_sha.slice(0,12)}`:null,Q=[J,Z].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${Q?` (${Q})`:""}. 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($,J,Z={}){if(Z.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages`,{method:"POST",body:{message:J,...Z.attachments?.length?{attachments:Z.attachments}:{},...Z.model?{model:Z.model}:{},...Z.reasoningEffort?{reasoning_effort:Z.reasoningEffort}:{},...Z.target?{target:Z.target}:{},...Z.delivery?{delivery:Z.delivery}:{}}})}async steerQueuedMessage($,J){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages/${encodeURIComponent(J)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage($,J){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages/${encodeURIComponent(J)}/queued`,{method:"DELETE"})}async getConversation($){let J=[],Z=null;for(let Q=0;Q<50;Q+=1){let X=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/conversation${Z?`?after=${encodeURIComponent(Z)}`:""}`);if(J.push(...X.items??[]),!X.has_next_page||!X.end_cursor)break;Z=X.end_cursor}return J}createSharedLink($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/shared-links`,{method:"POST",body:{url:J.url,...J.label?{label:J.label}:{},...J.expiresInSeconds!==void 0?{expires_in_seconds:J.expiresInSeconds}:{}}})}sessionAction($,J,Z={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/${J}`,{method:"POST",body:Z})}renameSession($,J){return this.sessionAction($,"rename",{title:J||null})}moveSessionToProject($,J){return this.sessionAction($,"project",{project_id:J})}compactSession($){return this.sessionAction($,"compact")}retrySession($){return this.sessionAction($,"retry")}rewindSession($,J){return this.sessionAction($,"rewind",{message_id:J.messageId,content:J.content,request_id:J.requestId})}forkSession($,J){return this.sessionAction($,"fork",{...J.message?{message:J.message}:{},client_session_id:J.clientSessionId})}cancelSession($,J={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/cancel`,{method:"POST",body:J.mode==="hard"?{mode:"hard"}:{}})}sessionPath($,J=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}${J}`}async archiveSession($){await this.request(this.sessionPath($,"/archive"),{method:"POST",body:{}})}async unarchiveSession($){await this.request(this.sessionPath($,"/unarchive"),{method:"POST",body:{}})}async deleteSession($){await this.request(this.sessionPath($),{method:"DELETE"})}async listSessionTags($){return P0(C9,await this.request(this.sessionPath($,"/tags")),"invalid_session_tags").tags}async appendSessionTags($,J){let Z=await this.request(this.sessionPath($,"/tags"),{method:"POST",body:{tags:J}});return P0(C9,Z,"invalid_session_tags").tags}async sessionInsight($,J=!1){let Z=await this.request(this.sessionPath($,J?"/insights/generate":"/insights"),J?{method:"POST",body:{}}:{});return P0(EZ,Z,"invalid_session_insight")}async listAutomations(){let $=[],J=null;for(let Z=0;Z<20;Z+=1){let Q=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${J?`&after=${encodeURIComponent(J)}`:""}`),X=P0(PZ,Q,"invalid_automation_list");if($.push(...X.items),J=X.has_next_page?X.end_cursor??null:null,!J)break}return $}async createScheduledAutomation($,J){let Z=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,Q=P0(P9,await this.request(Z,{method:"POST",body:{name:$.name,instructions:$.instructions,...$.repo?{repo:$.repo.full_name,provider:$.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${Z}/${encodeURIComponent(Q.id)}/triggers`,{method:"POST",body:J})}catch(X){throw await this.deleteAutomation(Q.id).catch(()=>{return}),X}return Q}async setAutomationEnabled($,J){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent($)}`,{method:"PATCH",body:{enabled:J}})}async deleteAutomation($){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent($)}`,{method:"DELETE"})}async transcribe($,J){let Z=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:$,contentType:J}});return P0(G.object({transcript:G.string()}),Z,"invalid_transcript").transcript}async listMcpServers(){let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return P0(xZ,$,"invalid_mcp_server_list").items}async setSkillEnabled($,J){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent($)}`,{method:"PUT",body:{is_enabled:J}})}}function y1($,J){let Z=k0($,"REASON_API_URL")?.trim();if(!Z)return j4(J);let Q=new URL(Z);if(Q.protocol!=="https:"&&!(Q.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(Q.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return Q.origin}function mZ($){return k0($,"REASON_API_URL")?.trim()?y1($,"production"):void 0}function z4($){return k0($,"REASON_API_KEY")?.trim()||void 0}async function w9($,J){let Z=$.env??process.env,Q=z4(Z);if(!Q)return($.getCredentials??k1)({apiOrigin:mZ(Z),signal:J});let X=y1(Z,$.channel??x0({env:Z})),Y=await($.fetchImpl??fetch)(X+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+Q,accept:"application/json"},signal:J}),B=await Y.json().catch(()=>({})),V=n0(B)?B:{};if(!Y.ok){let N=typeof V.detail==="string"?V.detail:typeof V.message==="string"?V.message:"API key authentication failed ("+Y.status+")";throw new Y0(Y.status,typeof V.error==="string"?V.error:"api_key_auth_failed",N)}if(typeof V.org_id!=="string"||!V.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let K=Array.isArray(V.scopes)?V.scopes.filter((N)=>typeof N==="string"):[];return{credentialKind:"api_key",apiOrigin:X,accessToken:Q,orgId:V.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:K}}import{createHash as vZ}from"crypto";import{unlinkSync as gZ}from"fs";import{platform as uZ}from"os";import{join as dZ}from"path";var b9=G.discriminatedUnion("store",[G.strictObject({version:G.literal(1),store:G.literal("keychain")}),G.strictObject({version:G.literal(1),store:G.literal("file"),api_key:G.string().min(1).max(4096)})]),f1=($)=>dZ($,"api-key.json");function z1($){let J=vZ("sha256").update(`reason-connect-api-key
|
|
4
|
+
`,{mode:384,flag:"wx"}),M9(Q,384),_9($,"utf8")!==J)throw Error("credentials_changed");XZ(Q,$)}catch{try{F9(Q)}catch{}}}function D9($=$1()){if(!T9($))return!1;return F9($),!0}var j9=["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 pV=j9.filter(($)=>$!=="network:read"&&$!=="network:write");class x$ extends Error{oauthCode;constructor($,J=null){super($);this.oauthCode=J;this.name="LoginError"}}function A9(){let $=z9(48).toString("base64url"),J=KZ("sha256").update($).digest("base64url");return{verifier:$,challenge:J,state:z9(32).toString("base64url")}}function HZ($,J){let Z=typeof $.error==="string"?$.error:null,Q=typeof $.error_description==="string"?$.error_description:Z?Z:J;return new x$(Q,Z)}async function NZ($,J,Z,Q){let X=await Z(`${$}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:J,signal:Q}),Y=await X.json().catch(()=>({}));if(!X.ok)throw HZ(Y,`OAuth token request failed (${X.status})`);return Y}var UZ=1e4;async function qZ($,J={}){let Z=J.fetchImpl??fetch,Q=await NZ($.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:$.clientId,refresh_token:$.refreshToken}),Z,AbortSignal.timeout(UZ)).catch((Y)=>{if(Y instanceof Error&&Y.name==="TimeoutError")throw new x$("Reason did not answer the login refresh in time. Check the network and retry.");throw Y});if(typeof Q.access_token!=="string"||typeof Q.refresh_token!=="string"||typeof Q.expires_in!=="number")throw new x$("Reason returned an incomplete refreshed login.");let X={...$,accessToken:Q.access_token,refreshToken:Q.refresh_token,expiresAt:new Date(Date.now()+Q.expires_in*1000).toISOString(),scopes:typeof Q.scope==="string"?Q.scope.split(/\s+/).filter(Boolean):$.scopes};return L9(X,J.path??$1()),X}var M2=new Map;function O9($,J){if(!J)return $;if(J.aborted)return Promise.reject(J.reason);return new Promise((Z,Q)=>{let X=()=>Q(J.reason);J.addEventListener("abort",X,{once:!0}),$.then(Z,Q).finally(()=>J.removeEventListener("abort",X))})}async function k1($={}){let J=$.path??$1(),Z=I$(J);if(!Z)return null;let Q=$.apiOrigin??k0(process.env,"REASON_API_URL")?.trim();if(Q&&!z0(Z.apiOrigin,new URL(Q).origin))return null;let X=Date.parse(Z.expiresAt)<=Date.now()+60000;if(!$.forceRefresh&&!X)return Z;let Y=[J,Z.apiOrigin,Z.clientId,Z.refreshToken].join("\x00"),B=M2.get(Y);if(B)return O9(B,$.signal);let V;return V=qZ(Z,{fetchImpl:$.fetchImpl,path:J}).catch(async(K)=>{if(!(K instanceof x$)||K.oauthCode!=="invalid_grant"&&K.oauthCode!=="invalid_client")throw K;let N=I$(J),q=K.oauthCode==="invalid_client"?N?.clientId!==Z.clientId:N?.refreshToken!==Z.refreshToken;if(N&&q)return k1({fetchImpl:$.fetchImpl,path:J});return D9(J),null}).finally(()=>{if(M2.get(Y)===V)M2.delete(Y)}),M2.set(Y,V),O9(V,$.signal)}function R9($,J){return new Promise((Z)=>{let Q=VZ({input:$}),X=!1,Y=(V)=>{if(X)return;X=!0,J.removeEventListener("abort",B),Q.close(),$.pause(),Z(V)},B=()=>Y(null);J.addEventListener("abort",B,{once:!0}),Q.once("line",(V)=>Y(V)),Q.once("close",()=>Y(null))})}var MZ=G.object({label:G.string(),used_percent:G.number().min(0).max(100).nullable(),resets_at:G.string().nullable(),exhausted:G.boolean().nullable()}),TZ=G.object({groups:G.array(G.object({selectable:G.boolean().optional(),accounts:G.array(G.object({source_id:G.string().min(1),model_ids:G.array(G.string().min(1)).optional()}))}))});function _Z($){let J=TZ.safeParse($);if(!J.success)return;return J.data.groups.some((Z)=>Z.selectable!==!1&&Z.accounts.some((Q)=>Q.model_ids===void 0||Q.model_ids.length>0))}class Y0 extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor($,J,Z,Q,X,Y){super(Z);this.status=$;this.code=J;this.suggestedModel=Q;this.retryAfterMs=X;this.resolutionReason=Y;this.name="ApiError"}static rateLimitDelayMs($,J){if(!($ instanceof Y0)||$.status!==429)return null;return Math.min(60000,Math.max(J,$.retryAfterMs??0))}}var FZ=["minimal","low","medium","high","xhigh","max"],WZ=G.object({id:G.string().min(1),kind:G.string(),name:G.string(),custom_name:G.string().nullish(),status:G.string(),online:G.boolean(),compatible:G.boolean().optional(),compatibility_reason:G.string().nullish(),folder_lane_of:G.string().nullish(),roots:G.array(G.object({id:G.string().min(1),label:G.string()}))}),LZ=G.object({devices:G.array(WZ),end_cursor:G.string().nullish(),has_next_page:G.boolean().optional()}),DZ=G.object({id:G.string().min(1),name:G.string()}),jZ=G.object({items:G.array(DZ)}),zZ=G.object({id:G.string().min(1),name:G.string(),main:G.boolean(),mine:G.boolean(),session_id:G.string().nullish(),appearance:G.object({color:G.string().nullish()}).nullish().catch(null)}),OZ=G.object({items:G.array(zZ)}),AZ=G.object({skill_id:G.string().min(1),name:G.string(),description:G.string().nullish(),activation_keywords:G.array(G.string()).default([]),is_enabled:G.boolean().default(!0)}),RZ=G.object({items:G.array(AZ).default([])}),CZ=G.object({id:G.string().min(1),kind:G.string(),enabled:G.boolean(),schedule:G.object({expression:G.string().nullish(),every_seconds:G.number().nullish(),next_run_at:G.string().nullish()}).nullish(),github:G.object({event:G.string().nullish(),action:G.string().nullish(),repo:G.string().nullish()}).nullish(),last_fired_at:G.string().nullish()}),P9=G.object({id:G.string().min(1),name:G.string().nullish(),instructions:G.string().nullish(),enabled:G.boolean(),triggers:G.array(CZ).default([])}),PZ=G.object({items:G.array(P9).default([]),end_cursor:G.string().nullish(),has_next_page:G.boolean().optional()}),IZ=G.object({id:G.string().min(1),slug:G.string().nullish(),name:G.string(),description:G.string().nullish(),transport:G.string().nullish(),url:G.string().nullish(),enabled:G.boolean()}),xZ=G.object({items:G.array(IZ).default([])}),EZ=G.object({status:G.string(),summary:G.string().nullish(),category:G.string().nullish(),outcome:G.string().nullish(),message_count:G.number().nullish(),pr_url:G.string().nullish(),cost_usd:G.number().nullish(),generated_at:G.string().nullish()}),C9=G.object({tags:G.array(G.string()).default([])}),SZ=G.enum(["linux","macos"]),I9=G.object({id:G.string().min(1),name:G.string().min(1),platform:SZ.nullable(),workers:G.object({total:G.number().int(),online:G.number().int(),busy:G.number().int(),idle:G.number().int()}),sessions:G.object({queued:G.number().int(),running:G.number().int()})}),wZ=G.object({machines:G.array(I9)}),bZ=G.object({machine:I9}),kZ=G.object({deleted:G.literal(!0),revoked_workers:G.number().int(),revoked_tokens:G.number().int()}),yZ=G.object({token:G.object({id:G.string().min(1),machine_id:G.string().min(1),token_prefix:G.string()}),secret:G.string().startsWith("rmt_")}),x9=G.looseObject({machine_id:G.string().min(1),machine_name:G.string().min(1)}),fZ=x9.extend({organization_id:G.string().min(1)}),nV=G.object({id:G.string().min(1),name:G.string().min(1),state:G.enum(["waiting","placed"]),queue_position:G.number().int().nullable()});var rV=G.union([G.object({kind:G.literal("cloud")}),G.object({kind:G.enum(["mac","headless"]),device_id:G.string().min(1),root_id:G.string().min(1)})]);function P0($,J,Z){let Q=$.safeParse(J);if(!Q.success)throw new Y0(502,Z,"Reason returned an unexpected response.");return Q.data}var hZ=G.object({error:G.object({type:G.string(),message:G.string()})});function E9($,J,Z){let Q=hZ.safeParse(J),X=typeof J.error==="string"?J.error:Q.success?Q.data.error.type:`http_${$}`,Y=typeof J.detail==="string"?J.detail:typeof J.message==="string"?J.message:Q.success?Q.data.error.message:`Reason request failed (${$}${typeof J.error==="string"?` ${J.error}`:""})`,B=X==="github_connection_required"&&typeof J.connect_url==="string"&&/^https?:\/\//.test(J.connect_url)?` Connect it at ${J.connect_url}`:"",V=Z===null||Z.trim()===""?NaN:Number(Z);return new Y0($,X,`${Y}${B}`,typeof J.suggested_model==="string"?J.suggested_model:void 0,Number.isFinite(V)&&V>=0?V*1000:void 0,typeof J.resolution_reason==="string"?J.resolution_reason:void 0)}async function S9($){let J=await($.fetchImpl??fetch)(`${$.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${$.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify($.body),signal:AbortSignal.timeout(30000),redirect:"error"}),Z=await J.json().catch(()=>({}));if(!J.ok)throw E9(J.status,Z,J.headers.get("retry-after"));return P0(fZ,Z,"invalid_machine_ticket")}class U1{options;credentials;constructor($,J={}){this.options=J;this.credentials=$}trackEvent($,J={}){}async request($,J={},Z=!1){let Q=this.options.fetchImpl??fetch,X=await Q(`${this.credentials.apiOrigin}/v3${$}`,{method:J.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":"reason-cli","x-reason-agent":"Reason CLI",...J.raw?{"content-type":J.raw.contentType}:J.body===void 0?{}:{"content-type":"application/json"},...J.headers},body:J.raw?J.raw.bytes:J.body===void 0?void 0:JSON.stringify(J.body),signal:J.signal,redirect:"error"}),Y=await X.json().catch(()=>({}));if(X.status===401&&!Z&&J.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let B=await k1({fetchImpl:Q,path:this.options.credentialsPath,forceRefresh:!0,signal:J.signal});if(B)return this.credentials=B,this.request($,J,!0)}if(!X.ok)throw E9(X.status,Y,X.headers.get("retry-after"));return Y}createHeadlessDeviceEnrollmentTicket($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:$,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice($){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:$,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(J){if(J instanceof Y0&&(J.status===404||J.status===405||J.status===403&&J.code==="endpoint_not_available"))return null;throw J}}addDeviceRoot($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent($)}/roots`,{method:"POST",body:J,signal:AbortSignal.timeout(30000)})}removeDeviceRoot($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent($)}/roots/${encodeURIComponent(J)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath($,J=""){let Z=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return $===void 0?Z:`${Z}/${encodeURIComponent($)}${J}`}async listMachines(){return P0(wZ,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine($){let J=await this.request(this.machinePath(),{method:"POST",body:{name:$.name,...$.platform?{platform:$.platform}:{}}});return P0(bZ,J,"invalid_machine").machine}async deleteMachine($){let J=await this.request(this.machinePath($),{method:"DELETE"});return P0(kZ,J,"invalid_machine_deletion")}async createMachineToken($){let J=await this.request(this.machinePath($,"/tokens"),{method:"POST",body:{}});return P0(yZ,J,"invalid_machine_token")}async createMachineEnrollmentTicket($,J){let Z=await this.request(this.machinePath($,"/enrollment-tickets"),{method:"POST",body:J,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return P0(x9,Z,"invalid_machine_ticket")}self($){return this.request("/self",{signal:$})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`)}startAgentNetwork($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:$})}rotateAgentNetwork($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:$})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`)).items??[]).flatMap((J)=>typeof J.email==="string"?[{email:J.email,role:typeof J.role==="string"?J.role:"member"}]:[])}claimExistingCliPairing($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:$}})}connectAnthropicProvider($,J,Z={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:Z.retryUnauthorized,signal:Z.signal,body:{access_token:$.access,refresh_token:$.refresh,expires_at:new Date($.expires).toISOString(),...J?{account_key:J}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((J)=>{let Z=typeof J.full_name==="string"?J.full_name:typeof J.repo_full_name==="string"?J.repo_full_name:null;if(!Z)return[];return[{repo_id:typeof J.repo_id==="string"?J.repo_id:void 0,full_name:Z,provider:J.provider==="gitlab"?"gitlab":"github",default_branch:typeof J.default_branch==="string"?J.default_branch:null,private:typeof J.private==="boolean"?J.private:void 0}]})}async listProjects(){let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),J=jZ.safeParse($);if(!J.success)throw new Y0(502,"invalid_project_list","Reason returned an unexpected project list.");return J.data.items}async listReasons(){let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return P0(OZ,$,"invalid_reason_list").items}async openReasonConversation($){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent($)}/conversation`,{method:"POST"});return P0(G.object({session_id:G.string().min(1)}),J,"invalid_reason_conversation").session_id}async listSkills(){try{let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return P0(RZ,$,"invalid_skill_list").items}catch($){if($ instanceof Y0&&($.status===403||$.status===404))return[];throw $}}async listDevices(){let $=[],J=null;for(let Z=0;Z<50;Z+=1){let Q=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${J?`?after=${encodeURIComponent(J)}`:""}`),X=LZ.safeParse(Q);if(!X.success)throw new Y0(502,"invalid_device_list","Reason returned an unexpected machine list.");if($.push(...X.data.devices),J=X.data.has_next_page?X.data.end_cursor??null:null,!J)break}return $}async listModels(){try{let J=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((X)=>X.hidden!==!0),Z=J.filter((X)=>X.available!==!1).map(({reasoning_efforts:X,hidden:Y,available:B,...V})=>({...V,...Array.isArray(X)?{reasoning_efforts:FZ.filter((K)=>X.includes(K))}:{}})),Q=new Set(Z.map((X)=>X.detail));return{models:Z.length>1&&Q.size===1?Z.map(({detail:X,...Y})=>Y):Z,runnable:Z.length>0||J.length===0}}catch($){if($ instanceof Y0&&($.status===403||$.status===404))return{models:[],runnable:!0};throw $}}async getAgentVersion($){try{let J=await this.request("/deployment",{signal:$,retryUnauthorized:!1});return U9(J.reason_version)?J.reason_version:null}catch{return null}}async getUsageQuota(){try{let $=MZ.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!$.success)return null;let J;try{J=_Z(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...$.data,own_inference:J}}catch($){if($ instanceof Y0&&($.status===403||$.status===404))return null;throw $}}async listSessions($=50,J,Z={}){let Q=new URLSearchParams({first:String(Math.min(Math.max($,1),200)),status:Z.status??"active"});if(J)Q.set("project_id",J);if(Z.origin)Q.set("origin",Z.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${Q.toString()}`)).items??[]}getSession($,J){let Z=J?.fields.length?`?fields=${encodeURIComponent(J.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}${Z}`)}async prestartSession($){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:$}});return J?.status==="starting"||J?.status==="ready"}async createSession($){let J=$.mode==="ephemeral"||$.workspaceOwnership==="externally-managed";if($.attachments?.length)await this.requireSessionAttachments();if(J||$.runtimeProfile){let X=await this.request("/deployment");if(J&&(!Array.isArray(X.session_modes)||!X.session_modes.includes($.mode??"standard")||!Array.isArray(X.workspace_ownerships)||!X.workspace_ownerships.includes($.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if($.runtimeProfile&&(!Array.isArray(X.experimental_runtime_profiles)||!X.experimental_runtime_profiles.includes($.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let Z=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:$.prompt,...$.attachments?.length?{attachments:$.attachments}:{},...$.mode?{mode:$.mode}:{},...$.workspaceOwnership?{workspace_ownership:$.workspaceOwnership}:{},...$.target?{target:$.target}:{},...$.repo?{repo:$.repo}:{},...$.provider?{provider:$.provider}:{},...$.model?{model:$.model}:{},...$.reasoningEffort?{reasoning_effort:$.reasoningEffort}:{},...$.runtimeProfile?{experimental_runtime_profile:$.runtimeProfile}:{},...$.ref?{ref:$.ref}:{},...$.branch?{branch:$.branch}:{},...$.completionMode?{completion_mode:$.completionMode}:{},...$.env&&Object.keys($.env).length>0?{env:$.env}:{},...$.clientSessionId?{client_session_id:$.clientSessionId}:{},...$.longRunning?{long_running:{enabled:!0}}:{},...$.spendLimitRcu?{spend_limit_rcu:$.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),Q=await this.getSession(Z.session_id);if(J){let X=Q.session_policy,Y=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!X||X.version!==1||X.mode!==($.mode??"standard")||X.workspaceOwnership!==($.workspaceOwnership??"managed")||!X.components||Y.some((B)=>X.components[B]!==!0))throw await this.cancelSession(Z.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if($.runtimeProfile&&Q.experimental_runtime_profile!==$.runtimeProfile)throw await this.cancelSession(Z.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return Q}async getEvents($,J=-1,Z={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/events?after_seq=${J}&limit=500${Z.waitMs?`&wait_ms=${Z.waitMs}`:""}`,Z.signal?{signal:Z.signal}:{})}catch(Q){if(!(Q instanceof Y0)||Q.status!==403&&Q.status!==404)throw Q;return{session:await this.getSession($),items:[],next_seq:J}}}async getMessages($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages?first=500${J===void 0?"":`&after_seq=${J}`}`)}async getAttachments($,J){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/attachments${J?`?view=${J}`:""}`)).items??[]}catch(Z){if(Z instanceof Y0&&(Z.status===403||Z.status===404))return[];throw Z}}async requireSessionAttachments(){let $=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if($.session_attachments!==!0){let J=typeof $.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test($.reason_version)?`Agent ${$.reason_version}`:null,Z=typeof $.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test($.commit_sha)?`server ${$.commit_sha.slice(0,12)}`:null,Q=[J,Z].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${Q?` (${Q})`:""}. 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($,J,Z={}){if(Z.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages`,{method:"POST",body:{message:J,...Z.attachments?.length?{attachments:Z.attachments}:{},...Z.model?{model:Z.model}:{},...Z.reasoningEffort?{reasoning_effort:Z.reasoningEffort}:{},...Z.target?{target:Z.target}:{},...Z.delivery?{delivery:Z.delivery}:{}}})}async steerQueuedMessage($,J){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages/${encodeURIComponent(J)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage($,J){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages/${encodeURIComponent(J)}/queued`,{method:"DELETE"})}async getConversation($){let J=[],Z=null;for(let Q=0;Q<50;Q+=1){let X=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/conversation${Z?`?after=${encodeURIComponent(Z)}`:""}`);if(J.push(...X.items??[]),!X.has_next_page||!X.end_cursor)break;Z=X.end_cursor}return J}createSharedLink($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/shared-links`,{method:"POST",body:{url:J.url,...J.label?{label:J.label}:{},...J.expiresInSeconds!==void 0?{expires_in_seconds:J.expiresInSeconds}:{}}})}sessionAction($,J,Z={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/${J}`,{method:"POST",body:Z})}renameSession($,J){return this.sessionAction($,"rename",{title:J||null})}moveSessionToProject($,J){return this.sessionAction($,"project",{project_id:J})}compactSession($){return this.sessionAction($,"compact")}retrySession($){return this.sessionAction($,"retry")}rewindSession($,J){return this.sessionAction($,"rewind",{message_id:J.messageId,content:J.content,request_id:J.requestId})}forkSession($,J){return this.sessionAction($,"fork",{...J.message?{message:J.message}:{},client_session_id:J.clientSessionId})}cancelSession($,J={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/cancel`,{method:"POST",body:J.mode==="hard"?{mode:"hard"}:{}})}sessionPath($,J=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}${J}`}async archiveSession($){await this.request(this.sessionPath($,"/archive"),{method:"POST",body:{}})}async unarchiveSession($){await this.request(this.sessionPath($,"/unarchive"),{method:"POST",body:{}})}async deleteSession($){await this.request(this.sessionPath($),{method:"DELETE"})}async listSessionTags($){return P0(C9,await this.request(this.sessionPath($,"/tags")),"invalid_session_tags").tags}async appendSessionTags($,J){let Z=await this.request(this.sessionPath($,"/tags"),{method:"POST",body:{tags:J}});return P0(C9,Z,"invalid_session_tags").tags}async sessionInsight($,J=!1){let Z=await this.request(this.sessionPath($,J?"/insights/generate":"/insights"),J?{method:"POST",body:{}}:{});return P0(EZ,Z,"invalid_session_insight")}async listAutomations(){let $=[],J=null;for(let Z=0;Z<20;Z+=1){let Q=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${J?`&after=${encodeURIComponent(J)}`:""}`),X=P0(PZ,Q,"invalid_automation_list");if($.push(...X.items),J=X.has_next_page?X.end_cursor??null:null,!J)break}return $}async createScheduledAutomation($,J){let Z=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,Q=P0(P9,await this.request(Z,{method:"POST",body:{name:$.name,instructions:$.instructions,...$.repo?{repo:$.repo.full_name,provider:$.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${Z}/${encodeURIComponent(Q.id)}/triggers`,{method:"POST",body:J})}catch(X){throw await this.deleteAutomation(Q.id).catch(()=>{return}),X}return Q}async setAutomationEnabled($,J){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent($)}`,{method:"PATCH",body:{enabled:J}})}async deleteAutomation($){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent($)}`,{method:"DELETE"})}async transcribe($,J){let Z=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:$,contentType:J}});return P0(G.object({transcript:G.string()}),Z,"invalid_transcript").transcript}async listMcpServers(){let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return P0(xZ,$,"invalid_mcp_server_list").items}async setSkillEnabled($,J){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent($)}`,{method:"PUT",body:{is_enabled:J}})}}function y1($,J){let Z=k0($,"REASON_API_URL")?.trim();if(!Z)return j4(J);let Q=new URL(Z);if(Q.protocol!=="https:"&&!(Q.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(Q.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return Q.origin}function mZ($){return k0($,"REASON_API_URL")?.trim()?y1($,"production"):void 0}function z4($){return k0($,"REASON_API_KEY")?.trim()||void 0}async function w9($,J){let Z=$.env??process.env,Q=z4(Z);if(!Q)return($.getCredentials??k1)({apiOrigin:mZ(Z),signal:J});let X=y1(Z,$.channel??x0({env:Z})),Y=await($.fetchImpl??fetch)(X+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+Q,accept:"application/json"},signal:J}),B=await Y.json().catch(()=>({})),V=n0(B)?B:{};if(!Y.ok){let N=typeof V.detail==="string"?V.detail:typeof V.message==="string"?V.message:"API key authentication failed ("+Y.status+")";throw new Y0(Y.status,typeof V.error==="string"?V.error:"api_key_auth_failed",N)}if(typeof V.org_id!=="string"||!V.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let K=Array.isArray(V.scopes)?V.scopes.filter((N)=>typeof N==="string"):[];return{credentialKind:"api_key",apiOrigin:X,accessToken:Q,orgId:V.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:K}}import{createHash as vZ}from"crypto";import{unlinkSync as gZ}from"fs";import{platform as uZ}from"os";import{join as dZ}from"path";var b9=G.discriminatedUnion("store",[G.strictObject({version:G.literal(1),store:G.literal("keychain")}),G.strictObject({version:G.literal(1),store:G.literal("file"),api_key:G.string().min(1).max(4096)})]),f1=($)=>dZ($,"api-key.json");function z1($){let J=vZ("sha256").update(`reason-connect-api-key
|
|
5
5
|
${$}`).digest("hex");return new e1(T2(),uZ(),J)}function O4($,J,Z=z1($)){try{Z.deleteBinding(),Z.createBinding(new TextEncoder().encode(J)),c(f1($),{version:1,store:"keychain"});return}catch(Q){if(!(Q instanceof G0))throw Q}c(f1($),{version:1,store:"file",api_key:J})}function p0($,J=z1($)){if(!u(f1($)))return null;let Z=b9.parse(JSON.parse(s(f1($))));if(Z.store==="file")return Z.api_key;try{let Q=J.loadBinding();return Q?new TextDecoder().decode(Q):null}catch(Q){if(!(Q instanceof G0))throw Q;throw Error("worker_api_key_unreadable")}}function k9($,J=z1($)){if(!u(f1($)))return;if(b9.parse(JSON.parse(s(f1($)))).store==="keychain")try{J.deleteBinding()}catch(Z){if(!(Z instanceof G0))throw Z}gZ(f1($))}async function A4($,J){let Z;try{Z=await w9({env:{REASON_API_KEY:J,REASON_API_URL:$.apiOrigin},fetchImpl:y0($.proxy)})}catch(Q){if(Q instanceof Y0&&(Q.status===401||Q.status===403))throw Error("worker_api_key_rejected");throw Q}if(!Z)throw Error("worker_api_key_rejected");if(!Z.scopes.includes("devices:write"))throw Error("worker_api_key_devices_write_required");return Z}import{readdirSync as BQ,renameSync as KQ,rmSync as v1}from"fs";import{join as M0}from"path";import{createHash as lZ}from"crypto";import{realpathSync as pZ,statSync as cZ,unlinkSync as _2}from"fs";import{platform as sZ}from"os";import{join as f0}from"path";function d($){return{state:f0(g($),"device.json"),control:f0(g($),"control.json"),lock:f0(g($),"lifecycle.lock"),socket:f0(g($),"control.sock"),daemon:f0(g($),"daemon.json"),releaseCheck:f0(g($),"release-check.json"),updateDeferral:f0(g($),"update-deferral.json"),firstHeartbeat:f0(g($),"first-heartbeat.json")}}var aZ=G.object({version:G.literal(1),device_id:G.string().min(1).max(160),offer:G.unknown().optional(),enrollment_ms:G.number().int().nonnegative().max($$).optional()});function f9($,J,Z){e(g($),!0),c(d($).firstHeartbeat,{version:1,device_id:J,...Z.offer?{offer:Z.offer}:{},...Z.enrollmentMs!==void 0?{enrollment_ms:Z.enrollmentMs}:{}})}function C4($,J){let Z=d($).firstHeartbeat;try{if(!u(Z))return null;let Q=aZ.safeParse(JSON.parse(s(Z)));if(_2(Z),!Q.success||Q.data.device_id!==J)return null;let X=F2(Q.data.offer);return{...X?{offer:X}:{},...Q.data.enrollment_ms!==void 0?{enrollmentMs:Q.data.enrollment_ms}:{}}}catch{return null}}function T0($,J=!1){e(g($),J);let Z=["local-device.key","local-device.binding","device.json"].filter((Q)=>{let X=f0(g($),Q);if(!u(X))return!1;return s(X),!0});return $.lifetime==="persistent"&&Z.join()==="device.json"?P4($):new R4(g($))}function W2($,J){T0($,!0),rZ($);let Z=J??P4($),Q=new R4(g($));try{Z.deleteBinding(),Z.deleteKey(),Z.createFreshPublicKey()}catch(X){if(X instanceof G0)return Q;throw X}return Q.deleteBinding(),Q.deleteKey(),Z}function P4($){return new e1(T2(),sZ(),iZ($))}function iZ($){let J=I4($);return lZ("sha256").update(`reason-worker
|
|
6
6
|
${J?.directory??g($)}`).digest("hex")}function S$($,J){c(f0(g($),w$),{version:1,directory:I4($)?.directory??g($),devicePublicKey:J})}var w$="keychain-scope.json";function h9($){return u(f0(g($),w$))}var nZ=G.strictObject({version:G.literal(1),directory:G.string().min(1),devicePublicKey:G.string().min(1)});function I4($){let J=f0(g($),w$);if(!u(J))return null;let Z=nZ.safeParse(JSON.parse(s(J))),Q=d($).state;if(!Z.success||!u(Q))return null;return JSON.parse(s(Q))?.devicePublicKey===Z.data.devicePublicKey?Z.data:null}function rZ($){let J=f0(g($),w$);if(!u(J))return;if(I4($))try{let Z=P4($);Z.deleteBinding(),Z.deleteKey()}catch(Z){if(!(Z instanceof G0))throw Z}_2(J)}function q1($){let J=pZ($.workspaceRoot);if(J!==$.workspaceRoot||!cZ(J).isDirectory()||!E$(J,$.stateDirectory))throw Error("worker_workspace_not_canonical_or_overlaps_state")}function t($){if(!u(g($)))return null;let J=h1(d($).state,{proofStore:T0($),repair:!1}),Z=J!==null&&y9($.apiOrigin,J.apiOrigin),Q=Z?[U0($),U0({...$,apiOrigin:J.apiOrigin})]:[U0($)];if(J&&(!Q.includes(J.worker?.configDigest??"")||J.worker.lifetime!==$.lifetime||J.apiOrigin!==$.apiOrigin&&!Z||J.roots.length>32||J.roots[0]?.path!==$.workspaceRoot||J.handsSlots!==$.slots))throw Error("worker_config_binding_mismatch");return J}var m9=G.strictObject({version:G.literal(1),drained:G.boolean(),revoked:G.boolean()});function $0($){let J=d($).control;return u(J)?m9.parse(JSON.parse(s(J))):{version:1,drained:!1,revoked:!1}}function E0($,J){c(d($).control,m9.parse(J))}function h0($){let J=T0($);J.deleteBinding(),J.deleteKey();let Z=f0(g($),w$);if(u(Z))_2(Z);let Q=d($).state;if(u(Q))_2(Q)}var tZ=G.strictObject({read:G.boolean(),write:G.boolean(),execute:G.boolean(),discover_environment:G.boolean(),expose_mcp:G.literal(!1)}),x4=G.strictObject({version:G.literal(1),organization_id:G.string().min(1).max(160),enrollment_ticket:G.string().min(1).max(4096),code_verifier:G.string().regex(/^[A-Za-z0-9._~-]{43,128}$/),root_fingerprint_key:G.string().regex(/^[a-f0-9]{64}$/),root:G.strictObject({path_fingerprint:G.string().regex(/^[a-f0-9]{64}$/),permissions:tZ,execution_mode:G.enum(["confined","host"]).default("confined")}),folders:G.array(G.strictObject({path_fingerprint:G.string().regex(/^[a-f0-9]{64}$/)})).min(1).max(31).optional()}),oZ=G.object({device_id:G.string().min(1).max(160),organization_id:G.string().min(1).max(160),auth_scheme:G.literal("p256"),protocol_version:G.literal(2),roots:G.array(G.object({id:G.string().min(1),label:G.string(),path_fingerprint:G.string()})).min(1).max(32),headless:G.object({lifecycle:G.enum(["persistent","ephemeral"]),expires_at:G.iso.datetime({offset:!0})}),first_heartbeat:G.unknown().optional()}),E4=30000;class J1 extends Error{deviceRemoved;constructor($){super("worker_enrollment_rejected");this.deviceRemoved=$}}async function eZ($,J,Z=fetch){let Q=await Z(`${$}/app/local-runtime/enroll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J),redirect:"error",signal:AbortSignal.timeout(E4)});if(!Q.ok){let X=Q.status===409?await Q.json().catch(()=>null):null;throw new J1(X?.error==="device_revoked")}return Q.json()}async function S4($,J,Z,Q){d0();let X=x4.parse(JSON.parse(s(J)));return Z1($,X,Z,Q)}async function Z1($,J,Z,Q=(Y,B)=>eZ(Y,B,y0($.proxy)),X=performance.now()){let Y=g9($,J,Z),B=await Q($.apiOrigin,{...Y.request,enrollment_ticket:J.enrollment_ticket,code_verifier:J.code_verifier});return Y.receipt(B,X)}async function v9($,J,Z,Q,X=performance.now()){let Y=g9($,J,Z),B=await Q(Y.request,J.code_verifier);return B===null?null:Y.receipt(B,X)}function g9($,J,Z){if(d0(),J.root.execution_mode!==$.executionMode)throw Error("worker_enrollment_mode_mismatch");let Q=m1([$.workspaceRoot],J.root.permissions,Buffer.from(J.root_fingerprint_key,"hex"))[0];if(Q.path!==$.workspaceRoot||Q.pathFingerprint!==J.root.path_fingerprint)throw Error("worker_enrollment_root_mismatch");let X=($.folders??[]).map((K,N)=>{let q=m1([K],J.root.permissions,Buffer.from(J.root_fingerprint_key,"hex"))[0];if(q.path!==K||q.pathFingerprint!==J.folders?.[N]?.path_fingerprint)throw Error("worker_enrollment_root_mismatch");return q});if((J.folders?.length??0)!==X.length)throw Error("worker_enrollment_root_mismatch");let Y=[{...Q,label:"workspace"},...X],B;try{B=Z.loadPublicKey()}catch{B=Z.createFreshPublicKey()}return{request:{device_public_key:B,name:$.name,os:process.platform,architecture:process.arch,reason_runtime_version:r,bridge_version:r,protocol_version:2,capabilities:{supported_operations:[]},roots:Y.map((K)=>({label:K.label,path_fingerprint:K.pathFingerprint,permissions:J.root.permissions}))},receipt(K,N){let q=oZ.parse(K);if(q.organization_id!==J.organization_id||q.roots.length!==Y.length||q.roots.some((U,M)=>U.path_fingerprint!==Y[M].pathFingerprint)||q.headless.lifecycle!==$.lifetime||Date.parse(q.headless.expires_at)<=Date.now())throw Error("worker_enrollment_receipt_mismatch");let H=F2(q.first_heartbeat);try{f9($,q.device_id,{...H?{offer:H}:{},enrollmentMs:Math.min($$,Math.max(0,Math.round(performance.now()-N)))})}catch{}return{version:4,apiOrigin:$.apiOrigin,orgId:q.organization_id,deviceId:q.device_id,devicePublicKey:B,displayName:$.name,registeredAt:new Date().toISOString(),handsSlots:$.slots,worker:{configDigest:U0($),lifetime:$.lifetime,expiresAt:q.headless.expires_at},roots:q.roots.map((U,M)=>({id:U.id,label:U.label,path:Y[M].path,pathFingerprint:U.path_fingerprint,permissions:J.root.permissions}))}}}}import{randomBytes as $Q,randomUUID as JQ}from"crypto";import{unlinkSync as ZQ}from"fs";import{join as QQ}from"path";var u9=G.strictObject({version:G.literal(1),install_id:G.uuid(),fingerprint_key:G.string().regex(/^[a-f0-9]{64}$/)}),XQ=G.object({enrollment_ticket:G.string().min(1).max(4096),expires_at:G.iso.datetime({offset:!0}),device_kind:G.literal("headless"),lifecycle:G.enum(["persistent","ephemeral"]),device_expires_at:G.iso.datetime({offset:!0})});function w4($){return XQ.parse($)}var YQ=G.object({credentialKind:G.enum(["oauth","api_key"]).optional(),apiOrigin:G.url(),clientId:G.string(),accessToken:G.string().min(1).max(32768),refreshToken:G.string().max(32768),expiresAt:G.iso.datetime({offset:!0}),scopes:G.array(G.string().max(128)).max(128),orgId:G.string().min(1).max(160)});function O1($){return $1(k$("REASON_CLI_CHANNEL",$.channel),V0())}async function A1($,J=O1($)){if(!u(J))return null;let Z=YQ.parse(JSON.parse(s(J)));if(!z0(Z.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(Z.credentialKind==="api_key")return Date.parse(Z.expiresAt)>Date.now()?Z:null;let Q=y0($.proxy),X=Object.assign((B,V)=>Q(B,{...V,redirect:"error",signal:AbortSignal.timeout(30000)}),{preconnect:fetch.preconnect}),Y=await k1({path:J,fetchImpl:X});if(Y&&!z0(Y.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");return Y}async function d9($,J,Z){if(!z0(J.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(!J.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let Q=R1($);return Q.complete(J.orgId,await Z.createHeadlessDeviceEnrollmentTicket(Q.request))}async function l9($,J,Z,Q,X){let Y=performance.now();if(!z0(J.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(!J.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let B=R1($),V=X?void 0:Z.enrollHeadlessDevice?.bind(Z);if(V){let K=await v9($,B.direct(J.orgId),Q,(N,q)=>V({approval:B.request,code_verifier:q,registration:N}).catch((H)=>{throw GQ(H)}),Y);if(K)return K}return Z1($,B.complete(J.orgId,await Z.createHeadlessDeviceEnrollmentTicket(B.request)),Q,X,Y)}function GQ($){if(!($ instanceof Y0))return $;if($.status===409)return new J1($.code==="device_revoked");if($.status===410||$.status===401&&$.code==="invalid_enrollment_ticket"||$.status===403&&$.code==="grant_exceeded"||$.status===400&&$.code==="invalid_device_enrollment")return new J1(!1);return $}var b$=($)=>QQ(g($),"enrollment-install.json");function p9($){if(u(b$($)))ZQ(b$($))}function R1($,{stored:J=!0}={}){d0();let Z=b$($),Q=J&&u(Z)?u9.parse(JSON.parse(s(Z))):{version:1,install_id:JQ(),fingerprint_key:$Q(32).toString("hex")};if(J&&!u(Z))c(Z,Q);let X={read:!0,write:!0,execute:!0,discover_environment:!0,expose_mcp:!1},Y=Buffer.from(Q.fingerprint_key,"hex"),B=m1([$.workspaceRoot],X,Y)[0];if(B.path!==$.workspaceRoot)throw Error("worker_workspace_not_canonical_or_overlaps_state");let V=($.folders??[]).map((H)=>{let U=m1([H],X,Y)[0];if(U.path!==H)throw Error("worker_workspace_not_canonical_or_overlaps_state");return{path_fingerprint:U.pathFingerprint}}),K=A9(),N={install_id:Q.install_id,code_challenge:K.challenge,lifecycle:$.lifetime,roots:[B.pathFingerprint,...V.map((H)=>H.path_fingerprint)].map((H)=>({path_fingerprint:H,permissions:X,execution_mode:$.executionMode}))},q=(H)=>({version:1,organization_id:H,code_verifier:K.verifier,root_fingerprint_key:Q.fingerprint_key,root:{path_fingerprint:B.pathFingerprint,permissions:X,execution_mode:$.executionMode},...V.length?{folders:V}:{}});return{request:N,saveInstall(H){e(g(H),!0),c(b$(H),Q)},complete(H,U){let M=w4(U);if(M.lifecycle!==$.lifetime||Date.parse(M.expires_at)<=Date.now()||Date.parse(M.device_expires_at)<=Date.now())throw Error("worker_ticket_receipt_mismatch");return{...q(H),enrollment_ticket:M.enrollment_ticket}},direct:q}}function c9($,J,Z){let Q=b$($);if(!u(Q))throw Error("worker_folders_unavailable");let X=u9.parse(JSON.parse(s(Q)));return m1([J],Z,Buffer.from(X.fingerprint_key,"hex"))[0]}var L2=8,i9=600000,n9=15000,s9=new Set(["device_revoked","invalid_device_credential"]),D2=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,M1=($)=>M0(g($),"workspaces"),r9="account.json",b4=($)=>u(M0($,r9));function m0($){let J;try{J=BQ(M1($))}catch{return[]}return J.filter((Z)=>D2.test(Z)).sort().map((Z)=>{let Q=M0(M1($),Z),X=M0(Q,"worker.json"),Y=null;try{let B=J0.safeParse(JSON.parse(s(X)));if(B.success&&B.data.stateDirectory===Q)Y=B.data}catch{}return{organizationId:Z,directory:Q,configPath:X,config:Y,account:b4(Q)}})}function j2($,J){let Z=J.toLowerCase();if(!D2.test(Z))throw Error("worker_workspace_id_invalid");let Q=J0.parse({...$,stateDirectory:M0(M1($),Z)});return e(Q.stateDirectory,!0),c(M0(Q.stateDirectory,r9),{version:1}),{config:Q,configPath:M0(Q.stateDirectory,"worker.json")}}function z2($,J){try{let{config:Z,configPath:Q}=j2($,J);e(g(Z),!0),E0(Z,{version:1,drained:!0,revoked:!0}),c(Q,Z)}catch{}}function f$($,J){let Z=J.toLowerCase(),Q=null;try{Q=t($)?.orgId.toLowerCase()??null}catch{}return Q===Z||m0($).some((X)=>!X.account&&X.config!==null&&X.organizationId===Z)}var k4=["device.json","local-device.key","local-device.binding","keychain-scope.json","control.json","enrollment-install.json","first-heartbeat.json"];function a9($,J){let Z=t($);if(!Z?.worker)throw Error("worker_identity_missing");S$($,Z.devicePublicKey),e(g(J),!0);for(let Y of k4)v1(M0(g(J),Y),{force:!0});for(let Y of k4){let B=M0(g($),Y);if(u(B))KQ(B,M0(g(J),Y))}let Q=T0(J),X=h1(d(J).state,{proofStore:Q,repair:!1});if(!X?.worker)throw Error("worker_identity_missing");v0({...X,worker:{...X.worker,configDigest:U0(J)}},d(J).state,{proofStore:Q})}function y4($){for(let J of m0($)){if(J.account)continue;try{if(J.config&&u(d(J.config).state))h0(J.config)}catch{}v1(J.directory,{recursive:!0,force:!0})}v1(h4($),{force:!0})}function O2($,{prefer:J,keep:Z,live:Q=!1}){let X=Date.now(),Y=(H)=>Number(Date.parse(H.worker?.expiresAt??"")>X+60000),V=m0($).flatMap((H)=>{if(!H.account||!H.config)return[];try{if($0(H.config).revoked)return[];let U=t(H.config);return U&&U.orgId.toLowerCase()===H.organizationId&&(!Q||Y(U))?[{...H,config:H.config,state:U}]:[]}catch{return[]}}).sort((H,U)=>Number(U.organizationId===J)-Number(H.organizationId===J)||Y(U.state)-Y(H.state))[0];if(!V)return null;let K=null;try{K=$0($).revoked?null:t($)}catch{}let N=K?.orgId.toLowerCase()??"";if(Z&&K&&D2.test(N)&&N!==V.organizationId){let H=j2($,N);a9($,H.config),c(H.configPath,H.config)}else if(u(g($))){try{if(u(d($).state))h0($)}catch{}for(let H of k4)v1(M0(g($),H),{force:!0})}y4($);let q=J0.parse({...V.config,stateDirectory:$.stateDirectory});return a9(V.config,q),c(M0($.stateDirectory,"worker.json"),q),v1(V.directory,{recursive:!0,force:!0}),q}var f4={before($){for(let{config:J}of m0($))try{let Z=J?t(J):null;if(J&&Z)S$(J,Z.devicePublicKey)}catch{}},after($,J){for(let{organizationId:Z,directory:Q,configPath:X,config:Y}of m0(J)){if(Y)continue;try{let B=J0.parse(JSON.parse(s(X)));if(B.stateDirectory!==M0(M1($),Z))continue;let V=J0.parse({...B,stateDirectory:Q}),K=T0(V),N=h1(d(V).state,{proofStore:K,repair:!1});if(N?.worker?.configDigest===U0(B))v0({...N,worker:{...N.worker,configDigest:U0(V)}},d(V).state,{proofStore:K});c(X,V)}catch{}}}},h4=($)=>M0(M1($),"listed.json");function t9($){try{let J=JSON.parse(s(h4($))),Z=J.names&&typeof J.names==="object"&&!Array.isArray(J.names)?Object.fromEntries(Object.entries(J.names).filter((Q)=>typeof Q[1]==="string")):{};return{listed:J.listed===!0,reason:J.reason==="sign_in"?"sign_in":null,blocked:Array.isArray(J.blocked)?J.blocked.filter((Q)=>typeof Q==="string"):[],names:Z}}catch{return null}}function o9($,J){let Z=m0($),Q=Z.filter((K)=>K.account),X=Z.filter((K)=>!K.account),Y=t9($),B=Y&&!Y.listed?Y.reason:null,V=B||X.length===0&&Y&&!Y.listed?[]:X;if(Q.length===0&&V.length===0&&(B||Y&&!Y.listed))return{workspaces:null,off:B};return{off:B,workspaces:[...Q,...V].map(({organizationId:K,config:N,account:q})=>{let H=!1,U=null,M=!1;try{H=N?$0(N).revoked:!1,U=N&&!H?t(N):null,M=J&&!!U&&y$(d(N).daemon)?.state==="connected"}catch{}return{organization_id:K,device_id:U?.deviceId??null,name:Y?.names?.[K]??null,root:U?.roots[0]?{id:U.roots[0].id,permissions:U.roots[0].permissions}:null,state:H?"removed":M?"connected":"not_running",blocked:!q&&!H&&!M&&(Y?.blocked.includes(K)??!1),...q?{account:!0}:{}}})}}function e9($){let{config:J,state:Z,client:Q,signal:X}=$,Y=$.log??(()=>{return}),B=new Map,V=null,K=!1,N=t9(J)??{listed:!1,reason:null,blocked:[]},q=(W)=>{let{folders:L,...R}=J,x=Z.roots.slice(1).map((C)=>C.path);return J0.parse({...R,...x.length?{folders:x}:{},stateDirectory:M0(M1(J),W)})},H=async(W)=>{let L=B.get(W);if(!L)return;L.controller.abort(),await L.done},U=(W,L=!1)=>{let R=new AbortController,x=()=>R.abort();if(X.addEventListener("abort",x,{once:!0}),X.aborted)R.abort();let C={...W,controller:R,claims:0,done:Promise.resolve(),account:L};C.done=$.serve(W,R.signal,(P)=>{C.claims=P}).then(()=>{return},(P)=>{if(L&&P instanceof _0&&P.status===401&&s9.has(P.code)){try{E0(W.config,{version:1,drained:!0,revoked:!0})}catch{}Y(`Reason worker: workspace ${W.organizationId} (another account's) no longer accepts this computer (${P.code}); run \`reason connect\` signed in as that account to connect it again
|
|
7
7
|
`)}else if(P instanceof _0&&P.status===401&&s9.has(P.code)){try{h0(W.config)}catch{}Y(`Reason worker: workspace ${W.organizationId} no longer accepts this computer
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$a as J7,Ea as i6,Ga as _4,Ha as R4,Ma as t6,Na as e6,Xa as z4,ab as Z7,bb as h4,cb as m4,eb as Q7,ga as C4,gb as Y8,hb as y0,ia as Y2,ib as m0,ja as H4,jb as r1,ka as D4,la as M4,ma as v6,mb as K7,na as u6,oa as A4,pa as d6,pb as F8,qa as T3,qb as E4,ra as l6,sa as s6,sb as B7,ta as c6,ua as n6,va as T4,wa as r6,xa as a6}from"./vm-hands-entry-lite-qg2q7w4z.js";import{Ab as r0,Bb as a0,Ib as P0,tb as Z4,ub as y6,vb as h6}from"./vm-hands-entry-lite-q8b738zj.js";import{Jb as V7,Mb as G7,Ob as U7,Pb as X7}from"./vm-hands-entry-lite-93ejmwqn.js";import{Ub as o6}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Vb as k6,Wb as f6,Xb as b6,Yb as x6,Zb as L0}from"./vm-hands-entry-lite-n07kxrd1.js";import{$b as e1,ac as $2,bc as b3,dc as x3,fc as y3,gc as h3,kc as m3,mc as S6}from"./vm-hands-entry-lite-b2wdaq7x.js";import{Fc as i1,Ic as A7,Rc as T7}from"./vm-hands-entry-lite-wmbe27q2.js";import{$d as f8,Ad as I6,Bd as A6,Cd as T6,Dd as _6,Ed as R6,Gd as P6,Hd as z6,Id as E6,Jd as q6,Kd as g6,Pd as A8,Qd as T8,Rd as _8,Sc as w1,Sd as R8,Tc as K2,Td as P8,Uc as V6,Ud as z8,Vc as A3,Wc as $4,Wd as E8,Xc as J4,Xd as q8,Yc as M0,Yd as g8,Zd as S8,_d as k8,ad as N0,ae as b8,be as x8,ce as y8,dd as d,de as h8,ed as g1,hd as I8,jd as S1,ld as G6,md as U6,nd as X6,od as W6,pd as Y6,qd as F6,rd as N6,sd as C6,td as H6,ud as D6,vd as M6,wd as L6,xd as w6,yd as O6,zd as j6}from"./vm-hands-entry-lite-t497ewn2.js";import{ee as V}from"./vm-hands-entry-lite-psybjyay.js";import{Ae as _7,De as Y5,Ee as c1,fe as L7,ge as w7,he as O7,ie as j7,je as I7,pe as r5,te as W5,ue as g5}from"./vm-hands-entry-lite-6fvcdr2b.js";import{bf as P4,if as $7}from"./vm-hands-entry-lite-wh0qp1gf.js";import{Af as m6,nf as L3}from"./vm-hands-entry-lite-yhz6sv35.js";import{Fg as W7,Gg as Y7,Hg as F7,Ig as N7,Kg as C7,Lg as H7,Ng as D7,Og as M7}from"./vm-hands-entry-lite-22jgncrd.js";import{ah as a1}from"./vm-hands-entry-lite-mzxhng4z.js";import{ch as I1,dh as p6,eh as j4,fh as I4}from"./vm-hands-entry-lite-cp1wqjs5.js";import{hh as M3,jh as J1,ph as W8,qh as G4}from"./vm-hands-entry-lite-ne8kkvk4.js";import{Oh as H}from"./vm-hands-entry-lite-v6tkjqb1.js";import{Uh as J8}from"./vm-hands-entry-lite-cxs89wzv.js";import{request as n7}from"http";import{request as r7}from"https";import{lookup as a7}from"dns/promises";import{isIP as i7}from"net";async function o7($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?r7:n7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:x3},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),K.end($.body)})}var v3=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),t7=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function p3($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(v3.has(Z))return"custom_endpoint_host_not_found";if(t7.has(Z))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let K=p3(Q,J+1);if(K)return K}return null}async function e7($,J){let Z=p3($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||i7(Q)!==0)return Z;let K;return await Promise.race([a7(Q).then(()=>!0,(G)=>!v3.has(String(G?.code))),new Promise((G)=>{K=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(K))?Z:"custom_endpoint_host_not_found"}function $9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function J9($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=K[U-1];if(Z[G]===Z[U])U++;K[G]=U}let B=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+B),Y=0;for(let X of G){while(B&&Z[B]!==X){let N=K[B-1];Y+=Z.copy(W,Y,0,B-N),B=N}if(Z[B]===X){if(B++,B===Z.length)Y+=Q.copy(W,Y),B=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,B),B=0;return W.subarray(0,Y)}}async function u3($){$.signal.throwIfAborted();let J=h3.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=m3.parse(await $.credential($.signal));if(!y3(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new H("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let K,B,G=0,U=0,W=0,Y=$9(Q.apiKey),X=J9(Q.apiKey,Y),N=async(F,D)=>{$.signal.throwIfAborted(),await new Promise((w,M)=>{let j=()=>{$.signal.removeEventListener("abort",j),M($.signal.reason)};if($.signal.addEventListener("abort",j,{once:!0}),$.signal.aborted){j();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(F,D)}).then(()=>{$.signal.removeEventListener("abort",j),w()},(O)=>{$.signal.removeEventListener("abort",j),M(O)})})},C=async(F)=>{if(G+=F.length,G>$2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<F.length;D+=e1){if(W>=b3)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await N(`custom_endpoint.chunk.${W++}`,{eof:!1,data:F.subarray(D,D+e1).toString("base64")})}};try{let F=await o7({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=F.response,B=F.close;let D=K.statusCode??500;if(D>=300&&D<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let w={};for(let M of["content-type","retry-after","x-request-id","request-id"]){let j=K.headers[M];if(typeof j==="string")w[M]=j.replaceAll(Q.apiKey,Y).slice(0,4096)}await N("custom_endpoint.headers",{status:D,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:w});for await(let M of K){$.signal.throwIfAborted();let j=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=j.length,U>$2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await C(X(j))}return await C(X(Buffer.alloc(0),!0)),await N(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(F){if($.signal.throwIfAborted(),F instanceof H)throw F;throw new H((K?null:await e7(F,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as d3}from"path";function Z9($,J){return $===d3(J,".ara","workspace")||$===d3(J,".reason","workspace")}function l3($,J){let Z=$.filter((Q)=>Z9(Q.path,J));return Z.length===1?Z[0].path:null}var Q9=/^[a-f0-9]{64}$/;var J2=32,K9=/^\/[^\x00-\x1f\x7f\\]*$/;function D1($){if(typeof $!=="string"||$.length>4096||!K9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function M1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!D1(J.home)||!Array.isArray(J.roots)||J.roots.length>J2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:K,path:B}=Q;if(typeof K!=="string"||!Q9.test(K)||!D1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}import{spawn as V9}from"child_process";import*as q from"fs";import*as r from"path";import{homedir as G9}from"os";function s3($,J,Z,Q="gh"){if(!["gh","git"].includes(Q))throw Error("local_device_gh_unavailable");let K=$.realpathSync(Z),B=Q==="git"&&process.platform==="darwin"?"/Library/Developer/CommandLineTools/usr/bin/git":"/usr/bin/"+Q;for(let G of["/opt/homebrew/bin/"+Q,"/usr/local/bin/"+Q,B])try{let U=$.realpathSync(G);if(U===K||U.startsWith(K+J.sep)||!["/opt/homebrew/","/usr/local/","/usr/bin/",...Q==="git"?["/Library/Developer/CommandLineTools/"]:[]].some((Y)=>U.startsWith(Y)))continue;let W=$.statSync(U);if(!W.isFile()||(W.mode&18)!==0||![0,process.getuid()].includes(W.uid))continue;return $.accessSync(U,$.constants.X_OK),U}catch{continue}throw Error("local_device_gh_unavailable")}function c3($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var n3=[{name:"private_key",regex:/-----BEGIN\s+(?:[A-Z0-9_-]+\s+)?PRIVATE\s+KEY-----/i},{name:"github_pat",regex:/\bgh[pousr]_[A-Za-z0-9_]{36,}\b/},{name:"github_fine_grained_pat",regex:/\bgithub_pat_[A-Za-z0-9_]{36,}\b/},{name:"gitlab_pat",regex:/\bglpat-[0-9a-zA-Z_-]{20,}\b/},{name:"slack_token",regex:/\bxox[baprs]-[0-9]{10,}-[0-9]{10,}-[0-9a-zA-Z]{24}\b/},{name:"stripe_live_key",regex:/\b[sr]k_live_[0-9a-zA-Z]{24,}\b/},{name:"bearer_jwt",regex:/\bBearer\s+ey[A-Za-z0-9_-]{20,}\.ey[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/}];function Z2($){let J=$.trim().replaceAll("\\","/");if(!J)return{valid:!1,reason:"empty_path"};if(J.startsWith("/"))return{valid:!1,reason:"absolute_path_forbidden"};if(J.split("/").includes("..")||J.includes("../")||J.endsWith("/.."))return{valid:!1,reason:"path_traversal_forbidden"};if(J===".git"||J.startsWith(".git/")||J.includes("/.git/"))return{valid:!1,reason:"git_directory_entry_forbidden"};return{valid:!0}}function r3($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function a3($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function L1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=r3(J).filter((G)=>!K.has(G));for(let G of $){let U=Z2(G.path);if(!U.valid){Q.push({path:G.path,reason:U.reason??"invalid_path"});continue}let W=G.content??"",Y=B.map((X)=>({secret:X,offset:W.indexOf(X)})).filter((X)=>X.offset>=0).sort((X,N)=>X.offset-N.offset);if(Y.length>0){let X=[...new Set(Y.flatMap((N)=>Z.secretNames?.(N.secret)??[]))];Q.push({path:G.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:c3(W,Y[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of n3){let N=a3(X,W).find((C)=>!K.has(C[0]));if(N){Q.push({path:G.path,reason:`credential_pattern_detected: ${X.name}`,pattern:X.name,ruleId:X.name,line:c3(W,N.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function i3($,J=[]){let Z=r3(J),Q=new Set;for(let{content:K}of $){for(let B of Z)if(K.includes(B))Q.add(B);for(let B of n3)for(let G of a3(B,K))Q.add(G[0])}return[...Q]}function B9($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function o3($,J,Z){let Q=(K,B)=>K.reduce((G,U)=>G+B9(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var T0=4194304,t3=536870912,Q2=/^[a-f0-9]{40}$/,U9=($,J,Z)=>new Promise((Q)=>{if(Z.signal?.aborted){Q({status:null,error:Error("cancelled"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let K;try{K=V9($,J,{cwd:Z.cwd,env:Z.env,detached:!0,stdio:["pipe","pipe","pipe"]})}catch{Q({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let B=Buffer.alloc(0),G=Buffer.alloc(0),U,W=!1,Y=(F)=>{if(U??=Error(F),K.pid)try{process.kill(-K.pid,"SIGKILL")}catch{}},X=()=>Y("cancelled"),N=setTimeout(()=>Y("timeout"),Z.timeout);Z.signal?.addEventListener("abort",X,{once:!0});let C=(F)=>{if(W)return;W=!0,clearTimeout(N),Z.signal?.removeEventListener("abort",X),Q({status:F,stdout:B,stderr:G,...U?{error:U}:{}})};if(K.stdout.on("data",(F)=>{if(B.length+G.length+F.length>Z.maxBuffer)Y("output_limit");else B=Buffer.concat([B,F])}),K.stderr.on("data",(F)=>{if(B.length+G.length+F.length>Z.maxBuffer)Y("output_limit");else G=Buffer.concat([G,F])}),K.on("error",()=>{if(Y("spawn_failed"),!K.pid)C(null)}),K.on("close",(F)=>C(F)),K.stdin.on("error",()=>Y("input_failed")),K.stdin.end(Z.input),Z.signal?.aborted)X()}),X9={command:U9,gh:($,J)=>s3(q,r,$,J),home:G9};function A($){throw Error($)}function W9($,J){let Z=(K)=>K.trim().replace(/^co-authored-by:\s*/i,"Co-authored-by: "),Q=new Set($.split(/\r?\n/).map(Z));return[...new Set(J)].filter((K)=>!Q.has(Z(K)))}var Y9=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),F9=($)=>JSON.stringify($,(J,Z)=>Y9.has(J)?void 0:Z);function e3($,J,Z){let Q=[...new Set($.map((B)=>`${J(B.path)}${B.line?`:${B.line}`:""} (${B.reason==="literal_secret_detected"?`value of ${B.secretNames?.length?B.secretNames.slice(0,3).join(", "):"a session variable"}`:`${B.ruleId??"credential"} credential`})`))].slice(0,10),K=$.some((B)=>B.reason==="literal_secret_detected");A(`local_device_gh_secret_scan_failed: the change adds text matching a secret that the base does not already contain: ${Q.join("; ")}. Nothing was sent. ${Z}${K?" If the line is ordinary code, that variable's value is too generic to tell apart from code: tell the person which variable matched so they can change its value.":""}`)}async function Q4($,J,Z=X9){let Q=w1.parse($);if(!["darwin","linux"].includes(process.platform))A("local_device_gh_platform_unavailable");J.assertCurrent();let K=q.realpathSync(J.root);if(K==="/")A("local_device_gh_root_unavailable");if(!M0(Q)&&!J.forbiddenSecretValues)A("local_device_gh_secret_scope_unavailable");if(!M0(Q)&&J.readOnly)A("local_device_gh_read_only");if(!M0(Q)){let L=L1([{path:"github-operation",content:F9(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!L.clean)e3(L.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let B=Z.gh(K),G=Z.home(),U=Z.gh(K,"git"),W=J.privateDirectory?q.realpathSync(J.privateDirectory):q.realpathSync(G);if(!M0(Q)&&(!J.privateDirectory||W===K||W.startsWith(K+r.sep)))A("local_device_gh_private_scope_unavailable");let Y={PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:G,GH_CONFIG_DIR:r.join(G,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:"/bin/cat",GH_HOST:"github.com",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1",...process.platform==="linux"?Object.fromEntries(["DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR"].flatMap((L)=>process.env[L]?[[L,process.env[L]]]:[])):{}},X=async(L,T,P=W,k,x=T0)=>{J.assertCurrent();let y=await Z.command(L,T,{cwd:P,env:Y,input:k,maxBuffer:x,timeout:Math.max(1,Math.min(60000,(J.deadlineMs??Date.now()+60000)-Date.now())),signal:J.signal});if(J.assertCurrent(),y.error||y.status!==0)A("local_device_gh_command_failed");return y.stdout},N=async(L)=>(await X(B,L)).toString("utf8").trim(),C=async(L,T="application/vnd.github+json")=>{$4(Q.repoFullName,L,{headers:{accept:T}}),J.assertCurrent();let P=await Z.command(B,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${T}`,L],{cwd:W,env:Y,maxBuffer:T0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),P.error&&P.status===null)A("local_device_gh_response_unavailable");let k=P.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!k)A("local_device_gh_response_invalid");let x=Number(k[1]);if(x>=200&&x<300&&P.status!==0)A("local_device_gh_response_unavailable");if(Buffer.byteLength(k[3])>K2)A("local_device_gh_response_too_large");let y={};for(let i of k[2].split(/\r?\n/)){let e=i.indexOf(":"),D0=i.slice(0,e).toLowerCase();if(["link","content-type"].includes(D0))y[D0]=i.slice(e+1).trim().slice(0,8192)}return{kind:"read",status:x,headers:y,body:x>=200&&x<300?k[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return C(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[L,T]=Q.repoFullName.split("/"),P=await N(["api","graphql","--hostname","github.com","-f",`query=${J4}`,"-f",`owner=${L}`,"-f",`repo=${T}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(P)>K2)A("local_device_gh_response_too_large");let k=JSON.parse(P);if(k.errors||k.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||k.data.repository.pullRequest?.number!==Q.number)A("local_device_gh_response_invalid");return{kind:"pr_review_context",body:P}}if(Q.kind==="pr_merge"){let L=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),T=JSON.parse(L.body),P=(y)=>y.number===Q.number&&y.html_url===`https://github.com/${Q.repoFullName}/pull/${Q.number}`&&y.base?.repo?.full_name?.toLowerCase()===Q.repoFullName.toLowerCase()&&y.base?.ref===Q.expectedBaseRef&&y.head?.sha===Q.expectedHeadSha;if(L.status!==200||!P(T)||T.state!=="open"||T.draft!==!1||T.head?.sha!==Q.expectedHeadSha||T.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())A("local_device_gh_merge_target_changed");await N(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha,...Q.commitBody!==void 0&&Q.method!=="rebase"?[`--body=${Q.commitBody}`]:[]]);let k=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),x=JSON.parse(k.body);if(k.status!==200||!P(x)||x.merged!==!0)A("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:Q.number,merged:!0}}if(Q.kind==="pr_create"){if(Q.head===Q.base)A("local_device_gh_default_branch");let L=await N(["pr","create","--repo",Q.repoFullName,"--head",Q.head,"--base",Q.base,`--title=${Q.title}`,`--body=${Q.body}`,...Q.draft?["--draft"]:[]]);if(!new RegExp("^https://github\\.com/"+Q.repoFullName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/pull/[1-9][0-9]*$").test(L))A("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:L}}if(Q.kind==="pr_mutation"){let L=Q.mutation,T=L.action==="edit"?["edit",...L.title!==void 0?[`--title=${L.title}`]:[],...L.body!==void 0?[`--body=${L.body}`]:[],...L.base?[`--base=${L.base}`]:[]]:L.action==="metadata"?["edit",`--${L.change}-${L.field}=${L.value}`]:L.action==="ready"?["ready"]:L.action==="draft"?["ready","--undo"]:["close"];return await N(["pr",...T,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)A("local_device_gh_workspace_unavailable");let F=q.realpathSync(J.repoPath);if(F!==K&&!F.startsWith(K+r.sep))A("local_device_gh_workspace_unavailable");let D=`https://github.com/${Q.repoFullName}.git`,w="!'"+B.replace(/'/g,"'\\''")+"' auth git-credential",M=Function("return ("+Z4+")")(),j=(L,T,P)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",L,T,...P]]:[T,P],O=async(L,T,P,k=T0)=>{let x=L===W||L.startsWith(W+r.sep),y=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...x?["-c",`credential.https://github.com.helper=${w}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",...T];if(x)return X(U,y,L,P,k);let i=r.join(F,".ara-local-gh-tmp");if(q.mkdirSync(i,{recursive:!0,mode:448}),q.lstatSync(i).isSymbolicLink()||q.realpathSync(i)!==i)A("local_device_gh_workspace_unavailable");J.assertCurrent();let e=await Z.command(...j(M(F,i),U,y),{cwd:L,input:P,maxBuffer:k,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:F,TMPDIR:i,GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1"}});if(J.assertCurrent(),e.error||e.status!==0)A("local_device_gh_collection_failed");return e.stdout},R=async(L,T)=>(await O(L,T)).toString("utf8").trim(),g=async(L,T)=>{let P=r.join(L,".ara-local-gh-tmp");if(q.mkdirSync(P,{recursive:!0,mode:448}),q.lstatSync(P).isSymbolicLink()||q.realpathSync(P)!==P)A("local_device_gh_workspace_unavailable");J.assertCurrent();let k=await Z.command(...j(M(L,P),"/bin/sh",["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",T]),{cwd:L,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:L,TMPDIR:P}});if(J.assertCurrent(),k.error||k.status!==0)A("local_device_gh_materialization_failed")},v=async(L)=>{let T=new Map;if(L.length===0)return T;let P=await O(E,["cat-file","--batch"],[...new Set(L)].join(`
|
|
2
|
+
import{$a as J7,Ea as i6,Ga as _4,Ha as R4,Ma as t6,Na as e6,Xa as z4,ab as Z7,bb as h4,cb as m4,eb as Q7,ga as C4,gb as Y8,hb as y0,ia as Y2,ib as m0,ja as H4,jb as r1,ka as D4,la as M4,ma as v6,mb as K7,na as u6,oa as A4,pa as d6,pb as F8,qa as T3,qb as E4,ra as l6,sa as s6,sb as B7,ta as c6,ua as n6,va as T4,wa as r6,xa as a6}from"./vm-hands-entry-lite-gycydjw0.js";import{Ab as r0,Bb as a0,Ib as P0,tb as Z4,ub as y6,vb as h6}from"./vm-hands-entry-lite-q8b738zj.js";import{Jb as V7,Mb as G7,Ob as U7,Pb as X7}from"./vm-hands-entry-lite-93ejmwqn.js";import{Ub as o6}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Vb as k6,Wb as f6,Xb as b6,Yb as x6,Zb as L0}from"./vm-hands-entry-lite-n07kxrd1.js";import{$b as e1,ac as $2,bc as b3,dc as x3,fc as y3,gc as h3,kc as m3,mc as S6}from"./vm-hands-entry-lite-b2wdaq7x.js";import{Fc as i1,Ic as A7,Rc as T7}from"./vm-hands-entry-lite-b92849ds.js";import{$d as f8,Ad as I6,Bd as A6,Cd as T6,Dd as _6,Ed as R6,Gd as P6,Hd as z6,Id as E6,Jd as q6,Kd as g6,Pd as A8,Qd as T8,Rd as _8,Sc as w1,Sd as R8,Tc as K2,Td as P8,Uc as V6,Ud as z8,Vc as A3,Wc as $4,Wd as E8,Xc as J4,Xd as q8,Yc as M0,Yd as g8,Zd as S8,_d as k8,ad as N0,ae as b8,be as x8,ce as y8,dd as d,de as h8,ed as g1,hd as I8,jd as S1,ld as G6,md as U6,nd as X6,od as W6,pd as Y6,qd as F6,rd as N6,sd as C6,td as H6,ud as D6,vd as M6,wd as L6,xd as w6,yd as O6,zd as j6}from"./vm-hands-entry-lite-t497ewn2.js";import{ee as V}from"./vm-hands-entry-lite-psybjyay.js";import{Ae as _7,De as Y5,Ee as c1,fe as L7,ge as w7,he as O7,ie as j7,je as I7,pe as r5,te as W5,ue as g5}from"./vm-hands-entry-lite-m1c4h4me.js";import{bf as P4,if as $7}from"./vm-hands-entry-lite-wh0qp1gf.js";import{Af as m6,nf as L3}from"./vm-hands-entry-lite-yhz6sv35.js";import{Fg as W7,Gg as Y7,Hg as F7,Ig as N7,Kg as C7,Lg as H7,Ng as D7,Og as M7}from"./vm-hands-entry-lite-22jgncrd.js";import{ah as a1}from"./vm-hands-entry-lite-mzxhng4z.js";import{ch as I1,dh as p6,eh as j4,fh as I4}from"./vm-hands-entry-lite-cp1wqjs5.js";import{hh as M3,jh as J1,ph as W8,qh as G4}from"./vm-hands-entry-lite-ne8kkvk4.js";import{Oh as H}from"./vm-hands-entry-lite-v6tkjqb1.js";import{Uh as J8}from"./vm-hands-entry-lite-cxs89wzv.js";import{request as n7}from"http";import{request as r7}from"https";import{lookup as a7}from"dns/promises";import{isIP as i7}from"net";async function o7($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?r7:n7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:x3},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),K.end($.body)})}var v3=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),t7=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function p3($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(v3.has(Z))return"custom_endpoint_host_not_found";if(t7.has(Z))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let K=p3(Q,J+1);if(K)return K}return null}async function e7($,J){let Z=p3($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||i7(Q)!==0)return Z;let K;return await Promise.race([a7(Q).then(()=>!0,(G)=>!v3.has(String(G?.code))),new Promise((G)=>{K=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(K))?Z:"custom_endpoint_host_not_found"}function $9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function J9($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=K[U-1];if(Z[G]===Z[U])U++;K[G]=U}let B=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+B),Y=0;for(let X of G){while(B&&Z[B]!==X){let N=K[B-1];Y+=Z.copy(W,Y,0,B-N),B=N}if(Z[B]===X){if(B++,B===Z.length)Y+=Q.copy(W,Y),B=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,B),B=0;return W.subarray(0,Y)}}async function u3($){$.signal.throwIfAborted();let J=h3.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=m3.parse(await $.credential($.signal));if(!y3(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new H("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let K,B,G=0,U=0,W=0,Y=$9(Q.apiKey),X=J9(Q.apiKey,Y),N=async(F,D)=>{$.signal.throwIfAborted(),await new Promise((w,M)=>{let j=()=>{$.signal.removeEventListener("abort",j),M($.signal.reason)};if($.signal.addEventListener("abort",j,{once:!0}),$.signal.aborted){j();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(F,D)}).then(()=>{$.signal.removeEventListener("abort",j),w()},(O)=>{$.signal.removeEventListener("abort",j),M(O)})})},C=async(F)=>{if(G+=F.length,G>$2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<F.length;D+=e1){if(W>=b3)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await N(`custom_endpoint.chunk.${W++}`,{eof:!1,data:F.subarray(D,D+e1).toString("base64")})}};try{let F=await o7({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=F.response,B=F.close;let D=K.statusCode??500;if(D>=300&&D<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let w={};for(let M of["content-type","retry-after","x-request-id","request-id"]){let j=K.headers[M];if(typeof j==="string")w[M]=j.replaceAll(Q.apiKey,Y).slice(0,4096)}await N("custom_endpoint.headers",{status:D,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:w});for await(let M of K){$.signal.throwIfAborted();let j=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=j.length,U>$2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await C(X(j))}return await C(X(Buffer.alloc(0),!0)),await N(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(F){if($.signal.throwIfAborted(),F instanceof H)throw F;throw new H((K?null:await e7(F,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as d3}from"path";function Z9($,J){return $===d3(J,".ara","workspace")||$===d3(J,".reason","workspace")}function l3($,J){let Z=$.filter((Q)=>Z9(Q.path,J));return Z.length===1?Z[0].path:null}var Q9=/^[a-f0-9]{64}$/;var J2=32,K9=/^\/[^\x00-\x1f\x7f\\]*$/;function D1($){if(typeof $!=="string"||$.length>4096||!K9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function M1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!D1(J.home)||!Array.isArray(J.roots)||J.roots.length>J2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:K,path:B}=Q;if(typeof K!=="string"||!Q9.test(K)||!D1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}import{spawn as V9}from"child_process";import*as q from"fs";import*as r from"path";import{homedir as G9}from"os";function s3($,J,Z,Q="gh"){if(!["gh","git"].includes(Q))throw Error("local_device_gh_unavailable");let K=$.realpathSync(Z),B=Q==="git"&&process.platform==="darwin"?"/Library/Developer/CommandLineTools/usr/bin/git":"/usr/bin/"+Q;for(let G of["/opt/homebrew/bin/"+Q,"/usr/local/bin/"+Q,B])try{let U=$.realpathSync(G);if(U===K||U.startsWith(K+J.sep)||!["/opt/homebrew/","/usr/local/","/usr/bin/",...Q==="git"?["/Library/Developer/CommandLineTools/"]:[]].some((Y)=>U.startsWith(Y)))continue;let W=$.statSync(U);if(!W.isFile()||(W.mode&18)!==0||![0,process.getuid()].includes(W.uid))continue;return $.accessSync(U,$.constants.X_OK),U}catch{continue}throw Error("local_device_gh_unavailable")}function c3($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var n3=[{name:"private_key",regex:/-----BEGIN\s+(?:[A-Z0-9_-]+\s+)?PRIVATE\s+KEY-----/i},{name:"github_pat",regex:/\bgh[pousr]_[A-Za-z0-9_]{36,}\b/},{name:"github_fine_grained_pat",regex:/\bgithub_pat_[A-Za-z0-9_]{36,}\b/},{name:"gitlab_pat",regex:/\bglpat-[0-9a-zA-Z_-]{20,}\b/},{name:"slack_token",regex:/\bxox[baprs]-[0-9]{10,}-[0-9]{10,}-[0-9a-zA-Z]{24}\b/},{name:"stripe_live_key",regex:/\b[sr]k_live_[0-9a-zA-Z]{24,}\b/},{name:"bearer_jwt",regex:/\bBearer\s+ey[A-Za-z0-9_-]{20,}\.ey[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/}];function Z2($){let J=$.trim().replaceAll("\\","/");if(!J)return{valid:!1,reason:"empty_path"};if(J.startsWith("/"))return{valid:!1,reason:"absolute_path_forbidden"};if(J.split("/").includes("..")||J.includes("../")||J.endsWith("/.."))return{valid:!1,reason:"path_traversal_forbidden"};if(J===".git"||J.startsWith(".git/")||J.includes("/.git/"))return{valid:!1,reason:"git_directory_entry_forbidden"};return{valid:!0}}function r3($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function a3($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function L1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=r3(J).filter((G)=>!K.has(G));for(let G of $){let U=Z2(G.path);if(!U.valid){Q.push({path:G.path,reason:U.reason??"invalid_path"});continue}let W=G.content??"",Y=B.map((X)=>({secret:X,offset:W.indexOf(X)})).filter((X)=>X.offset>=0).sort((X,N)=>X.offset-N.offset);if(Y.length>0){let X=[...new Set(Y.flatMap((N)=>Z.secretNames?.(N.secret)??[]))];Q.push({path:G.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:c3(W,Y[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of n3){let N=a3(X,W).find((C)=>!K.has(C[0]));if(N){Q.push({path:G.path,reason:`credential_pattern_detected: ${X.name}`,pattern:X.name,ruleId:X.name,line:c3(W,N.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function i3($,J=[]){let Z=r3(J),Q=new Set;for(let{content:K}of $){for(let B of Z)if(K.includes(B))Q.add(B);for(let B of n3)for(let G of a3(B,K))Q.add(G[0])}return[...Q]}function B9($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function o3($,J,Z){let Q=(K,B)=>K.reduce((G,U)=>G+B9(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var T0=4194304,t3=536870912,Q2=/^[a-f0-9]{40}$/,U9=($,J,Z)=>new Promise((Q)=>{if(Z.signal?.aborted){Q({status:null,error:Error("cancelled"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let K;try{K=V9($,J,{cwd:Z.cwd,env:Z.env,detached:!0,stdio:["pipe","pipe","pipe"]})}catch{Q({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let B=Buffer.alloc(0),G=Buffer.alloc(0),U,W=!1,Y=(F)=>{if(U??=Error(F),K.pid)try{process.kill(-K.pid,"SIGKILL")}catch{}},X=()=>Y("cancelled"),N=setTimeout(()=>Y("timeout"),Z.timeout);Z.signal?.addEventListener("abort",X,{once:!0});let C=(F)=>{if(W)return;W=!0,clearTimeout(N),Z.signal?.removeEventListener("abort",X),Q({status:F,stdout:B,stderr:G,...U?{error:U}:{}})};if(K.stdout.on("data",(F)=>{if(B.length+G.length+F.length>Z.maxBuffer)Y("output_limit");else B=Buffer.concat([B,F])}),K.stderr.on("data",(F)=>{if(B.length+G.length+F.length>Z.maxBuffer)Y("output_limit");else G=Buffer.concat([G,F])}),K.on("error",()=>{if(Y("spawn_failed"),!K.pid)C(null)}),K.on("close",(F)=>C(F)),K.stdin.on("error",()=>Y("input_failed")),K.stdin.end(Z.input),Z.signal?.aborted)X()}),X9={command:U9,gh:($,J)=>s3(q,r,$,J),home:G9};function A($){throw Error($)}function W9($,J){let Z=(K)=>K.trim().replace(/^co-authored-by:\s*/i,"Co-authored-by: "),Q=new Set($.split(/\r?\n/).map(Z));return[...new Set(J)].filter((K)=>!Q.has(Z(K)))}var Y9=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),F9=($)=>JSON.stringify($,(J,Z)=>Y9.has(J)?void 0:Z);function e3($,J,Z){let Q=[...new Set($.map((B)=>`${J(B.path)}${B.line?`:${B.line}`:""} (${B.reason==="literal_secret_detected"?`value of ${B.secretNames?.length?B.secretNames.slice(0,3).join(", "):"a session variable"}`:`${B.ruleId??"credential"} credential`})`))].slice(0,10),K=$.some((B)=>B.reason==="literal_secret_detected");A(`local_device_gh_secret_scan_failed: the change adds text matching a secret that the base does not already contain: ${Q.join("; ")}. Nothing was sent. ${Z}${K?" If the line is ordinary code, that variable's value is too generic to tell apart from code: tell the person which variable matched so they can change its value.":""}`)}async function Q4($,J,Z=X9){let Q=w1.parse($);if(!["darwin","linux"].includes(process.platform))A("local_device_gh_platform_unavailable");J.assertCurrent();let K=q.realpathSync(J.root);if(K==="/")A("local_device_gh_root_unavailable");if(!M0(Q)&&!J.forbiddenSecretValues)A("local_device_gh_secret_scope_unavailable");if(!M0(Q)&&J.readOnly)A("local_device_gh_read_only");if(!M0(Q)){let L=L1([{path:"github-operation",content:F9(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!L.clean)e3(L.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let B=Z.gh(K),G=Z.home(),U=Z.gh(K,"git"),W=J.privateDirectory?q.realpathSync(J.privateDirectory):q.realpathSync(G);if(!M0(Q)&&(!J.privateDirectory||W===K||W.startsWith(K+r.sep)))A("local_device_gh_private_scope_unavailable");let Y={PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:G,GH_CONFIG_DIR:r.join(G,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:"/bin/cat",GH_HOST:"github.com",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1",...process.platform==="linux"?Object.fromEntries(["DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR"].flatMap((L)=>process.env[L]?[[L,process.env[L]]]:[])):{}},X=async(L,T,P=W,k,x=T0)=>{J.assertCurrent();let y=await Z.command(L,T,{cwd:P,env:Y,input:k,maxBuffer:x,timeout:Math.max(1,Math.min(60000,(J.deadlineMs??Date.now()+60000)-Date.now())),signal:J.signal});if(J.assertCurrent(),y.error||y.status!==0)A("local_device_gh_command_failed");return y.stdout},N=async(L)=>(await X(B,L)).toString("utf8").trim(),C=async(L,T="application/vnd.github+json")=>{$4(Q.repoFullName,L,{headers:{accept:T}}),J.assertCurrent();let P=await Z.command(B,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${T}`,L],{cwd:W,env:Y,maxBuffer:T0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),P.error&&P.status===null)A("local_device_gh_response_unavailable");let k=P.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!k)A("local_device_gh_response_invalid");let x=Number(k[1]);if(x>=200&&x<300&&P.status!==0)A("local_device_gh_response_unavailable");if(Buffer.byteLength(k[3])>K2)A("local_device_gh_response_too_large");let y={};for(let i of k[2].split(/\r?\n/)){let e=i.indexOf(":"),D0=i.slice(0,e).toLowerCase();if(["link","content-type"].includes(D0))y[D0]=i.slice(e+1).trim().slice(0,8192)}return{kind:"read",status:x,headers:y,body:x>=200&&x<300?k[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return C(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[L,T]=Q.repoFullName.split("/"),P=await N(["api","graphql","--hostname","github.com","-f",`query=${J4}`,"-f",`owner=${L}`,"-f",`repo=${T}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(P)>K2)A("local_device_gh_response_too_large");let k=JSON.parse(P);if(k.errors||k.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||k.data.repository.pullRequest?.number!==Q.number)A("local_device_gh_response_invalid");return{kind:"pr_review_context",body:P}}if(Q.kind==="pr_merge"){let L=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),T=JSON.parse(L.body),P=(y)=>y.number===Q.number&&y.html_url===`https://github.com/${Q.repoFullName}/pull/${Q.number}`&&y.base?.repo?.full_name?.toLowerCase()===Q.repoFullName.toLowerCase()&&y.base?.ref===Q.expectedBaseRef&&y.head?.sha===Q.expectedHeadSha;if(L.status!==200||!P(T)||T.state!=="open"||T.draft!==!1||T.head?.sha!==Q.expectedHeadSha||T.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())A("local_device_gh_merge_target_changed");await N(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha,...Q.commitBody!==void 0&&Q.method!=="rebase"?[`--body=${Q.commitBody}`]:[]]);let k=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),x=JSON.parse(k.body);if(k.status!==200||!P(x)||x.merged!==!0)A("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:Q.number,merged:!0}}if(Q.kind==="pr_create"){if(Q.head===Q.base)A("local_device_gh_default_branch");let L=await N(["pr","create","--repo",Q.repoFullName,"--head",Q.head,"--base",Q.base,`--title=${Q.title}`,`--body=${Q.body}`,...Q.draft?["--draft"]:[]]);if(!new RegExp("^https://github\\.com/"+Q.repoFullName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/pull/[1-9][0-9]*$").test(L))A("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:L}}if(Q.kind==="pr_mutation"){let L=Q.mutation,T=L.action==="edit"?["edit",...L.title!==void 0?[`--title=${L.title}`]:[],...L.body!==void 0?[`--body=${L.body}`]:[],...L.base?[`--base=${L.base}`]:[]]:L.action==="metadata"?["edit",`--${L.change}-${L.field}=${L.value}`]:L.action==="ready"?["ready"]:L.action==="draft"?["ready","--undo"]:["close"];return await N(["pr",...T,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)A("local_device_gh_workspace_unavailable");let F=q.realpathSync(J.repoPath);if(F!==K&&!F.startsWith(K+r.sep))A("local_device_gh_workspace_unavailable");let D=`https://github.com/${Q.repoFullName}.git`,w="!'"+B.replace(/'/g,"'\\''")+"' auth git-credential",M=Function("return ("+Z4+")")(),j=(L,T,P)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",L,T,...P]]:[T,P],O=async(L,T,P,k=T0)=>{let x=L===W||L.startsWith(W+r.sep),y=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...x?["-c",`credential.https://github.com.helper=${w}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",...T];if(x)return X(U,y,L,P,k);let i=r.join(F,".ara-local-gh-tmp");if(q.mkdirSync(i,{recursive:!0,mode:448}),q.lstatSync(i).isSymbolicLink()||q.realpathSync(i)!==i)A("local_device_gh_workspace_unavailable");J.assertCurrent();let e=await Z.command(...j(M(F,i),U,y),{cwd:L,input:P,maxBuffer:k,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:F,TMPDIR:i,GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1"}});if(J.assertCurrent(),e.error||e.status!==0)A("local_device_gh_collection_failed");return e.stdout},R=async(L,T)=>(await O(L,T)).toString("utf8").trim(),g=async(L,T)=>{let P=r.join(L,".ara-local-gh-tmp");if(q.mkdirSync(P,{recursive:!0,mode:448}),q.lstatSync(P).isSymbolicLink()||q.realpathSync(P)!==P)A("local_device_gh_workspace_unavailable");J.assertCurrent();let k=await Z.command(...j(M(L,P),"/bin/sh",["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",T]),{cwd:L,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:L,TMPDIR:P}});if(J.assertCurrent(),k.error||k.status!==0)A("local_device_gh_materialization_failed")},v=async(L)=>{let T=new Map;if(L.length===0)return T;let P=await O(E,["cat-file","--batch"],[...new Set(L)].join(`
|
|
3
3
|
`)+`
|
|
4
4
|
`,T0*8);for(let k=0;k<P.length;){let x=P.indexOf(10,k),[y,i,e]=P.subarray(k,x).toString("utf8").split(" ");if(x<0||!y||i!=="blob"||!/^[0-9]+$/.test(e??""))A("local_device_gh_object_invalid");T.set(y,P.subarray(x+1,x+1+Number(e)).toString("utf8")),k=x+1+Number(e)+1}return T},I=async(L,T,P)=>{let k=r.join(F,".ara-local-gh-tmp"),x=M(F,k)+`
|
|
5
5
|
(allow file-read* file-write* (subpath ${JSON.stringify(F)}))
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Jd as xe}from"./vm-hands-entry-lite-t497ewn2.js";import{Ce as z,De as Je,ke as W,le as oe,ne as _t,oe as Ne,re as St,se as wt,te as $}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Jd as xe}from"./vm-hands-entry-lite-t497ewn2.js";import{Ce as z,De as Je,ke as W,le as oe,ne as _t,oe as Ne,re as St,se as wt,te as $}from"./vm-hands-entry-lite-m1c4h4me.js";import{Fe as v,He as tt,Ie as D,Qe as Ot}from"./vm-hands-entry-lite-wh0qp1gf.js";import{lg as Jt,og as xt,rg as Z,tg as zt,ug as ae}from"./vm-hands-entry-lite-wh9g92n9.js";import{Tg as Ae,Ug as se}from"./vm-hands-entry-lite-22jgncrd.js";import{ah as Se}from"./vm-hands-entry-lite-mzxhng4z.js";import{ch as q}from"./vm-hands-entry-lite-cp1wqjs5.js";import{Hh as pe,Nh as ye}from"./vm-hands-entry-lite-14t846kp.js";import{Oh as _}from"./vm-hands-entry-lite-v6tkjqb1.js";import{spawn as I}from"child_process";import{randomUUID as Oe}from"crypto";import{closeSync as Vr,copyFileSync as de,existsSync as ut,fstatSync as Er,mkdirSync as fe,openSync as vr,readdirSync as V,readFileSync as ge,readlinkSync as to,renameSync as eo,rmSync as ro,statSync as oo}from"fs";import{connect as so}from"net";import{userInfo as Te}from"os";import{basename as le,dirname as mt,join as b}from"path";var At=`import { spawn, execFileSync } from "node:child_process";
|
|
3
3
|
import { createHash, randomUUID } from "node:crypto";
|
|
4
4
|
import { readFileSync, readlinkSync, lstatSync, realpathSync, statSync, mkdtempSync, mkdirSync, chmodSync, writeFileSync, readdirSync, rmSync, openSync, readSync, closeSync, renameSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var r={name:"github-native-engineer-device-worker-production",version:"0.2.
|
|
2
|
+
var r={name:"github-native-engineer-device-worker-production",version:"0.2.322",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@anthropic-ai/sandbox-runtime":"^0.0.73","@earendil-works/pi-tui":"1.0.0","@modelcontextprotocol/sdk":"^1.29.0","@reason/runtime-distribution":"workspace:*","playwright-core":"1.60.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.13",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{r as Gh};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ab as L9,Bb as n0,Ib as K0,wb as NQ,xb as Y8,yb as s9,zb as _0}from"./vm-hands-entry-lite-q8b738zj.js";import{Qb as SQ,Rb as wQ,Sb as J4,Tb as Y4,Ub as V8}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Zb as b0}from"./vm-hands-entry-lite-n07kxrd1.js";import{Ad as W8,Bd as g0,Fd as C0,Sc as e$,Vc as $Q,yd as w9,zd as o0}from"./vm-hands-entry-lite-t497ewn2.js";import{ee as x}from"./vm-hands-entry-lite-psybjyay.js";import{Oe as yQ,Pe as y8,bf as gQ,hf as i9,if as f8}from"./vm-hands-entry-lite-wh0qp1gf.js";import{$f as JQ,Bf as d9,Cf as s$,Df as n$,Ef as R8,Hf as p9,Qf as I8,Rf as S0,Sf as O0,Tf as l9,_f as w8,ag as i$,kf as CZ,nf as B9,wf as QQ,xf as ZQ,zf as XQ}from"./vm-hands-entry-lite-yhz6sv35.js";import{ah as Z4}from"./vm-hands-entry-lite-mzxhng4z.js";import{ch as N8,dh as u9,gh as Q4}from"./vm-hands-entry-lite-cp1wqjs5.js";import{Bh as W$,hh as B8,ih as i0,jh as L8,kh as a0,lh as H9,mh as J8,nh as e8,oh as s0,ph as p0,qh as u$}from"./vm-hands-entry-lite-ne8kkvk4.js";import{Gh as VZ}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ab as L9,Bb as n0,Ib as K0,wb as NQ,xb as Y8,yb as s9,zb as _0}from"./vm-hands-entry-lite-q8b738zj.js";import{Qb as SQ,Rb as wQ,Sb as J4,Tb as Y4,Ub as V8}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Zb as b0}from"./vm-hands-entry-lite-n07kxrd1.js";import{Ad as W8,Bd as g0,Fd as C0,Sc as e$,Vc as $Q,yd as w9,zd as o0}from"./vm-hands-entry-lite-t497ewn2.js";import{ee as x}from"./vm-hands-entry-lite-psybjyay.js";import{Oe as yQ,Pe as y8,bf as gQ,hf as i9,if as f8}from"./vm-hands-entry-lite-wh0qp1gf.js";import{$f as JQ,Bf as d9,Cf as s$,Df as n$,Ef as R8,Hf as p9,Qf as I8,Rf as S0,Sf as O0,Tf as l9,_f as w8,ag as i$,kf as CZ,nf as B9,wf as QQ,xf as ZQ,zf as XQ}from"./vm-hands-entry-lite-yhz6sv35.js";import{ah as Z4}from"./vm-hands-entry-lite-mzxhng4z.js";import{ch as N8,dh as u9,gh as Q4}from"./vm-hands-entry-lite-cp1wqjs5.js";import{Bh as W$,hh as B8,ih as i0,jh as L8,kh as a0,lh as H9,mh as J8,nh as e8,oh as s0,ph as p0,qh as u$}from"./vm-hands-entry-lite-ne8kkvk4.js";import{Gh as VZ}from"./vm-hands-entry-lite-et7c3583.js";import{Mh as X4}from"./vm-hands-entry-lite-14t846kp.js";import{Oh as C}from"./vm-hands-entry-lite-v6tkjqb1.js";import{Ph as P1,Uh as GZ}from"./vm-hands-entry-lite-cxs89wzv.js";var v={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000,window:8};function h9($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function P0($,Q,Z=Number.MAX_SAFE_INTEGER){return typeof $==="number"&&Number.isSafeInteger($)&&$>=Q&&$<=Z}function E$($){return typeof $==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test($)}function S$($,Q){let Z=Buffer.from($,"latin1");return Buffer.concat([Buffer.from([Z.length]),Z,Q])}function I0($){if(!h9($)||Object.keys($).length!==12||![$.organizationId,$.userId,$.runId,$.deviceId,$.rootId,$.jobId,$.fenceId].every(E$)||!P0($.attachmentRevision,0)||!P0($.grantRevision,1)||!P0($.generation,1)||!P0($.port,1024,65535)||!P0($.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...$})}function c0($,Q){return Object.keys($).every((Z)=>$[Z]===Q[Z])}function q9($){if($.length>4096||!$.startsWith("/")||$.startsWith("//")||/[\\\x00-\x20\x7f#]/.test($))throw Error("preview_path_invalid");let Q=decodeURIComponent($);if(Q.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(Q))throw Error("preview_path_invalid");return $}function R$($){return Array.isArray($)&&$.length<=64&&$.every((Q)=>Array.isArray(Q)&&Q.length===2&&typeof Q[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(Q[0])&&typeof Q[1]==="string"&&Q[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(Q[1]))}function C9($,Q=v.chunk){if($.length>Math.ceil(Q/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test($))throw Error("preview_data_invalid");let Z=Buffer.from($,"base64");if(Z.length>Q)throw Error("preview_data_too_large");return Z}function w$($){if(Array.isArray($))return Buffer.concat($);if(typeof $==="string")return Buffer.from($,"utf8");if($ instanceof ArrayBuffer)return Buffer.from($);return $}function b$($){if(Buffer.byteLength($)>v.upload*1.4+300000)throw Error("preview_frame_too_large");let Q=JSON.parse($);if(!h9(Q))throw Error("preview_frame_invalid");if(Q.type==="hello")return{type:"hello",binding:I0(Q.binding),...P0(Q.messages,v.chunk,v.upload)?{messages:Q.messages}:{},...P0(Q.window,1,v.window)?{window:Q.window}:{},...Q.bytes===!0?{bytes:!0}:{}};if(Q.type==="refused"&&typeof Q.reason==="string"&&/^[a-z_]{1,32}$/.test(Q.reason))return{type:"refused",binding:I0(Q.binding),reason:Q.reason};if(!E$(Q.id))throw Error("preview_frame_invalid");if(Q.type==="end"||Q.type==="cancel"||Q.type==="credit")return{type:Q.type,id:Q.id};if(Q.type==="ws"&&typeof Q.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(Q.protocol))return{type:"ws",id:Q.id,protocol:Q.protocol};if(Q.type==="data"&&typeof Q.data==="string"&&typeof Q.binary==="boolean")return C9(Q.data,v.upload),{type:"data",id:Q.id,data:Q.data,binary:Q.binary};if(Q.type==="head"&&P0(Q.status,200,599)&&R$(Q.headers))return{type:"head",id:Q.id,status:Q.status,headers:Q.headers};if(Q.type==="request"&&typeof Q.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(Q.method)&&typeof Q.path==="string"&&R$(Q.headers)&&typeof Q.body==="string"&&typeof Q.upgrade==="boolean")return C9(Q.body,v.upload),{type:"request",id:Q.id,method:Q.method,path:q9(Q.path),headers:Q.headers,body:Q.body,upgrade:Q.upgrade};throw Error("preview_frame_invalid")}function D8($){let Q=[...$],Z=new Set(Q.filter(([J])=>J.toLowerCase()==="connection").flatMap(([,J])=>J.toLowerCase().split(",").map((Y)=>Y.trim()))),X=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 Q.filter(([J])=>!X.has(J.toLowerCase())&&!Z.has(J.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(J))}async function _8($){let Q;try{return await Promise.race([Promise.resolve().then($).then((Z)=>Z===!0||(Z===!1?!1:void 0),()=>{return}),new Promise((Z)=>{Q=setTimeout(()=>Z(void 0),v.authorizationMs)})])}finally{clearTimeout(Q)}}async function T9($){return await _8($)===!0}function v9($,Q){let Z=new URL($);if(Z.username||Z.password||Z.search||Z.hash||!(Z.protocol==="wss:"||Z.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(Z.hostname))||!new RegExp(`^/${Q}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(Z.pathname))throw Error("preview_relay_invalid");return Z.href}function k$($){if(!h9($)||Object.keys($).length!==2||typeof $.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:I0($.binding),deviceRelayUrl:v9($.deviceRelayUrl,"device")}}function f$($){if(!h9($)||Object.keys($).length!==1||!("binding"in $))throw Error("preview_close_invalid");return{binding:I0($.binding)}}import{request as T4}from"http";import{pipeline as O4}from"stream";import{constants as A8,createBrotliCompress as D4,createGzip as _4}from"zlib";import{WebSocket as O9}from"ws";import{randomBytes as j4,timingSafeEqual as C4}from"crypto";import{createServer as q4}from"net";var g$="x-preview-connection";async function m$($,Q){if(Q.aborted)throw Error("preview_closed");let Z=j4(32).toString("base64url"),X=new Set,J=!1,Y=q4((G)=>{if(J||Q.aborted||X.size>=v.streams*2)return G.destroy();X.add(G);let F=new AbortController;G.once("close",()=>{X.delete(G),F.abort()}),G.on("error",()=>G.destroy()),G.setTimeout(2000,()=>G.destroy());let B=Buffer.alloc(0),H=(L)=>{B=Buffer.concat([B,L]);let W=B.indexOf(`\r
|
|
3
3
|
\r
|
|
4
4
|
`);if(W<0){if(B.length>16384)G.destroy();return}if(G.pause(),G.off("data",H),W>16384||B.length>v.upload+16384)return G.destroy();z(B,W).catch(()=>G.destroy())};G.on("data",H);async function z(L,W){let U=L.subarray(0,W).toString("latin1").split(`\r
|
|
5
5
|
`),j=/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) (\S+) HTTP\/1\.1$/.exec(U.shift()??"");if(!j)throw Error("preview_request_invalid");q9(j[2]);let O=!1,q=0,A=[];for(let T of U){let S=/^([a-zA-Z0-9-]+):[ \t]*([^\x00-\x08\x0a-\x1f\x7f]*)$/.exec(T);if(!S)throw Error("preview_header_invalid");if(S[1].toLowerCase()===g$){q++;let g=Buffer.from(S[2].trim());O=g.length===Z.length&&C4(g,Buffer.from(Z))}else if(S[1].toLowerCase()!=="host")A.push(T)}if(!O||q!==1||J||F.signal.aborted)throw Error("preview_connection_denied");let R=await $.connect(F.signal);if(J||F.signal.aborted)throw R.destroy(),Error("preview_closed");X.add(R),R.on("error",()=>G.destroy()),R.once("close",()=>{X.delete(R),G.destroy()}),G.once("close",()=>R.destroy()),G.setTimeout(0);let P=[`${j[1]} ${j[2]} HTTP/1.1`,`Host: 127.0.0.1:${R.remotePort}`,...A,"",""].join(`\r
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{if as Z8}from"./vm-hands-entry-lite-wh0qp1gf.js";import{rf as R0}from"./vm-hands-entry-lite-yhz6sv35.js";import{ng as Kq}from"./vm-hands-entry-lite-
|
|
2
|
+
import{if as Z8}from"./vm-hands-entry-lite-wh0qp1gf.js";import{rf as R0}from"./vm-hands-entry-lite-yhz6sv35.js";import{ng as Kq}from"./vm-hands-entry-lite-wh9g92n9.js";import{Jg as p,Mg as V0,Pg as F0,Qg as C8,Rg as eq,Tg as g8,Wg as q0,Yg as x0}from"./vm-hands-entry-lite-22jgncrd.js";import{bh as wq}from"./vm-hands-entry-lite-mzxhng4z.js";import{ch as o,dh as C0}from"./vm-hands-entry-lite-cp1wqjs5.js";import{qh as B0}from"./vm-hands-entry-lite-ne8kkvk4.js";import{Hh as A0}from"./vm-hands-entry-lite-14t846kp.js";import{Oh as Z}from"./vm-hands-entry-lite-v6tkjqb1.js";import{execFile as V1,spawn as w0}from"child_process";import{randomBytes as F1}from"crypto";import{chmodSync as w1,existsSync as K0,lstatSync as K1,mkdirSync as M1,readFileSync as z1,rmSync as Y1,writeFileSync as Xq}from"fs";import{connect as _1}from"net";import{join as H}from"path";var Bq="./desktop-wallpaper-0pjhgyfk.jpg";var Rq="./dock-browser-afp005mt.png";var Cq="./dock-files-rywdm96b.png";var yq="./dock-terminal-s41cj1jp.png";var Sq=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
|
|
3
3
|
# The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
|
|
4
4
|
# python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
|
|
5
5
|
# Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Gh as $}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Gh as $}from"./vm-hands-entry-lite-et7c3583.js";var O=$.version,Z=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function S(B,D){if(!Z.test(B)||!Z.test(D))throw Error("cannot compare invalid CLI versions");let J=(q)=>{let y=q.indexOf("-");return y===-1?[q,void 0]:[q.slice(0,y),q.slice(y+1)]},[j,F]=J(B),[w,G]=J(D),K=j.split(".").map(BigInt),M=w.split(".").map(BigInt);for(let q=0;q<3;q+=1){if(K[q]===M[q])continue;return K[q]<M[q]?-1:1}if(F===void 0||G===void 0){if(F===G)return 0;return F===void 0?1:-1}let Q=F.split("."),U=G.split("."),A=Math.max(Q.length,U.length);for(let q=0;q<A;q+=1){let y=Q[q],z=U[q];if(y===void 0||z===void 0){if(y===z)return 0;return y===void 0?-1:1}if(y===z)continue;let H=/^\d+$/.test(y),W=/^\d+$/.test(z);if(H&&W){let X=BigInt(y),Y=BigInt(z);if(X===Y)continue;return X<Y?-1:1}if(H!==W)return H?-1:1;return y<z?-1:1}return 0}function k(B,D){return D?`cli ${B} \xB7 agent ${D}`:`cli ${B}`}
|
|
3
3
|
export{O as Ch,Z as Dh,S as Eh,k as Fh};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Tg as wz,Ug as Nz}from"./vm-hands-entry-lite-22jgncrd.js";import{ch as N}from"./vm-hands-entry-lite-cp1wqjs5.js";import{Ch as A}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Tg as wz,Ug as Nz}from"./vm-hands-entry-lite-22jgncrd.js";import{ch as N}from"./vm-hands-entry-lite-cp1wqjs5.js";import{Ch as A}from"./vm-hands-entry-lite-n2k92e7f.js";import{Uh as Fz}from"./vm-hands-entry-lite-cxs89wzv.js";import{spawnSync as iz}from"child_process";import{dirname as g}from"path";import{spawn as cz}from"child_process";import{accessSync as lz,constants as sz}from"fs";import{basename as nz,join as pz}from"path";import{randomUUID as p}from"crypto";import{spawnSync as M}from"child_process";import{chmodSync as Hz,cpSync as Rz,existsSync as U,lstatSync as O,mkdirSync as i,readdirSync as Cz,readFileSync as E,readlinkSync as Lz,realpathSync as T,renameSync as R,rmdirSync as Mz,rmSync as P,symlinkSync as c,writeFileSync as Oz}from"fs";import{dirname as C,join as D,relative as Uz,resolve as Tz}from"path";var a="so.ara.cli",_z="5LJFSBRY2F";var o="ReasonBackgroundIdentity",r="Contents/Helpers/ReasonPermissionTile";var x="AraBackgroundIdentity",Az="Reason",Iz=`anchor apple generic and identifier "${a}" and certificate leaf[subject.OU] = "${_z}"`;class L extends Error{code;constructor(z,J){super(J);this.code=z;this.name="MacOSBackgroundIdentityError"}}var k="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";function v(z=N()){return D(z,"Library","Application Support","Reason","Background","Reason.app")}function _(z=N()){return D(z,"Library","Application Support","Ara","Background","Ara.app")}function kz(z){try{return O(z).isFile()}catch{return!1}}function y(z){return[o,x].map((J)=>D(z,"Contents","MacOS",J)).find(kz)??null}function w(z){try{if(!O(z).isDirectory())return!1;let J=E(D(z,"Contents","Info.plist"),"utf8");return J.includes(`<string>${a}</string>`)&&(J.includes(`<string>${Az}</string>`)||J.includes("<string>Ara</string>"))&&y(z)!==null}catch{return!1}}function I(z=N()){let J=v(z);if(!w(J))return null;try{let Z=E(D(J,"Contents","Info.plist"),"utf8");return/<key>CFBundleVersion<\/key>\s*<string>(\d+\.\d+\.\d+)<\/string>/.exec(Z)?.[1]??null}catch{return null}}function Sz(z,J=N()){let Z=I(J);return Z===null||$z(S(Z.split(".")),S(z.split(/[.-]/).slice(0,3)))}var fz=1e4;function t(z,J){return M(z,[...J],{stdio:"ignore",timeout:fz}).status??1}var e=new Set;function zz(z){if(process.env.REASON_TEST_REFUSE_REAL_IDENTITY!=="1")return;let J=(Z)=>{try{return T(Z)}catch{return Tz(Z)}};if(z!==void 0&&J(z)!==J(N()))return;throw Error("A test tried to change this computer's real Reason background identity; pass a temporary home. Refused by scripts/test-env.ts.")}var Jz=/\/(?:runtime|CLI)\/versions\/(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$|\/\.ara(?:-staging)?-worker-(\d+)\.(\d+)\.(\d+)[^/]*\/[^/]+$/,Zz=new Set(["ara","ara.exe","reason","reason.exe"]);function S(z){return z.map((J)=>Number(J))}function $z(z,J){for(let Z=0;Z<3;Z+=1)if(z[Z]!==J[Z])return z[Z]<J[Z];return!1}var Ez=[0,2,161];function xz(z){if(z===null)return!0;let J=Ez,Z=null;try{Z=T(process.execPath)}catch{}return z.some(($)=>{let j=Jz.exec($);if(j){let Q=j[1]===void 0?j.slice(4,7):j.slice(1,4);return $z(S(Q),J)}let q=$.slice($.lastIndexOf("/")+1);return Zz.has(q)&&$!==Z&&$!==process.execPath})}function yz(){let z=M("/bin/ps",["-xo","pid=,comm="],{encoding:"utf8",timeout:5000});if(z.status!==0)return null;let J=[];for(let Z of z.stdout.split(`
|
|
3
3
|
`)){let $=/^\s*(\d+)\s+(\S.*)$/.exec(Z);if(!$||Number($[1])===process.pid)continue;let j=$[2].trimEnd(),q=j.slice(j.lastIndexOf("/")+1);if(!Jz.test(j)&&Zz.has(q)){let V=M("/usr/sbin/lsof",["-a","-p",$[1],"-d","txt","-Fn"],{encoding:"utf8",timeout:5000}).stdout?.split(`
|
|
4
4
|
`).find((X)=>X.startsWith("n/"));if(V)j=V.slice(1)}J.push(j)}return J}function bz(z){if(zz(z.home),!w(z.sourceApp))throw new L("identity_invalid","The packaged Reason background identity is missing or invalid.");let J=z.command??t,Z=v(z.home),$=C(Z);i($,{recursive:!0,mode:448}),Hz($,448);let j=T(z.sourceApp),q=null;try{q=T(Z)}catch{}if(j!==q){let Q=`${process.pid}.${p()}`,V=D($,`.Reason.app.${Q}.tmp`),X=D($,`.Reason.app.${Q}.old`),W=!1;try{if(Rz(j,V,{recursive:!0,errorOnExist:!0,preserveTimestamps:!0}),!w(V))throw new L("identity_invalid","The copied Reason background identity is invalid.");let Y=z.releaseSigned?["--test-requirement",`=${Iz}`]:[];if(J("/usr/bin/codesign",["--verify","--strict",...Y,V])!==0)throw new L("identity_invalid_signature","The installed Reason background identity has an invalid signature.");let B=!1;for(let F=0;F<4;F+=1){let G=!1;try{R(Z,X),G=!0,W=!0}catch(K){if(K.code!=="ENOENT")throw K}if(F===0)z.beforePublish?.();try{R(V,Z),B=!0}catch(K){let m=K.code;if(!["EEXIST","ENOTEMPTY"].includes(m??""))throw K;if(G)P(X,{recursive:!0,force:!0}),W=!1;if(F===3)throw K;continue}if(G)P(X,{recursive:!0,force:!0}),W=!1;break}if(!B)throw Error("Could not publish Reason's background identity.")}catch(Y){if(W&&!U(Z)&&U(X))R(X,Z);throw Y}finally{P(V,{recursive:!0,force:!0}),P(X,{recursive:!0,force:!0})}}return Wz(Z,z,{verified:j!==q}),Z}function jz(z){return D(C(z),".Reason.app.registered")}function qz(z){try{let J=O(z);return J.isDirectory()?`${J.ino}:${J.birthtimeMs}`:null}catch{return null}}function f(z){let J=qz(z);try{return J!==null&&E(jz(z),"utf8")===J}catch{return!1}}function Qz(z){if(w(z))return"bundle";try{if(O(D(z,"Contents","Info.plist"),{throwIfNoEntry:!1}))return null;return O(D(z,"Contents","MacOS",x)).isSymbolicLink()?"retired":null}catch{return null}}function Wz(z,J,Z={}){let $=J.command??t;if(!Z.verified&&$("/usr/bin/codesign",["--verify","--strict",z])!==0)throw new L("identity_invalid_signature","The installed Reason background identity has an invalid signature.");if($(k,["-f",z])!==0)throw new L("identity_register_failed","Could not register Reason's macOS background identity.");let j=qz(z);try{if(j)Oz(jz(z),j,{mode:384})}catch{}try{gz(z,J.home,$,J.runningExecutables??yz)}catch(q){let Q=q.code??"unknown";process.stderr.write(`Reason background identity: legacy_identity_retire_failed (${Q})
|
|
5
5
|
`)}}function gz(z,J,Z,$){let j=y(z);if(!j)return;let q=_(J),Q=C(q),V=(K)=>D(K,"Contents","MacOS",x),X=Uz(C(V(q)),j),W=`${process.pid}.${p()}`,Y=Qz(q);if(Y===null)return;let B=Y==="bundle";if(B)Z(k,["-u",q]);let F=D(Q,`.Ara.app.${W}.old`);if(!e.has(q)&&!xz($())){if(!B)Z(k,["-u",q]);try{R(q,F)}catch(K){if(K.code==="ENOENT")return;throw K}P(F,{recursive:!0,force:!0}),uz(Q);return}if(!B){if(Lz(V(q))===X)return;let K=`${V(q)}.${W}`;c(X,K);try{R(K,V(q))}finally{P(K,{force:!0})}return}let G=D(Q,`.Ara.app.${W}.shim`);i(C(V(G)),{recursive:!0}),c(X,V(G));try{try{R(q,F)}catch(K){if(K.code==="ENOENT")return;throw K}try{R(G,q)}catch(K){if(U(q))return;throw R(F,q),K}}finally{P(G,{recursive:!0,force:!0}),P(F,{recursive:!0,force:!0})}}function uz(z){try{if(Cz(z).some((Z)=>Z!==".DS_Store"))return;P(D(z,".DS_Store"),{force:!0}),Mz(z)}catch{}}var l=new Map;function hz(z=N()){let J=l.get(z);if(J)return J;if(process.platform!=="darwin")return[];let Z=s(z);if(Z===null&&U(C(v(z))))Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100),Z=s(z);if(Z===null)return[];return l.set(z,Z),Z}function s(z){let J=v(z),Z=_(z);if(!w(J)||!f(J))try{dz({home:z,skipWhenSettled:!0})}catch{}let $=w(J)&&(f(J)||!w(Z))?J:w(Z)?Z:null,j=$?y($):null;if(!j)return null;if($===Z)e.add(Z);let q=M(j,["--can-spawn"],{env:{},timeout:2000,encoding:"utf8"});return q.status===0&&q.stdout===`spawn
|
|
@@ -20,7 +20,7 @@ The macOS privacy permissions of this computer's Reason worker:
|
|
|
20
20
|
allow asks for each missing one, or the one named. macOS cannot ask for Full
|
|
21
21
|
Disk Access: allow disk opens its pane, shows the file to add in Finder and
|
|
22
22
|
waits until the worker has it.
|
|
23
|
-
`,u="x-apple.systempreferences:com.apple.preference.security",az="curl -fsSL https://reasonmachines.com/install.sh | bash",oz=180000,rz=2000,h=["screen","accessibility","disk"],d={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${u}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${u}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${u}?Privacy_AllFiles`}};function Bz(z){return z.executable}function tz(z,J){if(z==="computer_use_identity_missing")return`Reason's background identity is not installed (${z}); reinstall Reason: ${az}`;if(z==="computer_use_identity_outdated")return`Reason's background identity is outdated (${I(J)??"unknown"}; this CLI is ${A}) (${z}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${z}); run the installed \`reason\``}function ez(z=N()){let J=b(z);if(J.length>0)return{state:"ready",path:g(g(g(J[0]))),prefix:J};let Z=Kz(J,z)??"computer_use_identity_unavailable";return{state:Z,path:v(z),detail:tz(Z,z)}}function Pz(){return{identity:()=>ez(),grants:(z)=>wz(z),request:(z,J)=>Nz(z,J),worker:async()=>(await import("./status-
|
|
23
|
+
`,u="x-apple.systempreferences:com.apple.preference.security",az="curl -fsSL https://reasonmachines.com/install.sh | bash",oz=180000,rz=2000,h=["screen","accessibility","disk"],d={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${u}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${u}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${u}?Privacy_AllFiles`}};function Bz(z){return z.executable}function tz(z,J){if(z==="computer_use_identity_missing")return`Reason's background identity is not installed (${z}); reinstall Reason: ${az}`;if(z==="computer_use_identity_outdated")return`Reason's background identity is outdated (${I(J)??"unknown"}; this CLI is ${A}) (${z}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${z}); run the installed \`reason\``}function ez(z=N()){let J=b(z);if(J.length>0)return{state:"ready",path:g(g(g(J[0]))),prefix:J};let Z=Kz(J,z)??"computer_use_identity_unavailable";return{state:Z,path:v(z),detail:tz(Z,z)}}function Pz(){return{identity:()=>ez(),grants:(z)=>wz(z),request:(z,J)=>Nz(z,J),worker:async()=>(await import("./status-ghjnryz1.js")).connectionMacState(),open:(z)=>{iz("/usr/bin/open",z,{stdio:"ignore",timeout:1e4})},tile:Xz,restartConnection:async()=>(await import("./connect-cli-cyt0kpyr.js")).restartConnection(),sleep:(z)=>new Promise((J)=>setTimeout(J,z)),now:()=>Date.now()}}function Yz(z,J,Z){if(z.state!=="ready"||!J)return"unknown";return J[Z]?"granted":"missing"}async function vz(z){let J=z.identity(),Z=J.state==="ready"?await z.grants(J.prefix):null,$=await z.worker(),j=$?Bz($):null,q=!j||$?.full_disk_access==="unknown"?"unknown":$?.full_disk_access==="granted"?"granted":"missing",Q=(V,X,W)=>{let{label:Y,purpose:B,level:F}=d[V];return{id:V,label:Y,purpose:B,level:F,state:X,holder:W}};return{identity:{state:J.state,path:J.path,detail:J.state==="ready"?null:J.detail},worker_detail:j?null:"Full Disk Access is read from this computer's running worker; `reason connect` starts it.",permissions:[Q("screen",Yz(J,Z,"screen"),J.path),Q("accessibility",Yz(J,Z,"accessibility"),J.path),Q("disk",q,j)]}}function MJ(z){let J=z.identity.state==="ready"?null:z.identity.state,Z=z.permissions.filter((q)=>q.state==="granted").length,$=[...J?[J]:[],...z.permissions.filter((q)=>q.state!=="granted"&&!(J&&q.id!=="disk")).map((q)=>`${q.label} ${q.state}`)],j=!J&&z.permissions.some((q)=>q.state==="missing");return`Permissions: ${Z} of ${z.permissions.length}${$.length>0?` (${$.join(", ")})`:""}`+(j?" \u2014 reason permissions allow":$.length>0?" \u2014 reason permissions":"")}function zJ(z){let J=[];if(z.identity.detail)J.push(z.identity.detail);J.push(`Reason: ${z.identity.path}`);let Z=z.permissions.find(($)=>$.id==="disk");J.push(Z?.holder?`Worker: ${Z.holder}`:`Worker: ${z.worker_detail}`),J.push("");for(let $ of z.permissions){let j=`${$.label}${$.level==="recommended"?" (recommended)":""}`;J.push(` ${$.id.padEnd(13)} ${$.state.padEnd(7)} ${j}: ${$.purpose}`)}if(z.permissions.some(($)=>$.state==="missing"))J.push("","Allow the missing ones: reason permissions allow");return`${J.join(`
|
|
24
24
|
`)}
|
|
25
25
|
`}async function Gz(z,J){let Z=J.now()+oz;for(;;){if(await z())return!0;if(J.now()>=Z)return!1;await J.sleep(rz)}}async function JJ(z,J){let Z=J.host??Pz(),{io:$}=J,j=await vz(Z),q=j.permissions.filter((W)=>z.includes(W.id)&&W.state!=="granted");if(q.length===0)return $.stdout.write(`Reason permissions: ${z.map((W)=>d[W].label).join(", ")} already allowed.
|
|
26
26
|
`),0;let Q=!1,V=!1,X=Z.identity();for(let W of q){let{label:Y,pane:B}=d[W.id];if(W.id!=="disk"){if(X.state!=="ready"){if(!Q)$.stderr.write(`Reason permissions: ${X.detail}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./vm-hands-entry-lite-tsd17dcd.js";import"./vm-hands-entry-lite-t497ewn2.js";import"./vm-hands-entry-lite-psybjyay.js";import{Uh as A}from"./vm-hands-entry-lite-cxs89wzv.js";import{readFileSync as J}from"fs";var G=performance.now();delete process.env.BUN_BE_BUN;var q=(j,b={})=>console.log(JSON.stringify({stage:j,ms:Math.round(performance.now()),...b}));async function K(){if(process.argv.includes("--vm-hands-op-runner")){let{runVmHandsOpRunner:D}=await import("./vm-hands-op-runner-
|
|
2
|
+
import"./vm-hands-entry-lite-tsd17dcd.js";import"./vm-hands-entry-lite-t497ewn2.js";import"./vm-hands-entry-lite-psybjyay.js";import{Uh as A}from"./vm-hands-entry-lite-cxs89wzv.js";import{readFileSync as J}from"fs";var G=performance.now();delete process.env.BUN_BE_BUN;var q=(j,b={})=>console.log(JSON.stringify({stage:j,ms:Math.round(performance.now()),...b}));async function K(){if(process.argv.includes("--vm-hands-op-runner")){let{runVmHandsOpRunner:D}=await import("./vm-hands-op-runner-766rq98c.js");await D();return}q("parsed",{t0:Math.round(G)});let j="";try{j=J(3,"utf8")}catch{}q("fd3_read",{bytes:j.length});let b=null;if(j.trim())try{b=JSON.parse(j)}catch{b=null}if(!b||typeof b!=="object"||Array.isArray(b))q(j.trim()?"identity_invalid":"identity_free"),await new Promise(()=>{setInterval(()=>{return},1073741824)});let{parseVmHandsInit:B,runVmHands:C}=await import("./vm-hands-runtime-xa917sav.js"),z=B(b);if(!z)q("identity_invalid"),await new Promise(()=>{setInterval(()=>{return},1073741824)});await C(z,q),process.exit(0)}K();
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ka as Kq,ob as Bq,qa as Yq,sb as Tq}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ka as Kq,ob as Bq,qa as Yq,sb as Tq}from"./vm-hands-entry-lite-gycydjw0.js";import"./vm-hands-entry-lite-q8b738zj.js";import"./vm-hands-entry-lite-qvrnx0vk.js";import"./vm-hands-entry-lite-n07kxrd1.js";import"./vm-hands-entry-lite-t497ewn2.js";import"./vm-hands-entry-lite-psybjyay.js";import"./vm-hands-entry-lite-wh0qp1gf.js";import"./vm-hands-entry-lite-yhz6sv35.js";import"./vm-hands-entry-lite-mzxhng4z.js";import"./vm-hands-entry-lite-cp1wqjs5.js";import"./vm-hands-entry-lite-ne8kkvk4.js";import"./vm-hands-entry-lite-et7c3583.js";import"./vm-hands-entry-lite-14t846kp.js";import"./vm-hands-entry-lite-v6tkjqb1.js";import"./vm-hands-entry-lite-cxs89wzv.js";import{spawn as wq}from"child_process";import{chmodSync as Pq,chownSync as Dq,existsSync as t,lstatSync as s,mkdirSync as e,mkdtempSync as jq,readdirSync as p,readFileSync as A,realpathSync as Aq,rmdirSync as r,rmSync as fq,writeFileSync as c}from"fs";import{join as L}from"path";var Uq="/sys/fs/cgroup/reason-payload",S="vm-hands",Cq="/run/ara-srt/fallbacks.jsonl",u="/reason-person",qq=5000,vq=1e4,Xq="__VM_HANDS_PROOF_DIR__",Oq="__VM_HANDS_PROBE_NONCE__";class R extends Error{code;constructor(q,z){super(z);this.code=q}}function Vq(q,z){if(!/^[0-9a-f-]{36}$/i.test(z))throw new R("vm_hands_bind_invalid","bad bind id");return L(q,S,`b-${z.toLowerCase()}`)}var bq=30000,Lq=(q)=>`'${q.replaceAll("'","'\\''")}'`;function lq(q){let z=q.cgroup??Uq,K=q.init.layout.payload_uid,X=q.log??(()=>{}),G=new Map,Y=new Map,B=0,O=()=>{try{let Z=A("/run/ara-srt/starts.jsonl","utf8"),$=Z.slice(B>Z.length?0:B).split(`
|
|
3
3
|
`).filter(Boolean);B=Z.length;let Q=$.map((T)=>{try{return Number(JSON.parse(T).elapsed_ms)||0}catch{return 0}});if(Q.length)X("vm_hands.srt_server_starts",{count:Q.length,elapsed_ms:Q.slice(0,8)})}catch{}},j=null,_=!1,h=q.srtCgroup??"/sys/fs/cgroup/reason-srt",f=()=>{j??=Zq()},b=0,x=()=>{try{let Z=A(Cq,"utf8"),$=Z.slice(b>Z.length?0:b);b=Z.length;let Q=$.split(`
|
|
4
4
|
`).filter(Boolean).slice(0,1000);if(!Q.length)return null;let T={},U=0;for(let N of Q)try{let M=JSON.parse(N),F=typeof M.code==="string"&&/^[a-z_]{1,40}$/.test(M.code)?M.code:"other";if(T[F]=(T[F]??0)+1,typeof M.elapsed_ms==="number")U=Math.max(U,M.elapsed_ms)}catch{T.unparsed=(T.unparsed??0)+1}return X("vm_hands.srt_fallbacks",{count:Q.length,codes:T,max_elapsed_ms:U}),{count:Q.length,codes:T,max_elapsed_ms:U}}catch{return null}},w=!1,y=(Z,$,Q)=>{if(w)throw Error("vm_hands_pool_held");return n(Z,$,Q)},i=(Z)=>($,Q,T)=>wq("/bin/sh",["-c",`echo $$ > ${Lq(L(Z,"cgroup.procs"))} || exit 125; exec "$@"`,"vm-hands-join",$,...Q],T),n=i(L(z,S)),g=(Z)=>Vq(z,Z),Mq=(Z)=>{let $=g(Z);try{e($,{mode:493})}catch(Q){if(!(Q&&typeof Q==="object"&&("code"in Q)&&Q.code==="EEXIST"))throw new R("vm_hands_bind_failed","bind cgroup")}return $},Nq=(Z)=>{try{r(g(Z))}catch{}},I=q.prespawn?Kq({spawnProcess:y,...q.relayDependencies?.sourceEntrypoint?{sourceEntrypoint:q.relayDependencies.sourceEntrypoint}:{},log:(Z,$)=>X(Z,$??{})}):null;I?.arm();let a=I?setInterval(()=>{I.arm()},bq):null;a?.unref?.();async function m(Z){let $=G.get(Z);if(G.delete(Z),!$)return;$.abort.abort(),await $.done}return{bindCgroup:g,async startExecutor(Z){if(f(),Y.set(Z.bindId,Zq()),_=!0,!Z.claim)throw new R("vm_hands_bind_invalid","an executor needs the claim it serves");await m(Z.bindId);let{claim:$,bindId:Q}=Z,T=Mq(Q),U=$.owner;if(!U||typeof U.device_id!=="string"||typeof $.root_id!=="string")throw new R("vm_hands_bind_invalid","claim without its owner Device or root");let N=new AbortController,M,F,D=new Promise((W,P)=>{M=W,F=P}),v,C=new Promise((W)=>{v=W}),V=Tq({headless:!0,hostExecution:!0,runtimeDirectory:q.runtimeDirectory,deviceIdentity:{deviceId:U.device_id,rootId:$.root_id,apiOrigin:q.apiOrigin},claimOwner:$.owner,root:q.root,runId:$.run_id,operationId:$.operation_id,attemptId:$.attempt_id,payload:Object.fromEntries(Object.entries($.payload).filter(([W])=>!W.startsWith("vm_hands_"))),signal:N.signal,emitEvent:async(W,P)=>{if(W==="hands.ready"){M(P);return}if(W==="hands.started"||W==="hands.stopped"||W==="hands.failed")return;await q.forward(Q,W,P)}},{...q.relayDependencies,spawnWorker:(W)=>i(T)(W.command,W.args,W.options),...I?{takePrespawnedWorker:(W)=>{let P=I.take(W);if(!P?.pid)return P;try{return c(L(T,"cgroup.procs"),String(P.pid)),P}catch{try{P.kill("SIGKILL")}catch{}return null}},adoptSpawnedWorker:I.adopt}:{}}).then(()=>{v("executor_stopped")},(W)=>{let P=W&&typeof W==="object"&&"code"in W?String(W.code):"executor_failed";F(new R(P,W instanceof Error?W.message:String(W))),v(P)}).finally(()=>F(new R("vm_hands_executor_exited","executor ended before it was ready")));G.set(Q,{abort:N,done:V,exited:C,operationId:$.operation_id,runId:$.run_id,expiresAtMs:Date.parse(String($.payload.expires_at??""))||0});let E=await D,J=E.executor_launch_id;if(typeof J!=="string")throw new R("vm_hands_bind_failed","executor ready without a launch id");return{launchId:J,readyData:E,applied:{hands_confinement:typeof $.payload.hands_confinement==="string"?$.payload.hands_confinement:null,browser_egress:$.payload.browser_egress??null}}},takeSrtFallbacks:x,executorExited(Z){return G.get(Z)?.exited??new Promise(()=>{})},freezeBind(Z){let $=g(Z);if(t(L($,"cgroup.freeze")))c(L($,"cgroup.freeze"),"1")},async killAndVerifyPayload(Z){let $=new Set(Z?.keep??[]);if($.size)return Rq(Z?.bindId??null,$);w=!0;let Q=Wq();try{await Jq();let T=Promise.all([...G.keys()].map((F)=>m(F).catch(()=>{return})));O();let U=Date.now()+qq;await d(z,U,"payload"),await T;let N=(_||q.srtWarmLate?.()===!0)&&t(L(h,"cgroup.events"));if(N)await d(h,U,"srt");let M=Qq(K).filter((F)=>!k(F,u));if(j!==null){let F=$q(j).filter((D)=>D!==process.pid&&!k(D,u));if(F.length)throw X("vm_hands.kill_strays",{strays:F.slice(0,16).map((D)=>{let v="?",C="?";try{v=A(`/proc/${D}/comm`,"utf8").trim().slice(0,32)}catch{}try{C=(A(`/proc/${D}/cgroup`,"utf8").split(`
|
|
5
5
|
`).find((V)=>V.startsWith("0::"))??"").slice(3,80)}catch{}return{pid:D,comm:v,cgroup:C}})}),new R("vm_hands_kill_unverified",`${F.length} process(es) the run started survived it`);j=null}if(_=!1,N)q.onSrtReset?.();if(M.length)throw X("vm_hands.kill_survivors",{pids:M.slice(0,16)}),new R("vm_hands_kill_unverified",`${M.length} payload-uid process(es) outside the payload cgroup`);Y.clear();for(let F of o())try{r(L(z,S,F))}catch{}}finally{w=!1,Q()}if(I)setTimeout(()=>{if(!G.size)I.arm()},100).unref?.()},async runProbe({nonce:Z,script:$}){if(f(),!$.includes(Xq))throw new R("vm_hands_probe_failed","probe names no proof directory");let Q=q.proofParent??"/tmp/reason-vm-hands-proof";e(Q,{mode:457,recursive:!0});let T=s(Q);if(T.isSymbolicLink()||!T.isDirectory()||T.uid!==(process.getuid?.()??-1)||(T.mode&4095)!==457)throw new R("vm_hands_probe_failed","proof parent is not root's 0711 directory");let U=jq(L(Q,"p-")),N=!1;try{if(!/^[A-Za-z0-9/._-]+$/.test(U)||!/^[A-Za-z0-9_-]{1,128}$/.test(Z))throw new R("vm_hands_probe_failed","proof directory path or nonce");Dq(U,K,K),Pq(U,448);let M=s(U).ino,F=n("/bin/bash",["-c",$.replaceAll(Xq,U).replaceAll(Oq,Z)],{cwd:"/",env:{PATH:"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},stdio:["ignore","pipe","ignore"]}),D="";F.stdout?.on("data",(C)=>{if(D.length<16384)D+=C.toString("utf8").slice(0,16384-D.length)});let v=await new Promise((C)=>{let V=setTimeout(()=>{N=!0,F.kill("SIGKILL"),C(124)},vq);F.once("error",()=>{clearTimeout(V),C(127)}),F.once("close",(E)=>{clearTimeout(V),C(E??1)})});return X("vm_hands.probe",{nonce_len:Z.length,exit_code:v}),{exitCode:v,markers:D,proofDirInode:M}}finally{if(!N)fq(U,{recursive:!0,force:!0})}},restatLayout(){let{session_root:Z,alias:$}=q.init.layout,Q="invalid";try{Bq(Z),Q="0:0:755"}catch{}let T=!1,U=-1;try{let N=s($);U=N.uid,T=Q==="0:0:755"&&$===L(Z,"repo")&&!N.isSymbolicLink()&&N.isDirectory()&&Aq($)===$&&N.uid===K}catch{}return{root_mode:Q,alias_ok:T,owner_uid:U}},installEnvironment(Z,$){let Q=G.get(Z);if(!Q)throw new R("environment_unavailable","no executor owns an environment");return Yq({root:q.root,operationId:Q.operationId,payload:$}).installed_revision},async stop(){if(a)clearInterval(a);I?.close(),await Promise.all([...G.keys()].map((Z)=>m(Z)))}};function o(){try{return p(L(z,S),{withFileTypes:!0}).filter((Z)=>Z.isDirectory()&&/^b-[0-9a-f-]{36}$/.test(Z.name)).map((Z)=>Z.name)}catch{return[]}}async function Rq(Z,$){let Q=new Set([...$].map((U)=>U.toLowerCase())),T=Wq();try{await Jq();let U=Date.now()+qq,N=new Set(o().filter((J)=>!Q.has(J.slice(2))).map((J)=>J.slice(2)));if(Z)N.add(Z.toLowerCase());let M=null;for(let J of N){let W=m(J).catch(()=>{return}),P=Y.get(J);if(P!==void 0)M=M===null?P:Math.min(M,P);if(t(L(g(J),"cgroup.events")))await d(g(J),U,"bind");await W}let F=[...Q].map((J)=>g(J).replace(/^\/sys\/fs\/cgroup/,"")),D=[z,L(z,S)].map((J)=>J.replace(/^\/sys\/fs\/cgroup/,"")),v=h.replace(/^\/sys\/fs\/cgroup/,""),C=(J)=>k(J,u)||F.some((W)=>k(J,W)),V=Qq(K).filter((J)=>!C(J));if(V.length)throw X("vm_hands.kill_survivors",{pids:V.slice(0,16),beside:Q.size}),new R("vm_hands_kill_unverified",`${V.length} payload-uid process(es) outside a live bind`);let E=(J)=>!C(J)&&!k(J,"/reason-vm-hands")&&!k(J,v)&&!D.some((W)=>xq(J,W));if(M!==null){let J=$q(M).filter((W)=>W!==process.pid&&E(W));if(J.length)throw X("vm_hands.kill_strays",{strays:J.slice(0,16).map((W)=>({pid:W})),beside:Q.size}),new R("vm_hands_kill_unverified",`${J.length} process(es) the run started survived it`)}for(let J of N)Y.delete(J),Nq(J)}finally{T()}}}function xq(q,z,K="/proc"){try{return A(L(K,String(q),"cgroup"),"utf8").split(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Uh as E}from"./vm-hands-entry-lite-cxs89wzv.js";async function Q(){let[{executeLocalOperation:G},{configureDesktopAccount:H},{configureWorkerSandbox:J}]=await Promise.all([import("./local-capabilities-
|
|
2
|
+
import{Uh as E}from"./vm-hands-entry-lite-cxs89wzv.js";async function Q(){let[{executeLocalOperation:G},{configureDesktopAccount:H},{configureWorkerSandbox:J}]=await Promise.all([import("./local-capabilities-aya670gj.js"),import("./desktop-account-emwzhj61.js"),import("./worker-sandbox-yt11b09s.js")]);J();let K=(process.geteuid?.()??0)!==0,z=new Map,y=(B)=>{try{process.send?.(B)}catch{}};process.on("message",(B)=>{let j=B;if(j?.t==="cancel"){z.get(j.id)?.abort();return}if(j?.t!=="op")return;if(!K){y({t:"done",id:j.id,completion:{status:"failed",error_code:"vm_hands_payload_account_unavailable"}});return}let F=new AbortController;z.set(j.id,F),G(j.state,j.claim,{worker:j.worker,signal:F.signal,emit:(q)=>{let{deliverySignal:N,...M}=q;y({t:"event",id:j.id,event:M})}}).then((q)=>y({t:"done",id:j.id,completion:q}),(q)=>y({t:"done",id:j.id,completion:{status:"failed",error_code:q&&typeof q==="object"&&"code"in q&&typeof q.code==="string"?q.code:"vm_hands_op_failed"}})).finally(()=>z.delete(j.id))}),process.on("disconnect",()=>process.exit(0)),await new Promise(()=>{})}export{Q as runVmHandsOpRunner};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{u as k,v as m,w as l}from"./vm-hands-entry-lite-tsd17dcd.js";import{_c as v}from"./vm-hands-entry-lite-t497ewn2.js";import"./vm-hands-entry-lite-psybjyay.js";import{Uh as F}from"./vm-hands-entry-lite-cxs89wzv.js";import{spawn as a}from"child_process";import{createHash as r}from"crypto";import{lstatSync as x,mkdirSync as s,readFileSync as i,statSync as t,writeFileSync as d}from"fs";var V="/run/reason-vm-hands",R="/run/reason-vm-hands/env",w="/home/runner",e=/^https:\/\/[a-z0-9.-]+(?::\d{1,5})?$/,O="/sys/fs/cgroup/reason-srt",S="/usr/local/bin/ara-srt-exec",jj=65536,qj=21600000;function Jj(Q,j="/run/ara-srt"){try{if((process.getuid?.()??-1)!==0)return;s(j,{recursive:!0,mode:448});let J=x(j);if(!J.isDirectory()||J.uid!==0||(J.mode&63)!==0){Q("srt_base_keyed_skipped",{reason:"socket_dir_unsafe"});return}d(`${j}/base-keyed`,`1
|
|
3
|
-
`,{mode:420}),Q("srt_base_keyed",{})}catch{Q("srt_base_keyed_skipped",{reason:"error"})}}function p(Q,j){let J=(K)=>{return j("srt_warm_skipped",{reason:K}),Promise.resolve()};if(typeof Q.srt_base_settings!=="string")return J("no_settings");let Z=Buffer.from(Q.srt_base_settings,"base64");if(Z.length===0||Z.length>jj||Z.toString("base64")!==Q.srt_base_settings)return J("settings_invalid");try{let K=x(O);if(!K.isDirectory()||K.uid!==0||(K.mode&18)!==0)return J("cgroup_unsafe");for(let[W,g]of[[S,!1],["/usr/local/bin",!0]]){let B=x(W);if((g?!B.isDirectory():!B.isFile())||B.uid!==0||(B.mode&18)!==0)return J("srt_exec_unsafe")}}catch{return J("cgroup_or_exec_missing")}if((process.getuid?.()??-1)!==0)return J("not_root");let z=performance.now(),X=r("sha256").update(Z).digest("hex"),N=`${V}/srt-base-settings.json`;try{d(N,Z,{mode:384,flag:"w"})}catch{return J("settings_write")}let H=a("/bin/sh",["-c",`echo $$ > ${O}/cgroup.procs || exit 125; exec "$@"`,"vm-hands-srt",S,"--settings",N,"--idle-ms",String(qj),"--","/bin/true"],{cwd:"/",env:{PATH:"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},stdio:"ignore"});return new Promise((K)=>{H.once("error",()=>{j("srt_warm_failed",{reason:"spawn"}),K()}),H.once("close",(W)=>{j(W===0?"srt_warm_done":"srt_warm_failed",{exit_code:W,warm_ms:Math.round(performance.now()-z),settings_sha256:X}),K()})})}var y=3000;function Wj(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let j=Q,J=j.layout,Z=j.device_key,z=j.credential;return typeof j.workspace_id==="string"&&Number.isSafeInteger(j.instance_generation)&&typeof j.api_origin==="string"&&e.test(j.api_origin)&&typeof j.manifest_digest==="string"&&!!z&&typeof z.key_id==="string"&&Number.isSafeInteger(z.expires_at_ms)&&typeof z.signature==="string"&&!!J&&typeof J.session_root==="string"&&typeof J.alias==="string"&&Number.isSafeInteger(J.payload_uid)&&typeof J.kind==="string"&&!!Z&&typeof Z.pkcs8==="string"&&typeof Z.spki==="string"?j:null}function u(Q){s(Q,{recursive:!0,mode:448});let j=t(Q);if(!j.isDirectory()||(j.mode&63)!==0||j.uid!==(process.getuid?.()??-1))throw Error(`vm_hands_runtime_directory_unsafe: ${Q}`)}async function Qj(Q){let[{CLI_VERSION:j},J,Z,z]=await Promise.all([import("./version-
|
|
4
|
-
`)){let J=j.split(":");if(J.length>=4&&Number(J[2])===Q&&/^\d+$/.test(J[3]??"")&&Number(J[3])>0)return Number(J[3])}throw Error("vm_hands_payload_account_unavailable")}function Xj(Q,j){let J=j.owner;if(!J||typeof J.organization_id!=="string"||typeof J.device_id!=="string"||typeof j.root_id!=="string")return null;return{version:4,apiOrigin:Q.api_origin,orgId:J.organization_id,deviceId:J.device_id,devicePublicKey:"",displayName:"vm-hands",registeredAt:new Date(0).toISOString(),handsSlots:1,roots:[{id:j.root_id,label:"workspace",path:w,pathFingerprint:"0".repeat(64),permissions:{read:!0,write:!0,execute:!0,discover_environment:!0,expose_mcp:!1}}]}}async function Hj(Q,j){u(V),u(R),Jj(j);let J=p(Q,j),Z=!1,z=async()=>{if(!await Promise.race([J.then(()=>!0),new Promise(($)=>setTimeout(()=>$(!1),y).unref?.())]))Z=!0,j("srt_warm_late",{wait_ms:y})},[{configureDesktopAccount:X},{configureWorkerSandbox:N}]=await Promise.all([import("./desktop-account-emwzhj61.js"),import("./worker-sandbox-yt11b09s.js")]);N();try{X({value:String(Q.layout.payload_uid)})}catch{j("payload_account_unavailable"),await new Promise(()=>{setInterval(()=>{return},1073741824)})}let H=new AbortController;for(let q of["SIGTERM","SIGINT"])process.on(q,()=>H.abort());let K=new Map,W,g=new Promise((q)=>{W=q}),B=g.then(()=>import("./vm-hands-executor-
|
|
3
|
+
`,{mode:420}),Q("srt_base_keyed",{})}catch{Q("srt_base_keyed_skipped",{reason:"error"})}}function p(Q,j){let J=(K)=>{return j("srt_warm_skipped",{reason:K}),Promise.resolve()};if(typeof Q.srt_base_settings!=="string")return J("no_settings");let Z=Buffer.from(Q.srt_base_settings,"base64");if(Z.length===0||Z.length>jj||Z.toString("base64")!==Q.srt_base_settings)return J("settings_invalid");try{let K=x(O);if(!K.isDirectory()||K.uid!==0||(K.mode&18)!==0)return J("cgroup_unsafe");for(let[W,g]of[[S,!1],["/usr/local/bin",!0]]){let B=x(W);if((g?!B.isDirectory():!B.isFile())||B.uid!==0||(B.mode&18)!==0)return J("srt_exec_unsafe")}}catch{return J("cgroup_or_exec_missing")}if((process.getuid?.()??-1)!==0)return J("not_root");let z=performance.now(),X=r("sha256").update(Z).digest("hex"),N=`${V}/srt-base-settings.json`;try{d(N,Z,{mode:384,flag:"w"})}catch{return J("settings_write")}let H=a("/bin/sh",["-c",`echo $$ > ${O}/cgroup.procs || exit 125; exec "$@"`,"vm-hands-srt",S,"--settings",N,"--idle-ms",String(qj),"--","/bin/true"],{cwd:"/",env:{PATH:"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},stdio:"ignore"});return new Promise((K)=>{H.once("error",()=>{j("srt_warm_failed",{reason:"spawn"}),K()}),H.once("close",(W)=>{j(W===0?"srt_warm_done":"srt_warm_failed",{exit_code:W,warm_ms:Math.round(performance.now()-z),settings_sha256:X}),K()})})}var y=3000;function Wj(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let j=Q,J=j.layout,Z=j.device_key,z=j.credential;return typeof j.workspace_id==="string"&&Number.isSafeInteger(j.instance_generation)&&typeof j.api_origin==="string"&&e.test(j.api_origin)&&typeof j.manifest_digest==="string"&&!!z&&typeof z.key_id==="string"&&Number.isSafeInteger(z.expires_at_ms)&&typeof z.signature==="string"&&!!J&&typeof J.session_root==="string"&&typeof J.alias==="string"&&Number.isSafeInteger(J.payload_uid)&&typeof J.kind==="string"&&!!Z&&typeof Z.pkcs8==="string"&&typeof Z.spki==="string"?j:null}function u(Q){s(Q,{recursive:!0,mode:448});let j=t(Q);if(!j.isDirectory()||(j.mode&63)!==0||j.uid!==(process.getuid?.()??-1))throw Error(`vm_hands_runtime_directory_unsafe: ${Q}`)}async function Qj(Q){let[{CLI_VERSION:j},J,Z,z]=await Promise.all([import("./version-rkf1f8kn.js"),import("./hands-worker-source-ws7x23xe.js"),import("./network-contract-bv7mj5he.js"),import("./device-workspace-xnyb7zp2.js")]),{REASON_HANDS_PROTOCOL_VERSION:X}=await import("./reason-hands-protocol-5zt3ys5t.js");return{reason_runtime_version:j,bridge_version:j,protocol_version:v,execution_eligible:!0,instance_generation:Q.instance_generation,capabilities:{supported_operations:["hands.connect"],hands_worker_artifact_sha256:J.REASON_HANDS_WORKER_ARTIFACT_SHA256,hands_worker_entrypoint:J.REASON_HANDS_WORKER_ENTRYPOINT,hands_slots:1,max_payload_bytes:Z.LOCAL_OPERATION_MAX_BYTES,max_result_bytes:Z.LOCAL_OPERATION_MAX_BYTES,operation_constraints:{"hands.connect":{ready:!0,execution_mode:"host",transport:"wss_relay",worker:"ara_hands",slots:1,session_group:Z.HANDS_SESSION_GROUP,worker_version:J.REASON_HANDS_WORKER_VERSION,protocol_version:X,worker_artifact_sha256:J.REASON_HANDS_WORKER_ARTIFACT_SHA256,worker_entrypoint:J.REASON_HANDS_WORKER_ENTRYPOINT,policy_mode:"full_access",policy_version:1,workspace_base:z.REASON_WORKSPACE_BASE,workspace_layout:z.SESSION_WORKSPACE_LAYOUT,browser_state:"optional_headless",desktop:!1,max_session_ms:43200000,environment_delivery:Z.HANDS_ENVIRONMENT_DELIVERY,[Z.HANDS_ENVIRONMENT_AT_CLAIM_KEY]:Z.HANDS_ENVIRONMENT_AT_CLAIM,[Z.HANDS_CLOUD_ACCESS_KEY]:Z.HANDS_CLOUD_ACCESS,[Z.HANDS_LARGE_ENVIRONMENT_KEY]:Z.HANDS_LARGE_ENVIRONMENT,[Z.HANDS_CONFINEMENT_KEY]:Z.HANDS_CONFINEMENT,[Z.HANDS_JOBS_USER_KEY]:Z.HANDS_JOBS_USER,vm_hands:"v1"}}}}}var C=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.list","ports.list","pty.start","jobs.control","automation.call.v1"],Zj=new Set(["pty.start","jobs.control"]);function $j(Q,j){let J=j([{id:"vm-hands",label:"workspace",path:w,pathFingerprint:"0".repeat(64),permissions:{read:!0,write:!0,execute:!0,discover_environment:!0,expose_mcp:!1}}],{worker:{executionMode:"unsandboxed",readiness:Object.fromEntries(C.map((X)=>[X,!0]))}}),Z=Q.capabilities,z={...Z.operation_constraints};for(let X of C)z[X]={...J.operation_constraints?.[X]??{},ready:!0,execution_mode:J.operation_constraints?.[X]?.execution_mode??"host"};return{...Q,capabilities:{...Z,supported_operations:["hands.connect",...C],operation_constraints:z}}}function zj(Q){for(let j of i("/etc/passwd","utf8").split(`
|
|
4
|
+
`)){let J=j.split(":");if(J.length>=4&&Number(J[2])===Q&&/^\d+$/.test(J[3]??"")&&Number(J[3])>0)return Number(J[3])}throw Error("vm_hands_payload_account_unavailable")}function Xj(Q,j){let J=j.owner;if(!J||typeof J.organization_id!=="string"||typeof J.device_id!=="string"||typeof j.root_id!=="string")return null;return{version:4,apiOrigin:Q.api_origin,orgId:J.organization_id,deviceId:J.device_id,devicePublicKey:"",displayName:"vm-hands",registeredAt:new Date(0).toISOString(),handsSlots:1,roots:[{id:j.root_id,label:"workspace",path:w,pathFingerprint:"0".repeat(64),permissions:{read:!0,write:!0,execute:!0,discover_environment:!0,expose_mcp:!1}}]}}async function Hj(Q,j){u(V),u(R),Jj(j);let J=p(Q,j),Z=!1,z=async()=>{if(!await Promise.race([J.then(()=>!0),new Promise(($)=>setTimeout(()=>$(!1),y).unref?.())]))Z=!0,j("srt_warm_late",{wait_ms:y})},[{configureDesktopAccount:X},{configureWorkerSandbox:N}]=await Promise.all([import("./desktop-account-emwzhj61.js"),import("./worker-sandbox-yt11b09s.js")]);N();try{X({value:String(Q.layout.payload_uid)})}catch{j("payload_account_unavailable"),await new Promise(()=>{setInterval(()=>{return},1073741824)})}let H=new AbortController;for(let q of["SIGTERM","SIGINT"])process.on(q,()=>H.abort());let K=new Map,W,g=new Promise((q)=>{W=q}),B=g.then(()=>import("./vm-hands-executor-bjswhqrs.js")).then(({createVmHandsExecutor:q})=>{let $=q({init:Q,root:w,runtimeDirectory:V,apiOrigin:Q.api_origin,prespawn:!0,onSrtReset:()=>{Z=!1,J=p(Q,j)},srtWarmLate:()=>Z,forward:(U,G,M)=>K.get(U)?.(G,M)??Promise.reject(Error("vm_hands_not_bound")),log:(U,G)=>j(U,G)});return j("executor_loaded"),$}),A=(q)=>async(...$)=>(await B)[q](...$),D=null;B.then((q)=>{D=($)=>q.executorExited($)});let L={startExecutor:async(...q)=>{return await z(),A("startExecutor")(...q)},killAndVerifyPayload:A("killAndVerifyPayload"),runProbe:async(...q)=>{return await z(),A("runProbe")(...q)},restatLayout:()=>{throw Error("replaced below")},installEnvironment:()=>{throw Error("replaced below")},executorExited:(q)=>D?D(q):new Promise(()=>{}),takeSrtFallbacks:()=>null};B.then((q)=>{L.restatLayout=()=>q.restatLayout(),L.installEnvironment=($,U)=>q.installEnvironment($,U),L.freezeBind=($)=>q.freezeBind($),L.takeSrtFallbacks=()=>q.takeSrtFallbacks?.()??null});let c=await k(Q),o=new m(Q,c,L,{envRoot:R}),h=Qj(Q),b=null,n=Promise.all([h,import("./local-capabilities-aya670gj.js")]).then(([q,$])=>{b=$j(q,$.capabilityInventoryForRoots),j("device_ops_loaded")}).catch((q)=>j("device_ops_unavailable",{error:q instanceof Error?q.name:"error"})),T=g.then(()=>import("./vm-hands-executor-bjswhqrs.js")).then(({createVmHandsOpRunners:q,vmHandsBindCgroup:$,VM_HANDS_PAYLOAD_CGROUP:U})=>q({payloadUid:Q.layout.payload_uid,payloadGid:zj(Q.layout.payload_uid),bindCgroup:(G)=>$(U,G),log:(G,M)=>j(G,M)})).catch(()=>null);T.then((q)=>q?.warm("person")),j("agent_ready"),await l({apiOrigin:Q.api_origin,agent:o,signal:H.signal,heartbeat:async()=>b??await h,executeOp:async({kind:q,claim:$,bindId:U,signal:G,emit:M})=>{let f=Xj(Q,$);if(!f)return{status:"failed",error_code:"vm_hands_bind_invalid"};let E={executionMode:"unsandboxed",runtimeDirectory:V,readiness:Object.fromEntries(C.map((Y)=>[Y,!0]))},_=(Y)=>{let P=typeof Y.kind==="string"?Y.kind:"";if(P)M({kind:P,...Y.data&&typeof Y.data==="object"?{data:Y.data}:{}})};if($.capability==="exec.full"&&q!=="person")return{status:"failed",error_code:"capability_not_granted"};if($.capability==="automation.call.v1"&&q!=="model")return{status:"failed",error_code:"capability_not_granted"};if(Zj.has(String($.capability))){let{executeLocalOperation:Y}=await import("./local-capabilities-aya670gj.js");return Y(f,$,{worker:E,signal:G,emit:(P)=>_(P)})}let I=await T;if(!I)return{status:"failed",error_code:"vm_hands_payload_account_unavailable"};return I.run(q,{id:String($.attempt_id),claim:$,state:f,worker:E},_,G,U)},readyData:({launchId:q})=>({executor_launch_id:q}),log:(q,$)=>{if(q==="vm_hands.registered"||q==="vm_hands.reconnected")W();j(q,$)},onTurn:(q,$)=>{if($)K.set(q,$);else K.delete(q)}}),await(await B).stop(),(await T)?.stop()}export{p as startBaseSrtServer,Hj as runVmHands,Wj as parseVmHandsInit,Qj as heartbeatBody,Jj as enableBaseKeyedSrt};
|