@reason-machines/cli-linux-arm64-musl 0.2.311 → 0.2.313
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-jggevd6v.js → connect-cli-dqghjqd4.js} +1 -1
- package/bin/vm-hands/{local-automation-f745tkm7.js → local-automation-eb60mapm.js} +1 -1
- package/bin/vm-hands/{local-capabilities-ebn1v8ek.js → local-capabilities-6rr3bahs.js} +1 -1
- package/bin/vm-hands/{local-display-session-h4zs144x.js → local-display-session-vbyhrk1t.js} +1 -1
- package/bin/vm-hands/{permissions-wsbngq8n.js → permissions-8e309cm8.js} +1 -1
- package/bin/vm-hands/{status-7ztp566x.js → status-nac4r75q.js} +9 -9
- package/bin/vm-hands/{version-h34tnfqq.js → version-c4jz97dy.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-wm1x5t80.js → vm-hands-entry-lite-8gr872ee.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-7zaerpzt.js → vm-hands-entry-lite-bsfm2m38.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-qwf40mek.js → vm-hands-entry-lite-erxpqz9e.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-qdvts5kj.js → vm-hands-entry-lite-ncty87q3.js} +15 -15
- package/bin/vm-hands/{vm-hands-entry-lite-hzk6qcbz.js → vm-hands-entry-lite-nqgg6v5n.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-8p9wtv7e.js → vm-hands-entry-lite-pct56639.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-sjjefpda.js → vm-hands-entry-lite-qdcp5vf4.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-naxss5d5.js → vm-hands-entry-lite-sg20hwxb.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-qxzskxaz.js → vm-hands-executor-fwq7gd0d.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-kae28wpv.js → vm-hands-op-runner-q0z9bqyk.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-0wsbw397.js → vm-hands-runtime-0h74s3jy.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-qdcp5vf4.js";import"./vm-hands-entry-lite-bswnp5ve.js";import"./vm-hands-entry-lite-nqgg6v5n.js";import"./vm-hands-entry-lite-sg20hwxb.js";import"./vm-hands-entry-lite-rrk5g62b.js";import"./vm-hands-entry-lite-ya1a2eep.js";import"./vm-hands-entry-lite-qvrnx0vk.js";import"./vm-hands-entry-lite-n07kxrd1.js";import"./vm-hands-entry-lite-0ergg2ky.js";import"./vm-hands-entry-lite-ncty87q3.js";import"./vm-hands-entry-lite-8st97h7b.js";import"./vm-hands-entry-lite-q6fshf3h.js";import"./vm-hands-entry-lite-bsfm2m38.js";import"./vm-hands-entry-lite-pf1ft65e.js";import"./vm-hands-entry-lite-q2pb31vh.js";import"./vm-hands-entry-lite-8gr872ee.js";import"./vm-hands-entry-lite-6j2yaa4n.js";import"./vm-hands-entry-lite-7k65s010.js";import"./vm-hands-entry-lite-em388nee.js";import"./vm-hands-entry-lite-yp315y25.js";import"./vm-hands-entry-lite-pct56639.js";import"./vm-hands-entry-lite-erxpqz9e.js";import"./vm-hands-entry-lite-wgx7z7gt.js";import"./vm-hands-entry-lite-xsq25kmd.js";import"./vm-hands-entry-lite-hf0mk7vd.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{Cc as a,Dc as b,Ec as c,Fc as d,Gc as e,Hc as f,Ic as g,Jc as h,Kc as i,Lc as j,Mc as k,Nc as l}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Cc as a,Dc as b,Ec as c,Fc as d,Gc as e,Hc as f,Ic as g,Jc as h,Kc as i,Lc as j,Mc as k,Nc as l}from"./vm-hands-entry-lite-ncty87q3.js";import"./vm-hands-entry-lite-8st97h7b.js";import"./vm-hands-entry-lite-q6fshf3h.js";import"./vm-hands-entry-lite-bsfm2m38.js";import"./vm-hands-entry-lite-pf1ft65e.js";import"./vm-hands-entry-lite-q2pb31vh.js";import"./vm-hands-entry-lite-8gr872ee.js";import"./vm-hands-entry-lite-6j2yaa4n.js";import"./vm-hands-entry-lite-7k65s010.js";import"./vm-hands-entry-lite-em388nee.js";import"./vm-hands-entry-lite-yp315y25.js";import"./vm-hands-entry-lite-pct56639.js";import"./vm-hands-entry-lite-erxpqz9e.js";import"./vm-hands-entry-lite-wgx7z7gt.js";import"./vm-hands-entry-lite-xsq25kmd.js";import"./vm-hands-entry-lite-hf0mk7vd.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-nqgg6v5n.js";import"./vm-hands-entry-lite-sg20hwxb.js";import"./vm-hands-entry-lite-rrk5g62b.js";import"./vm-hands-entry-lite-ya1a2eep.js";import"./vm-hands-entry-lite-qvrnx0vk.js";import{Zb as b}from"./vm-hands-entry-lite-n07kxrd1.js";import"./vm-hands-entry-lite-0ergg2ky.js";import"./vm-hands-entry-lite-ncty87q3.js";import"./vm-hands-entry-lite-8st97h7b.js";import"./vm-hands-entry-lite-q6fshf3h.js";import"./vm-hands-entry-lite-bsfm2m38.js";import"./vm-hands-entry-lite-pf1ft65e.js";import"./vm-hands-entry-lite-q2pb31vh.js";import"./vm-hands-entry-lite-8gr872ee.js";import"./vm-hands-entry-lite-6j2yaa4n.js";import"./vm-hands-entry-lite-7k65s010.js";import"./vm-hands-entry-lite-em388nee.js";import"./vm-hands-entry-lite-yp315y25.js";import"./vm-hands-entry-lite-pct56639.js";import"./vm-hands-entry-lite-erxpqz9e.js";import"./vm-hands-entry-lite-wgx7z7gt.js";import{Kh as a}from"./vm-hands-entry-lite-xsq25kmd.js";import"./vm-hands-entry-lite-hf0mk7vd.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-h4zs144x.js → local-display-session-vbyhrk1t.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ae as h,te as a,ue as b,ve as c,we as d,xe as e,ye as f,ze as g}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ae as h,te as a,ue as b,ve as c,we as d,xe as e,ye as f,ze as g}from"./vm-hands-entry-lite-bsfm2m38.js";import"./vm-hands-entry-lite-pf1ft65e.js";import"./vm-hands-entry-lite-q2pb31vh.js";import"./vm-hands-entry-lite-8gr872ee.js";import"./vm-hands-entry-lite-6j2yaa4n.js";import"./vm-hands-entry-lite-7k65s010.js";import"./vm-hands-entry-lite-em388nee.js";import"./vm-hands-entry-lite-yp315y25.js";import"./vm-hands-entry-lite-pct56639.js";import"./vm-hands-entry-lite-erxpqz9e.js";import"./vm-hands-entry-lite-wgx7z7gt.js";import"./vm-hands-entry-lite-xsq25kmd.js";import"./vm-hands-entry-lite-hf0mk7vd.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 j,rg as a,sg as b,tg as c,ug as d,vg as e,wg as f,xg as g,yg as h,zg as i}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ag as j,rg as a,sg as b,tg as c,ug as d,vg as e,wg as f,xg as g,yg as h,zg as i}from"./vm-hands-entry-lite-8gr872ee.js";import"./vm-hands-entry-lite-6j2yaa4n.js";import"./vm-hands-entry-lite-em388nee.js";import"./vm-hands-entry-lite-yp315y25.js";import"./vm-hands-entry-lite-pct56639.js";import"./vm-hands-entry-lite-erxpqz9e.js";import"./vm-hands-entry-lite-xsq25kmd.js";import"./vm-hands-entry-lite-hf0mk7vd.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-qdcp5vf4.js";import"./vm-hands-entry-lite-bswnp5ve.js";import"./vm-hands-entry-lite-nqgg6v5n.js";import"./vm-hands-entry-lite-sg20hwxb.js";import"./vm-hands-entry-lite-rrk5g62b.js";import"./vm-hands-entry-lite-ya1a2eep.js";import"./vm-hands-entry-lite-qvrnx0vk.js";import"./vm-hands-entry-lite-n07kxrd1.js";import"./vm-hands-entry-lite-0ergg2ky.js";import{lc as jq}from"./vm-hands-entry-lite-ncty87q3.js";import"./vm-hands-entry-lite-8st97h7b.js";import{ae as G}from"./vm-hands-entry-lite-q6fshf3h.js";import"./vm-hands-entry-lite-bsfm2m38.js";import{Ee as H,Fe as u,Ge as s,bf as Qq}from"./vm-hands-entry-lite-pf1ft65e.js";import"./vm-hands-entry-lite-q2pb31vh.js";import"./vm-hands-entry-lite-8gr872ee.js";import"./vm-hands-entry-lite-6j2yaa4n.js";import"./vm-hands-entry-lite-7k65s010.js";import{_g as l}from"./vm-hands-entry-lite-em388nee.js";import"./vm-hands-entry-lite-yp315y25.js";import{yh as R}from"./vm-hands-entry-lite-pct56639.js";import"./vm-hands-entry-lite-erxpqz9e.js";import"./vm-hands-entry-lite-wgx7z7gt.js";import"./vm-hands-entry-lite-xsq25kmd.js";import{Oh as $q}from"./vm-hands-entry-lite-hf0mk7vd.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
|
---
|
|
@@ -44,7 +44,7 @@ Base URL: \`https://api.reasonmachines.com/v3\`
|
|
|
44
44
|
`;function m(q){return vq(q,".agents","skills","ara","SKILL.md")}function i(q){let J=m(q);return Tq(J)&&Uq(J,"utf8")===Eq}var p=["codex","claude","cursor"],r={codex:"Codex",claude:"Claude Code",cursor:"Cursor"};function pq(q,J=process.env){let x=J.PATH??"";for(let Y of x.split(gq)){if(!Y)continue;try{return _q(T(Y,q),wq.X_OK),!0}catch{}}return!1}function dq(){return{exists:pq,run(q,J,x={}){let Y=x.interactive===!0,X=Mq(q,J,{encoding:"utf8",env:process.env,stdio:Y?"inherit":"pipe"});return{status:X.status??1,stdout:Y?"":X.stdout??"",stderr:Y?X.error?.message??"":`${X.stderr??""}${X.error?`${X.error.message}
|
|
45
45
|
`:""}`}}}}function O(q){return`${q.stdout}
|
|
46
46
|
${q.stderr}`}function k(q){return q.status===0}function I(q,J,x,Y={}){let X=q.run(J,x,Y);if(k(X))return X;let $=O(X).trim();throw Error(`${J} ${x.join(" ")} failed${$?`: ${$}`:` with exit code ${X.status}`}`)}function uq(q=process.env){return s(H({env:q}))}function d(q,J){return q.split(/\s+/).some((x)=>e(x,J))}function w(q){return T(q,".cursor","mcp.json")}function t(q){if(!L(q))return{};try{let J=JSON.parse(fq(q,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))throw Error("top-level value must be an object");return J}catch(J){let x=J instanceof Error?J.message:String(J);throw Error(`Cursor MCP config at ${q} is invalid; refusing to overwrite it (${x})`)}}function lq(q,J){Lq(mq(q),{recursive:!0,mode:448});let x=`${q}.ara-${process.pid}.tmp`;hq(x,`${JSON.stringify(J,null,2)}
|
|
47
|
-
`,{mode:384}),Sq(x,q)}function e(q,J){if(typeof q!=="string")return!1;if(q===J)return!0;try{let x=new URL(q);return["https://api.ara.so","https://api-staging.ara.so","https://api.reasonmachines.ai","https://staging-api.reasonmachines.ai","https://api.reasonmachines.com","https://staging-api.reasonmachines.com"].includes(x.origin)&&!x.username&&!x.password&&x.pathname==="/mcp/ara"&&!x.search&&!x.hash}catch{return!1}}function oq(q,J){let x=q.mcpServers?.ara;return Boolean(x&&typeof x==="object"&&!Array.isArray(x)&&e(x.url,J))}class f{runner;home;mcpUrl;constructor(q=dq(),J=Cq(),x=uq()){this.runner=q;this.home=J;this.mcpUrl=x}isAvailable(q){if(q==="codex")return this.runner.exists("codex");if(q==="claude")return this.runner.exists("claude");return this.runner.exists("cursor")||L("/Applications/Cursor.app")||L(T(this.home,"Applications","Cursor.app"))||L(w(this.home))}availableClients(){return p.filter((q)=>this.isAvailable(q))}installationPath(q){if(q==="cursor")return w(this.home);if(q==="codex")return T(this.home,".codex","plugins","cache","ara");return T(this.home,".claude","plugins","cache","ara")}sharedSkillStatus(){return{installed:i(this.home),path:m(this.home)}}status(q){let J=r[q];if(!this.isAvailable(q))return{id:q,label:J,available:!1,installed:!1,connection:null,detail:"Client not detected",legacyInstallations:[]};if(q==="cursor"){let
|
|
47
|
+
`,{mode:384}),Sq(x,q)}function e(q,J){if(typeof q!=="string")return!1;if(q===J)return!0;try{let x=new URL(q);return["https://api.ara.so","https://api-staging.ara.so","https://api.reasonmachines.ai","https://staging-api.reasonmachines.ai","https://api.reasonmachines.com","https://staging-api.reasonmachines.com"].includes(x.origin)&&!x.username&&!x.password&&x.pathname==="/mcp/ara"&&!x.search&&!x.hash}catch{return!1}}function oq(q,J){let x=q.mcpServers?.ara;return Boolean(x&&typeof x==="object"&&!Array.isArray(x)&&e(x.url,J))}class f{runner;home;mcpUrl;constructor(q=dq(),J=Cq(),x=uq()){this.runner=q;this.home=J;this.mcpUrl=x}isAvailable(q){if(q==="codex")return this.runner.exists("codex");if(q==="claude")return this.runner.exists("claude");return this.runner.exists("cursor")||L("/Applications/Cursor.app")||L(T(this.home,"Applications","Cursor.app"))||L(w(this.home))}availableClients(){return p.filter((q)=>this.isAvailable(q))}installationPath(q){if(q==="cursor")return w(this.home);if(q==="codex")return T(this.home,".codex","plugins","cache","ara");return T(this.home,".claude","plugins","cache","ara")}sharedSkillStatus(){return{installed:i(this.home),path:m(this.home)}}status(q){let J=r[q];if(!this.isAvailable(q))return{id:q,label:J,available:!1,installed:!1,connection:null,detail:"Client not detected",legacyInstallations:[]};if(q==="cursor"){let B=w(this.home),D=oq(t(B),this.mcpUrl);return{id:q,label:J,available:!0,installed:D,connection:D?"configured":null,detail:D?`Retired Reason MCP configuration in ${B}`:`No retired Reason MCP configuration in ${B}`,legacyInstallations:[]}}if(q==="codex"){let B=this.runner.run("codex",["plugin","list"]);if(!(k(B)&&O(B).includes("ara@ara")))return{id:q,label:J,available:!0,installed:!1,connection:null,detail:"No retired Reason plugin installed",legacyInstallations:[]};let P=this.runner.run("codex",["mcp","list"]),Q=O(P).split(/\r?\n/).find((E)=>E.trimStart().startsWith("ara ")&&d(E,this.mcpUrl)),h=k(P)&&Boolean(Q),v=!k(P)?"error":Q?.includes("Not logged in")?"not_logged_in":Q?.includes("OAuth")?"oauth":Q?"configured":"unknown";return{id:q,label:J,available:!0,installed:h,connection:v,detail:Q?.trim()||"The retired Reason plugin is installed but has no verified retired MCP registration",legacyInstallations:[]}}let x=this.runner.run("claude",["plugin","list"]),Y=O(x),X=k(x)&&Y.includes("ara@ara"),$=k(x)&&Y.includes("ara-handoff@ara");if(!X&&!$)return{id:q,label:J,available:!0,installed:!1,connection:null,detail:"No retired Reason plugin installed",legacyInstallations:[]};let W=this.runner.run("claude",["mcp","list"]),K=O(W),j=K.split(/\r?\n/).find((B)=>B.includes("plugin:ara:ara")&&d(B,this.mcpUrl)),A=K.split(/\r?\n/).find((B)=>B.includes("plugin:ara-handoff:ara")&&d(B,this.mcpUrl)),U=k(W)&&Boolean(j),F=k(W)&&A?["ara-handoff@ara"]:[],S=!k(W)?"error":j?.includes("Connected")?"connected":j?.includes("Failed")?"error":j?"configured":"unknown";return{id:q,label:J,available:!0,installed:U,connection:S,detail:j?.trim()||"The retired Reason plugin is installed but has no verified retired MCP registration",legacyInstallations:F}}statuses(){return p.map((q)=>this.status(q))}logout(q){let J=this.status(q);if(!J.available||!J.installed)return`${J.label}: not connected`;if(q==="cursor")return this.uninstall("cursor").replace("removed retired Reason","signed out and removed retired Reason");if(q==="codex")return I(this.runner,"codex",["mcp","logout","ara"]),"Codex: signed out of Reason";return I(this.runner,"claude",["mcp","logout","plugin:ara:ara"]),"Claude Code: signed out of Reason"}uninstall(q){let J=this.status(q);if(!J.available||!J.installed)return`${J.label}: Reason is not installed`;if(q==="cursor"){let x=w(this.home),Y=t(x),X={...Y.mcpServers??{}};return delete X.ara,Y.mcpServers=X,lq(x,Y),`Cursor: removed retired Reason MCP from ${x}`}if(q==="codex")return I(this.runner,"codex",["plugin","remove","ara@ara"]),"Codex: removed retired ara@ara";return I(this.runner,"claude",["plugin","uninstall","ara@ara","--scope","user"]),"Claude Code: removed retired ara@ara"}removeLegacyClaudePlugin(){if(!this.runner.exists("claude"))return"Claude Code: not installed";if(!this.status("claude").legacyInstallations.includes("ara-handoff@ara"))return"Claude Code: no legacy Reason plugin found";return I(this.runner,"claude",["plugin","uninstall","ara-handoff@ara","--scope","user"]),"Claude Code: removed obsolete ara-handoff@ara"}removeRetiredInstallations(){let q=[],J=[];for(let x of p){let Y;try{Y=this.status(x)}catch(X){J.push(`${r[x]}: ${X instanceof Error?X.message:String(X)}`);continue}if(Y.installed){if(x!=="cursor")try{q.push(this.logout(x))}catch(X){J.push(`${Y.label}: ${X instanceof Error?X.message:String(X)}`)}try{q.push(this.uninstall(x))}catch(X){J.push(`${Y.label}: ${X instanceof Error?X.message:String(X)}`)}}if(x==="claude"&&Y.legacyInstallations.includes("ara-handoff@ara"))try{q.push(this.removeLegacyClaudePlugin())}catch(X){J.push(`${Y.label}: ${X instanceof Error?X.message:String(X)}`)}}if(q.length===0&&J.length===0)q.push("No retired Reason MCP configuration found.");return{messages:q,failures:J}}}function n(q){return`claude mcp add --transport http reason ${q}`}function a(q){return`codex mcp add reason --url ${q}
|
|
48
48
|
codex mcp login reason`}var P3=n("https://mcp.reasonmachines.com/mcp"),y3=a("https://mcp.reasonmachines.com/mcp"),R3=`https://claude.ai/settings/connectors?add=custom&url=${encodeURIComponent("https://mcp.reasonmachines.com/mcp")}`,N3=`https://cursor.com/install-mcp?name=reason&config=${encodeURIComponent(btoa(JSON.stringify({url:"https://mcp.reasonmachines.com/mcp"})))}`;var cq="https://github.com/reason-machines/reason-plugins",E3=`Connect a coding agent to Reason over MCP
|
|
49
49
|
|
|
50
50
|
Usage:
|
|
@@ -52,7 +52,7 @@ Usage:
|
|
|
52
52
|
reason mcp uninstall Remove only this machine's registrations of the earlier, retired server
|
|
53
53
|
|
|
54
54
|
Plugins for Claude Code and Codex: ${cq}
|
|
55
|
-
`;function qq(q){if(!q.available)return"not detected";if(q.installed||q.legacyInstallations.length>0)return"retired configuration";return"not installed"}function iq(q,J){let x=J.toLowerCase();if(q==="codex")return x.includes("codex");if(q==="claude")return x.includes("claude");return x.includes("cursor")}function xq(q,J){return(J.mcp_connections??[]).filter((Y)=>iq(q.id,Y.client_name)).flatMap((Y)=>Y.last_used_at?[Y.last_used_at]:[]).sort().at(-1)??null}function Jq(q,J=new Date){if(!q)return"never";let x=Date.parse(q);if(!Number.isFinite(x))return"never";let Y=Math.max(0,Math.floor((J.getTime()-x)/1000));if(Y<45)return"just now";let X=Math.floor(Y/60);if(X<60)return`${X} ${X===1?"minute":"minutes"} ago`;let $=Math.floor(X/60);if($<24)return`${$} ${$===1?"hour":"hours"} ago`;let
|
|
55
|
+
`;function qq(q){if(!q.available)return"not detected";if(q.installed||q.legacyInstallations.length>0)return"retired configuration";return"not installed"}function iq(q,J){let x=J.toLowerCase();if(q==="codex")return x.includes("codex");if(q==="claude")return x.includes("claude");return x.includes("cursor")}function xq(q,J){return(J.mcp_connections??[]).filter((Y)=>iq(q.id,Y.client_name)).flatMap((Y)=>Y.last_used_at?[Y.last_used_at]:[]).sort().at(-1)??null}function Jq(q,J=new Date){if(!q)return"never";let x=Date.parse(q);if(!Number.isFinite(x))return"never";let Y=Math.max(0,Math.floor((J.getTime()-x)/1000));if(Y<45)return"just now";let X=Math.floor(Y/60);if(X<60)return`${X} ${X===1?"minute":"minutes"} ago`;let $=Math.floor(X/60);if($<24)return`${$} ${$===1?"hour":"hours"} ago`;let W=Math.floor($/24);return`${W} ${W===1?"day":"days"} ago`}function Xq(q){let J=q.name?.trim(),x=q.email?.trim();if(J&&x)return`${J} (${x})`;return J||x||q.id||"Reason user"}function Yq(q){let J=q.name?.trim(),x=q.slug?.trim();if(J&&x)return`${J} (${x})`;return J||x||q.id}var rq=G.enum(["granted","not_granted","unknown"]),Zq=G.object({status:rq,checkedAt:G.number().finite(),executablePath:G.string().min(1)});var J3=`Reason status
|
|
56
56
|
|
|
57
57
|
Usage:
|
|
58
58
|
reason status [--json]
|
|
@@ -62,15 +62,15 @@ computer's connection (\`reason connect\`) and the workspaces it serves, any
|
|
|
62
62
|
retired MCP configuration that can be cleaned up, and automatic updates.
|
|
63
63
|
`,X3=5000,Y3=300000,Z3=G.object({version:G.literal(1),key:G.string(),at:G.number(),self:G.object({principal_type:G.string(),user_id:G.string().optional(),user_name:G.string().nullish(),email:G.string().nullish(),org_id:G.string(),organization_name:G.string().nullish(),organization_slug:G.string().nullish(),mcp_connections:G.array(G.object({client_id:G.string(),client_name:G.string(),last_used_at:G.string().nullable()})).optional()})}),Pq=(q)=>`${q.apiOrigin}
|
|
64
64
|
${tq("sha256").update(q.accessToken).digest("hex")}`;function $3(q,J,x){try{let Y=Z3.safeParse(JSON.parse(eq(q,"utf8")));if(!Y.success||Y.data.key!==Pq(J))return null;let X=x-Y.data.at;return X>=0&&X<Y3?Y.data.self:null}catch{return null}}function G3(q,J,x,Y){let X=`${q}.${process.pid}.${sq(6).toString("hex")}.tmp`;try{let $={version:1,key:Pq(J),at:Y,self:x};q3(X,`${JSON.stringify($)}
|
|
65
|
-
`,{mode:384,flag:"wx"}),nq(X,q)}catch{try{aq(X)}catch{}}}var Q3=30000;function W3(q,J=Date.now()){let x=Qq(q),Y=(()=>{if(x?.state!=="connected"&&x?.state!=="starting")return!1;try{return process.kill(x.pid,0),!0}catch{return!1}})(),X=Y&&x?.state==="connected",$=(K)=>X&&J-K>=0&&J-K<Q3,
|
|
66
|
-
`),1;let Y=new AbortController,X=setTimeout(()=>Y.abort(Error("timed out reading the account")),X3);try{let $=J.now?.()??new Date,
|
|
65
|
+
`,{mode:384,flag:"wx"}),nq(X,q)}catch{try{aq(X)}catch{}}}var Q3=30000;function W3(q,J=Date.now()){let x=Qq(q),Y=(()=>{if(x?.state!=="connected"&&x?.state!=="starting")return!1;try{return process.kill(x.pid,0),!0}catch{return!1}})(),X=Y&&x?.state==="connected",$=(K)=>X&&J-K>=0&&J-K<Q3,W=Zq.safeParse(x?.fullDiskAccess);return{full_disk_access:W.success&&$(W.data.checkedAt)?W.data.status:"unknown",keep_awake:{enabled:Dq(q)==="battery_and_ac",holding:x?.idleSleepHold===!0&&$(Date.parse(x.lastHeartbeatAt??""))},executable:Y&&W.success?W.data.executablePath:null}}function B3(q=H()){if(process.platform!=="darwin")return null;let J=kq(Aq(Kq(zq(l()),q),"worker.json"));return J?W3(Fq(J).daemon):null}var Gq={connected:"connected",starting:"starting",reconnecting:"reconnecting",stopping:"stopping",not_running:"not running",removed:"removed from Reason (run `reason connect` to connect it again)"};async function x1(q,J={}){let x=J.io??{stdout:process.stdout,stderr:process.stderr};if(q.includes("--help")||q.includes("-h"))return x.stdout.write(J3),0;if(q.some(($)=>$!=="--json"))return x.stderr.write(`Usage: reason status [--json]
|
|
66
|
+
`),1;let Y=new AbortController,X=setTimeout(()=>Y.abort(Error("timed out reading the account")),X3);try{let $=J.now?.()??new Date,W=performance.now(),K=W,j=()=>{let Z=performance.now(),V=Math.round(Z-K);return K=Z,V},A=null,U=(Z)=>{return A=Z instanceof Error?Z.message:String(Z),null},F=await bq(J,Y.signal).catch(U),S=j(),B=F?.credentialKind==="api_key",D=F&&!B?Aq(x3(Wq(J.env??process.env)),"status-account.json"):null,P=F&&D&&q.includes("--json")?$3(D,F,$.getTime()):null,Q=P??(F?await(J.getSelf??((Z,V)=>new Bq(Z).self(V)))(F,Y.signal).catch(U):null);if(F&&Q&&!P&&D)G3(D,F,Q,$.getTime());let h=j(),v=J.manager??new f,E=q.includes("--json")?[]:v.statuses(),M=(J.loadReceipt??jq)(),_=await(J.readConnection??(()=>Hq({channel:J.channel})))().catch(()=>null),z=null;try{if(_)z=(J.readConnectionMacState??(()=>B3(J.channel??H())))()}catch{}let b=_&&z?{..._,...z}:_,C=(()=>{try{return(J.readDisconnected??(()=>Vq(zq(l()),J.channel??H())))()}catch{return!1}})(),yq=j(),o=Q?{id:Q.org_id,name:Q.organization_name??null,slug:Q.organization_slug??null}:null,N=Q?{id:Q.user_id??null,name:(B?Q.service_user_name:Q.user_name)??null,email:Q.email??null,credential:B?"api_key":"login"}:null,g=J.channel??H(),y={version:R,channel:g,api_origin:F?.apiOrigin??u(g),account:N,account_error:A,organization:o,mcp:E.map((Z)=>({client:Z.id,label:Z.label,status:qq(Z),installed_at:Z.installed?v.installationPath(Z.id):null,last_used_at:Q?xq(Z,Q):null})),connection:b,disconnected:C,installation:M?{background_mode:M.background_mode,automatic_updates:M.background_mode!=="cli_only",future_device_consent:M.device_consent?.decision??"disabled"}:null,timings_ms:{process:Math.round(W),credentials:S,account:h,local:yq,total:Math.round(performance.now()-W)}};if(q.includes("--json"))return x.stdout.write(`${JSON.stringify(y,null,2)}
|
|
67
67
|
`),0;if(g==="staging")x.stdout.write(`Reason ${R} \xB7 channel: STAGING
|
|
68
68
|
`),x.stdout.write(`API: ${y.api_origin}
|
|
69
69
|
`);else x.stdout.write(`Reason ${R}
|
|
70
|
-
`);if(N)x.stdout.write(
|
|
70
|
+
`);if(N)x.stdout.write(B?`Account: API key (REASON_API_KEY)${N.name?`: ${N.name}`:""}
|
|
71
71
|
`:`Account: ${Xq(N)}
|
|
72
72
|
`),x.stdout.write(`Organization: ${Yq(o)}
|
|
73
|
-
`);else if(
|
|
73
|
+
`);else if(A)x.stdout.write(`Account: unavailable (${A})
|
|
74
74
|
`);else x.stdout.write(`Account: signed out
|
|
75
75
|
`),x.stdout.write(`Organization: none
|
|
76
76
|
`);if(x.stdout.write(`
|
|
@@ -79,8 +79,8 @@ 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
|
-
`),
|
|
83
|
-
`);x.stdout.write(`Keep awake: ${
|
|
82
|
+
`),z){let Z=z,V=await(J.readPermissionsSummary??(async()=>{let{permissionsSummary:Rq,readMacPermissions:Nq,reasonIdentity:Iq}=await import("./permissions-8e309cm8.js"),{macScreenStatus:Oq}=await import("./local-display-mac-3zz66vzn.js");return Rq(await Nq({identity:()=>Iq(),grants:Oq,worker:async()=>Z}))}))().catch(()=>null);if(V)x.stdout.write(`${V}
|
|
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}
|
|
86
86
|
`)}if(b.workspaces_off==="sign_in")x.stdout.write("Other workspaces: off. This computer's sign-in is not one the Reason app or the setup command\n Reason shows you made for it (or that sign-in ended, or it is in use on another computer), so it is\n connected in one workspace only. Run the setup command from Reason here (it ends in --pair CODE);\n if this computer was connected before that, run `reason disconnect` and `reason connect` once.\n")}let c=y.mcp.filter((Z)=>Z.installed_at||Z.status!=="not installed");if(c.length>0)x.stdout.write(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ah as c,Bh as d,yh as a,zh as b}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ah as c,Bh as d,yh as a,zh as b}from"./vm-hands-entry-lite-pct56639.js";import"./vm-hands-entry-lite-erxpqz9e.js";import"./vm-hands-entry-lite-hf0mk7vd.js";export{c as compareCliVersions,d as cliAndAgentVersion,b as CLI_VERSION_PATTERN,a as CLI_VERSION};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Pg as wz,Qg as Nz}from"./vm-hands-entry-lite-6j2yaa4n.js";import{_g as N}from"./vm-hands-entry-lite-em388nee.js";import{yh as A}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Pg as wz,Qg as Nz}from"./vm-hands-entry-lite-6j2yaa4n.js";import{_g as N}from"./vm-hands-entry-lite-em388nee.js";import{yh as A}from"./vm-hands-entry-lite-pct56639.js";import{Oh as Fz}from"./vm-hands-entry-lite-hf0mk7vd.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-nac4r75q.js")).connectionMacState(),open:(z)=>{iz("/usr/bin/open",z,{stdio:"ignore",timeout:1e4})},tile:Xz,restartConnection:async()=>(await import("./connect-cli-dqghjqd4.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,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ef as Z8}from"./vm-hands-entry-lite-pf1ft65e.js";import{nf as R0}from"./vm-hands-entry-lite-q2pb31vh.js";import{jg as Kq}from"./vm-hands-entry-lite-
|
|
2
|
+
import{ef as Z8}from"./vm-hands-entry-lite-pf1ft65e.js";import{nf as R0}from"./vm-hands-entry-lite-q2pb31vh.js";import{jg as Kq}from"./vm-hands-entry-lite-8gr872ee.js";import{Fg as p,Ig as V0,Lg as F0,Mg as C8,Ng as eq,Pg as g8,Sg as q0,Ug as x0}from"./vm-hands-entry-lite-6j2yaa4n.js";import{Zg as wq}from"./vm-hands-entry-lite-7k65s010.js";import{$g as C0,_g as o}from"./vm-hands-entry-lite-em388nee.js";import{mh as B0}from"./vm-hands-entry-lite-yp315y25.js";import{Dh as A0}from"./vm-hands-entry-lite-wgx7z7gt.js";import{Kh as Z}from"./vm-hands-entry-lite-xsq25kmd.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
|
-
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.313",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 Ch};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Fd as xe}from"./vm-hands-entry-lite-8st97h7b.js";import{ge as W,he as
|
|
2
|
+
import{Fd as xe}from"./vm-hands-entry-lite-8st97h7b.js";import{ge as W,he as oe,je as _t,ke as Ne,ne as St,oe as wt,pe as $,ye as z,ze as Je}from"./vm-hands-entry-lite-bsfm2m38.js";import{Be as v,De as tt,Ee as D,Me as Ot}from"./vm-hands-entry-lite-pf1ft65e.js";import{hg as Jt,kg as xt,ng as Z,pg as zt,qg as ae}from"./vm-hands-entry-lite-8gr872ee.js";import{Pg as Ae,Qg as se}from"./vm-hands-entry-lite-6j2yaa4n.js";import{Yg as Se}from"./vm-hands-entry-lite-7k65s010.js";import{_g as q}from"./vm-hands-entry-lite-em388nee.js";import{Dh as pe,Jh as ye}from"./vm-hands-entry-lite-wgx7z7gt.js";import{Kh as _}from"./vm-hands-entry-lite-xsq25kmd.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";
|
|
@@ -691,14 +691,14 @@ if(process.env.REASON_CLOUD_GATEWAY_EXEC === "1") {
|
|
|
691
691
|
process.stdout.write(JSON.stringify(cloudAutomationFailure(error))+"\\n");process.exitCode=1;
|
|
692
692
|
}
|
|
693
693
|
}
|
|
694
|
-
`;import{spawn as De}from"child_process";import{basename as Me}from"path";var Pe="__desktop-call",Ze="/usr/bin/setpriv",he=27262976,Qe=8192,ke=2000;function E(t){return Boolean(t)&&typeof t==="object"&&!Array.isArray(t)}function Ye(t){try{return JSON.parse(t)}catch{return null}}function Xe(){return[process.execPath,...Me(process.execPath).startsWith("bun")&&process.argv[1]?[process.argv[1]]:[],Pe]}function We(t,e,r,o={}){r.throwIfAborted();let s=o.command??Xe();return new Promise((a,c)=>{let i=(o.spawnProcess??De)(Ze,[`--reuid=${t.uid}`,`--regid=${t.gid}`,"--clear-groups","--no-new-privs","--",...s],{cwd:t.home,detached:!0,stdio:["pipe","pipe","pipe"],env:{HOME:t.home,USER:t.username,LOGNAME:t.username,PATH:"/usr/local/bin:/usr/bin:/bin"}}),d=[],f=0,n="",l=null,u=!1,m,S=(x)=>{try{process.kill(-i.pid,x)}catch{i.kill(x)}},B=(x)=>{l??=x,S("SIGTERM"),m??=setTimeout(()=>S("SIGKILL"),ke)},g=()=>B(new _("cancelled","Reason cancelled the desktop operation."));r.addEventListener("abort",g,{once:!0});let w=(x)=>{if(u)return;u=!0,clearTimeout(m),r.removeEventListener("abort",g),x()};if(i.stdout.on("data",(x)=>{if(f+=x.byteLength,f>he)B(new _("desktop_delegate_failed","Reason's desktop reply is too large."));else d.push(x)}),i.stderr.setEncoding("utf8").on("data",(x)=>{n=(n+x).slice(-Qe)}),i.stdin.on("error",()=>{}),i.once("error",()=>w(()=>c(l??new _("desktop_delegate_unavailable","Reason could not start its desktop as the desktop account.")))),i.once("close",(x,ze)=>w(()=>{if(l)return c(l);let y=Ye(Buffer.concat(d).toString("utf8"));if(E(y)&&y.ok===!0&&E(y.result))return a(y.result);let F=E(y)&&y.ok===!1&&typeof y.code==="string"&&typeof y.message==="string"?new _(y.code.slice(0,120),y.message.slice(0,2000)):null,
|
|
695
|
-
`).at(-1)?.slice(-300)??"";if(!F||F.code==="desktop_delegate_failed")process.stderr.write(`Reason worker: desktop call ${
|
|
696
|
-
`);if(F)return c(F);c(new _("desktop_delegate_failed",`Reason's desktop operation failed (${
|
|
697
|
-
`)}function
|
|
694
|
+
`;import{spawn as De}from"child_process";import{basename as Me}from"path";var Pe="__desktop-call",Ze="/usr/bin/setpriv",he=27262976,Qe=8192,ke=2000;function E(t){return Boolean(t)&&typeof t==="object"&&!Array.isArray(t)}function Ye(t){try{return JSON.parse(t)}catch{return null}}function Xe(){return[process.execPath,...Me(process.execPath).startsWith("bun")&&process.argv[1]?[process.argv[1]]:[],Pe]}function We(t,e,r,o={}){r.throwIfAborted();let s=o.command??Xe();return new Promise((a,c)=>{let i=(o.spawnProcess??De)(Ze,[`--reuid=${t.uid}`,`--regid=${t.gid}`,"--clear-groups","--no-new-privs","--",...s],{cwd:t.home,detached:!0,stdio:["pipe","pipe","pipe"],env:{HOME:t.home,USER:t.username,LOGNAME:t.username,PATH:"/usr/local/bin:/usr/bin:/bin"}}),d=[],f=0,n="",l=null,u=!1,m,S=(x)=>{try{process.kill(-i.pid,x)}catch{i.kill(x)}},B=(x)=>{l??=x,S("SIGTERM"),m??=setTimeout(()=>S("SIGKILL"),ke)},g=()=>B(new _("cancelled","Reason cancelled the desktop operation."));r.addEventListener("abort",g,{once:!0});let w=(x)=>{if(u)return;u=!0,clearTimeout(m),r.removeEventListener("abort",g),x()};if(i.stdout.on("data",(x)=>{if(f+=x.byteLength,f>he)B(new _("desktop_delegate_failed","Reason's desktop reply is too large."));else d.push(x)}),i.stderr.setEncoding("utf8").on("data",(x)=>{n=(n+x).slice(-Qe)}),i.stdin.on("error",()=>{}),i.once("error",()=>w(()=>c(l??new _("desktop_delegate_unavailable","Reason could not start its desktop as the desktop account.")))),i.once("close",(x,ze)=>w(()=>{if(l)return c(l);let y=Ye(Buffer.concat(d).toString("utf8"));if(E(y)&&y.ok===!0&&E(y.result))return a(y.result);let F=E(y)&&y.ok===!1&&typeof y.code==="string"&&typeof y.message==="string"?new _(y.code.slice(0,120),y.message.slice(0,2000)):null,pt=`exited ${x??ze}${F?"":" with no reply"}`,yt=n.trim().split(`
|
|
695
|
+
`).at(-1)?.slice(-300)??"";if(!F||F.code==="desktop_delegate_failed")process.stderr.write(`Reason worker: desktop call ${pt}${n?`: ${n.trim().slice(-500)}`:""}
|
|
696
|
+
`);if(F)return c(F);c(new _("desktop_delegate_failed",`Reason's desktop operation failed (${pt}${yt?`: ${yt}`:""}).`))})),r.aborted)g();i.stdin.end(JSON.stringify(e))})}async function Nt(t,e,r,o={}){let s=await We(t,{op:"automation",call:e},r,o);if(!Number.isSafeInteger(s.code)||typeof s.stdout!=="string"||typeof s.stderr!=="string")throw new _("desktop_delegate_failed","Reason's desktop reply is malformed.");return{code:s.code,stdout:Buffer.from(s.stdout,"base64"),stderr:s.stderr}}import{execFile as zr,spawn as jr}from"child_process";import{closeSync as Dr,mkdirSync as Mr,openSync as Pr}from"fs";import{dirname as k,join as Zr}from"path";import{promisify as hr}from"util";import{spawnSync as P}from"child_process";import{createHash as Sr,randomUUID as pr}from"crypto";import{chmodSync as yr,existsSync as st,mkdirSync as Ar,readdirSync as es,readFileSync as U,renameSync as Nr,rmSync as N,statSync as Or,writeFileSync as gr}from"fs";import{dirname as Tr,isAbsolute as jt,join as G}from"path";import{chmodSync as Mo,existsSync as He,mkdirSync as Po,readlinkSync as Ke,readFileSync as Ve,renameSync as Zo,unlinkSync as ho,writeFileSync as Qo}from"fs";import{homedir as gt}from"os";import{basename as Ee,dirname as Tt,isAbsolute as qt,join as R,normalize as ve,relative as tr,resolve as er}from"path";var et=3,rr=1,or=2,sr=1,ar=1,ir="Reason may read and write files and run commands in this signed-in OS account, subject to saved restrictions and operating system permissions.",cr="Reason may later execute on this computer inside a Reason sandbox, limited to folders explicitly attached by the user.",nr=[cr,"Ara may later execute on this computer inside an Ara sandbox, limited to folders explicitly attached by the user."];function dr(t){return typeof t==="string"&&nr.includes(t)}var fr=["future_device","updates_only","cli_only"];function Ct(t){return typeof t==="string"&&fr.some((e)=>e===t)}function lr(t=process.env,e=gt()){return t.XDG_CONFIG_HOME?.trim()||R(e,".config")}function rt(t=process.env,e=gt()){let r=D({env:t}),o=lr(t,e);return R(o,Ot(o).state==="kept"?"ara":"reason",...r==="staging"?["staging"]:[],"installation.json")}function p(t){return typeof t==="string"&&t.trim().length>0}var _r=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function ur(t){return typeof t==="string"&&_r.test(t)}function j(t){return p(t)&&qt(t)&&ve(t)===t}function Bt(t){if(!t||typeof t!=="object"||Array.isArray(t))return!1;let e=t;return j(e.path)&&(e.role==="launcher"&&(e.kind==="file"||e.kind==="symlink")||e.role==="worker_root"&&e.kind==="directory"||e.role==="alias"&&e.kind==="symlink"&&j(e.target))}function It(t){return t.owned_paths?.every((e)=>e.role!=="alias"||t.installer==="shell"&&e.path===R(t.install_dir,t.channel==="staging"?"reason-staging":"reason")&&e.target===R(t.install_dir,t.channel==="staging"?"ara-staging":"ara")&&t.owned_paths?.some((r)=>r.role==="launcher"&&r.path===e.target))??!1}function mr(t,e){try{return er(Tt(t),Ke(t))===e}catch{return!1}}function ot(t){let e=Ee(t),r=e==="ara"?"reason":e==="ara-staging"?"reason-staging":null;if(!r)return t;let o=R(Tt(t),r);return mr(o,t)?o:t}function $t(t,e){let r=tr(t,e);return r.length>0&&!r.startsWith("..")&&!qt(r)}function Ft(t){if(t===null)return!0;if(!t||typeof t!=="object"||Array.isArray(t))return!1;let e=t;return e.kind==="shell_profile"&&p(e.location)&&p(e.value)&&(typeof e.added_by_installer==="boolean"||typeof e.added_by_ara==="boolean")&&(e.added_by_installer===void 0||typeof e.added_by_installer==="boolean")&&(e.added_by_ara===void 0||typeof e.added_by_ara==="boolean")}function Rt(t,e){if(e===null)return t==="cli_only";if(!e||typeof e!=="object"||Array.isArray(e))return!1;let r=e;if(r.version!==sr||!p(r.recorded_at))return!1;if(t==="future_device")return r.decision==="authorized"&&dr(r.scope);return r.scope===null&&r.decision===(t==="updates_only"?"ask":"disabled")}function br(t){if(!t||typeof t!=="object"||Array.isArray(t))return null;let e=t;if(e.schema_version!==rr||!tt.includes(e.channel)||e.install_method!=="curl"||e.installer!=="shell"||!p(e.installed_at)||!p(e.version)||!p(e.target)||!j(e.install_dir)||!Array.isArray(e.owned_paths)||!e.owned_paths.every(Bt)||!e.owned_paths.every((r)=>$t(e.install_dir,r.path))||!It(e)||!Ft(e.path_entry))return null;return{...e,schema_version:et,installation_id:null,background_mode:"cli_only",device_consent:null}}function wr(t){if(!t||typeof t!=="object"||Array.isArray(t))return null;let e=t;if(e.schema_version!==or||!Gt(e)||!Ct(e.background_mode)||!Rt(e.background_mode,e.device_consent))return null;return{...e,schema_version:et,installation_id:null}}function Gt(t){return tt.includes(t.channel)&&(t.install_method==="curl"&&t.installer==="shell"||t.install_method==="desktop"&&t.installer==="desktop"&&Array.isArray(t.owned_paths)&&t.owned_paths.length===0&&t.path_entry===null)&&p(t.installed_at)&&p(t.version)&&p(t.target)&&j(t.install_dir)&&Array.isArray(t.owned_paths)&&t.owned_paths.every(Bt)&&t.owned_paths.every((e)=>$t(t.install_dir,e.path))&&It(t)&&Ft(t.path_entry)}function xr(t){let e=br(t);if(e)return e;let r=wr(t);if(r)return r;if(!t||typeof t!=="object"||Array.isArray(t))return null;let o=t;if(o.schema_version!==et||!ur(o.installation_id)||!Gt(o)||!Ct(o.background_mode)||!Rt(o.background_mode,o.device_consent)||o.desktop_account_access!==void 0&&(o.desktop_account_access===null||typeof o.desktop_account_access!=="object"||Array.isArray(o.desktop_account_access)||o.desktop_account_access.version!==ar||o.desktop_account_access.scope!==ir||!p(o.desktop_account_access.recorded_at)||!Number.isFinite(Date.parse(o.desktop_account_access.recorded_at))))return null;return o}function Ut(t=rt()){if(!He(t))return null;try{return xr(JSON.parse(Ve(t,"utf8")))}catch{return null}}var at="REASON_WORKER_SERVICE",qr="worker_identity_unavailable";function Dt(t){return{platform:process.platform,home:t,uid:process.getuid?.(),command:(e,r)=>P(e,[...r],{stdio:"ignore"}).status??1,read:(e,r)=>{let o=P(e,[...r],{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4});return o.status===0?o.stdout:null},sleep:(e)=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e),workerIdentity:(e)=>zt(t,e),insideService:(e)=>Cr(e,process.platform,process.getuid?.())}}function Cr(t,e,r){if(process.env[at]===t||process.env.XPC_SERVICE_NAME===t)return!0;if(e==="linux")try{return U("/proc/self/cgroup","utf8").includes(`/${t}.service`)}catch{return!0}if(e!=="darwin")return!1;if(typeof r!=="number")return!0;let o=P("/bin/launchctl",["print",`gui/${r}/${t}`],{encoding:"utf8",timeout:5000});if(o.status===Br)return!1;if(o.error||o.status!==0)return!0;let s=Number(/^\s*pid = (\d+)$/m.exec(o.stdout??"")?.[1]??0);if(!s)return!1;let a=process.pid;for(let c=0;c<64&&a>1;c+=1){if(a===s)return!0;let i=P("/bin/ps",["-o","ppid=","-p",String(a)],{encoding:"utf8",timeout:5000}),d=Number(i.stdout?.trim());if(i.error||i.status!==0||!Number.isSafeInteger(d)||d<=0)return!0;if(d===a)return!1;a=d}return a>1}var Br=113;class A extends Error{code;constructor(t,e){super(t);this.code=e}}function Mt(t,e){if(t.platform!=="darwin"&&t.platform!=="linux")throw new A("A background service needs macOS (launchd) or Linux (systemd --user).");if(t.platform==="darwin")L(t);let o=[Ut(rt(e,t.home))?.owned_paths.find((s)=>s.role==="launcher")?.path,v(e,"REASON_CLI_LAUNCHER_PATH")?.trim(),G(t.home,".local","bin",D({env:e})==="staging"?"ara-staging":"ara")];for(let s of o)try{if(s&&jt(s)&&Or(s).isFile())return ot(s)}catch{}throw new A("A background service runs the installed Reason launcher, which was not found. Install Reason with: curl -fsSL https://reasonmachines.com/install | sh","worker_launcher_missing")}var it=/(<key>ProgramArguments<\/key>\s*<array>\n)((?:\s*<string>[^<]*<\/string>\n)*)(\s*<\/array>)/,M=new RegExp(`(\\n\\s*<key>${Z}</key>\\s*<string>)[^<]*(</string>)`),Ir=/(<key>EnvironmentVariables<\/key>\s*<dict>[\s\S]*?)(\n\s*<\/dict>)/;function $r(t){return t.replaceAll("<","<").replaceAll(">",">").replaceAll(""",'"').replaceAll("'","'").replaceAll("&","&")}function Pt(t){let e=[...(it.exec(t)?.[2]??"").matchAll(/<string>([^<]*)<\/string>/g)].map((o)=>$r(o[1])),r=e[1]==="--run-worker"?e.slice(2):e;return r[0]?{launcher:r[0],args:r.slice(1)}:null}function Zt(t,e,r){let o=r.workerIdentity?.(t)??null;return{program:o?[o.executable,"--run-worker",t,...e]:[t,...e],identity:o}}function ct(t){return t.map((e)=>` <string>${O(e)}</string>`).join(`
|
|
697
|
+
`)}function ht(t,e){let r;try{r=U(t,"utf8")}catch{return null}let o=Pt(r);if(!o)return null;let s=jt(o.launcher)?ot(o.launcher):o.launcher,{program:a,identity:c}=Zt(s,o.args,e),i=r.replace(it,(d,f,n,l)=>`${f}${ct(a)}
|
|
698
698
|
${l}`);if(!c)i=i.replace(M,"");else if(M.test(i))i=i.replace(M,(d,f,n)=>`${f}${O(c.app)}${n}`);else i=i.replace(Ir,(d,f,n)=>`${f}
|
|
699
699
|
<key>${Z}</key>
|
|
700
|
-
<string>${O(c.app)}</string>${n}`);return i===r?null:i}function Fr(t,e){let r=
|
|
701
|
-
`:""}${u}`)===
|
|
700
|
+
<string>${O(c.app)}</string>${n}`);return i===r?null:i}function Fr(t,e){let r=ht(t,e);if(r!==null)Q(t,r)}function cs(t,e,r){if(e.platform!=="darwin")return!1;let o=dt(t,e,r);return o!==null&&ht(o.definition,e)!==null}var h="com.reasonmachines.worker.",nt="so.reason.worker.",Qt=[h,nt];function kt(t,e=h){return`${e}connect${t==="production"?"":`.${t}`}`}function ns(t,e){return Qt.some((r)=>t===kt(e,r))}function Rr(t,e,r){if(e==="connect")return kt(t.channel,r);let o=Sr("sha256").update(t.workspaceRoot).digest("hex").slice(0,8);return`${r}${t.name.toLowerCase()}.${o}`}function Gr(t,e){if(e==="darwin")return{directory:G(t,"Library","LaunchAgents"),suffix:".plist"};if(e==="linux")return{directory:G(t,".config","systemd","user"),suffix:".service"};return null}function T(t,e,r,o=h){let s=Rr(t,r,o),a=Gr(e.home,e.platform);if(!a)return null;return{label:s,definition:G(a.directory,`${s}${a.suffix}`),logs:e.platform==="darwin"?G(t.stateDirectory,"service.log"):`journalctl --user -u ${s}.service`}}function dt(t,e,r="serve"){return Yt(t,e,r)[0]??null}function Yt(t,e,r){return Qt.map((o)=>T(t,e,r,o)).filter((o)=>o!==null&&st(o.definition))}function Xt(t,e,r){let o=T(t,e,r,nt);return o&&st(o.definition)?o:null}function Ur(t,e,r){let o=T(t,e,r),s=Xt(t,e,r);if(!o||!s||!st(o.definition)||e.insideService?.(s.label))return null;if(!Lr(o,e))return"current_not_running";if(e.platform==="darwin"){if(typeof e.uid==="number"&&e.uid>0)e.command("/bin/launchctl",["bootout",`gui/${e.uid}/${s.label}`]);return N(s.definition,{force:!0}),"retired"}return e.command("systemctl",["--user","disable","--now",`${s.label}.service`]),N(s.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"]),"retired"}function Lr(t,e){if(e.platform==="darwin")return typeof e.uid==="number"&&e.uid>0&&e.command("/bin/launchctl",["print",`gui/${e.uid}/${t.label}`])===0;let r=`${t.label}.service`;return e.command("systemctl",["--user","is-enabled","--quiet",r])===0&&Jr.has(e.read("systemctl",["--user","show","--property=ActiveState","--value",r])?.trim()??"")}var Jr=new Set(["active","activating","reloading"]);function ds(t,e){if(e.platform==="darwin"){if(typeof e.uid!=="number"||e.uid<=0)return!1;let r=e.read("/bin/launchctl",["print",`gui/${e.uid}/${t.label}`]);return Number(/^\s*pid = (\d+)$/m.exec(r??"")?.[1]??0)>0}return Number(e.read("systemctl",["--user","show","--property=MainPID","--value",`${t.label}.service`])?.trim()??0)>0}function fs(t){let{config:e,launcher:r,host:o,kind:s}=t,a=T(e,o,s);if(!a)return!1;let c;try{c=U(a.definition,"utf8")}catch{return!1}if(o.platform!=="darwin")return c===Kt(e,s,a,r,o.home,t.path);let i=Pt(c);return c.replace(M,"").replace(it,(f,n,l,u)=>`${n}${i?`${ct([i.launcher,...i.args])}
|
|
701
|
+
`:""}${u}`)===Ht(e,s,a,r,{...o,workerIdentity:()=>null},t.path).plist}function Wt(t,e){if(e==="connect")return{args:["connect"],environment:{REASON_CLI_CHANNEL:t.channel},description:"Reason connection of this computer"};return{args:["serve",t.name,"--dir",t.workspaceRoot,...t.executionMode==="confined"?["--sandbox"]:[]],environment:{},description:`Reason machine ${t.name} worker`}}function O(t){return t.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Lt(t,e=!1){if(/[\0-\x1f\x7f]/.test(t))throw new A("A background service cannot use a path with control characters.");let r=t.replaceAll("\\","\\\\").replaceAll('"',"\\\"").replaceAll("%","%%");return`"${e?r.replaceAll("$","$$$$"):r}"`}function Ht(t,e,r,o,s,a){let c=Wt(t,e),i=Zt(o,c.args,s),d={HOME:s.home,PATH:a,[at]:r.label,...c.environment,...i.identity?{[Z]:i.identity.app}:{}};return{identity:i.identity,plist:`<?xml version="1.0" encoding="UTF-8"?>
|
|
702
702
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
703
703
|
<plist version="1.0">
|
|
704
704
|
<dict>
|
|
@@ -706,7 +706,7 @@ ${l}`);if(!c)i=i.replace(M,"");else if(M.test(i))i=i.replace(M,(d,f,n)=>`${f}${O
|
|
|
706
706
|
<string>${O(r.label)}</string>
|
|
707
707
|
<key>AssociatedBundleIdentifiers</key>
|
|
708
708
|
<array>
|
|
709
|
-
<string>${
|
|
709
|
+
<string>${Jt}</string>
|
|
710
710
|
</array>
|
|
711
711
|
<key>ProgramArguments</key>
|
|
712
712
|
<array>
|
|
@@ -739,12 +739,12 @@ ${Object.entries(d).map(([f,n])=>` <key>${f}</key>
|
|
|
739
739
|
<string>${O(r.logs)}</string>
|
|
740
740
|
</dict>
|
|
741
741
|
</plist>
|
|
742
|
-
`}}function
|
|
742
|
+
`}}function Kt(t,e,r,o,s,a){let c=Wt(t,e);return`[Unit]
|
|
743
743
|
Description=${c.description}
|
|
744
744
|
|
|
745
745
|
[Service]
|
|
746
|
-
ExecStart=${[o,...c.args].map((i)=>
|
|
747
|
-
Environment=${[`HOME=${s}`,`PATH=${a}`,`${at}=${r.label}`,...Object.entries(c.environment).map(([i,d])=>`${i}=${d}`)].map((i)=>
|
|
746
|
+
ExecStart=${[o,...c.args].map((i)=>Lt(i,!0)).join(" ")}
|
|
747
|
+
Environment=${[`HOME=${s}`,`PATH=${a}`,`${at}=${r.label}`,...Object.entries(c.environment).map(([i,d])=>`${i}=${d}`)].map((i)=>Lt(i)).join(" ")}
|
|
748
748
|
Restart=on-failure
|
|
749
749
|
RestartSec=10
|
|
750
750
|
TimeoutStopSec=${Math.ceil(t.shutdownGraceMs/1000)+10}
|
|
@@ -752,9 +752,9 @@ UMask=0077
|
|
|
752
752
|
|
|
753
753
|
[Install]
|
|
754
754
|
WantedBy=default.target
|
|
755
|
-
`}function Q(t,e){Ar(Tr(t),{recursive:!0,mode:448});let r=`${t}.${pr()}.tmp`;try{gr(r,e,{mode:384,flag:"wx"}),yr(r,384),Nr(r,t)}finally{N(r,{force:!0})}}function L(t){if(typeof t.uid!=="number"||!Number.isSafeInteger(t.uid)||t.uid<=0)throw new A("Set up a background service as your own user, not with sudo.");return`gui/${t.uid}`}function ls(t){let{config:e,launcher:r,host:o}=t,s=t.kind??"serve",a=
|
|
756
|
-
`}function xo(t,e,r,o={stdin:process.stdin,stdout:process.stdout}){return new Promise((s)=>{let a=I(t,e,{env:r,stdio:["pipe","pipe","inherit"]}),c=(n)=>{a.kill(n)},i=["SIGTERM","SIGINT","SIGHUP"];for(let n of i)process.on(n,c);o.stdin.pipe(a.stdin),a.stdin.on("error",()=>{return}),a.stdout.pipe(o.stdout,{end:!1});let d=!1,f=(n)=>{if(d)return;d=!0;for(let l of i)process.off(l,c);o.stdin.unpipe(a.stdin),o.stdout.write("",()=>s(n))};a.once("error",()=>f(127)),a.once("close",(n)=>f(n??1))})}async function Hs(t,e={}){let r=e.stderr??process.stderr,o=(e.identity??
|
|
755
|
+
`}function Q(t,e){Ar(Tr(t),{recursive:!0,mode:448});let r=`${t}.${pr()}.tmp`;try{gr(r,e,{mode:384,flag:"wx"}),yr(r,384),Nr(r,t)}finally{N(r,{force:!0})}}function L(t){if(typeof t.uid!=="number"||!Number.isSafeInteger(t.uid)||t.uid<=0)throw new A("Set up a background service as your own user, not with sudo.");return`gui/${t.uid}`}function ls(t){let{config:e,launcher:r,host:o}=t,s=t.kind??"serve",a=Xt(e,o,s),c=a!==null&&o.insideService?.(a.label)===!0,i=T(e,o,s,c?nt:h);if(!i)throw new A("A background service needs macOS (launchd) or Linux (systemd --user).");if(o.platform==="darwin")L(o);if(o.platform==="linux"&&o.command("systemctl",["--user","show-environment"])!==0)throw new A("No background service here: this computer has no systemd user session.","worker_service_manager_missing");let d=o.platform==="darwin"?Ht(e,s,i,r,o,t.path):null;if(Q(i.definition,d?d.plist:Kt(e,s,i,r,o.home,t.path)),Vt(e,o,i,c?null:a),d)return d.identity?i:{...i,identityProblem:qr};return{...i,lingering:o.command("loginctl",["enable-linger"])===0}}function Vt(t,e,r,o){if(e.platform==="darwin"){let c=L(e);if(o)e.command("/bin/launchctl",["bootout",`${c}/${o.label}`]);if(Et(t,r,e)){if(o)N(o.definition,{force:!0});return}if(N(r.definition,{force:!0}),o)e.command("/bin/launchctl",["bootstrap",c,o.definition]);throw new A("Could not start the background service (launchctl bootstrap failed).")}let s=`${r.label}.service`,a=o?`${o.label}.service`:null;if(e.command("systemctl",["--user","daemon-reload"])!==0||a!==null&&e.command("systemctl",["--user","disable","--now",a])!==0||e.command("systemctl",["--user","enable",s])!==0||e.command("systemctl",["--user","restart",s])!==0){if(e.command("systemctl",["--user","disable",s]),N(r.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"]),a)e.command("systemctl",["--user","enable","--now",a]);throw new A("Could not start the background service (systemctl --user failed).")}if(o)N(o.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"])}function Et(t,e,r){let o=L(r);r.command("/bin/launchctl",["bootout",`${o}/${e.label}`]);let s=(Math.ceil(t.shutdownGraceMs/1000)+10)*1000;for(let a=0,c=100;;c=Math.min(c*2,2000)){if(r.command("/bin/launchctl",["bootstrap",o,e.definition])===0)return!0;if(a>=s)return!1;r.sleep(c),a+=c}}function _s(t,e,r){let o=dt(t,e,r);if(!o)return null;let s=e.insideService?.(o.label)===!0;if(e.platform==="darwin"&&!s)Fr(o.definition,e);let a=T(t,e,r);if(a&&o.label!==a.label&&!s)return Q(a.definition,U(o.definition,"utf8").replaceAll(o.label,a.label)),Vt(t,e,a,o),a;let c=e.platform==="darwin"&&s,i;if(c)i=e.command("/bin/launchctl",["kickstart","-k",`${L(e)}/${o.label}`])===0;else if(e.platform==="darwin")i=Et(t,o,e);else e.command("systemctl",["--user","enable",`${o.label}.service`]),i=e.command("systemctl",["--user","restart",`${o.label}.service`])===0;if(!i)throw new A(`Could not restart the background service ${o.label}.`);if(a&&o.label===a.label)Ur(t,e,r);return o}function us(t,e,r,o){let s=dt(t,r,o),a=T(e,r,o);if(r.platform!=="darwin"||!s||!a)return;let c=`<string>${O(s.logs)}</string>`,i=U(s.definition,"utf8");if(i.includes(c))Q(s.definition,i.replaceAll(c,`<string>${O(a.logs)}</string>`))}function ms(t,e,r="serve"){let o=Yt(t,e,r);for(let s of o){if(e.platform==="darwin"){if(typeof e.uid==="number"&&e.uid>0)e.command("/bin/launchctl",["bootout",`gui/${e.uid}/${s.label}`]);N(s.definition,{force:!0});continue}e.command("systemctl",["--user","disable","--now",`${s.label}.service`]),N(s.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"])}return o[0]??null}var Qr=hr(zr),vt="x-apple.systempreferences:com.apple.preference.security",kr={accessibility:`${vt}?Privacy_Accessibility`,screen:`${vt}?Privacy_ScreenCapture`},Yr=64,J=new Map;function Y(t,e){let r=J.get(t);if(r?.has(e))return!1;if(!r){if(J.size>=Yr)J.delete(J.keys().next().value);r=new Set,J.set(t,r)}return r.add(e),!0}function Xr(){let t=q(),e=Mt(Dt(t),process.env),r=Zr(t,".local","share","reason","desktop-install.log");Mr(k(r),{recursive:!0,mode:448});let o=Pr(r,"a",384);try{let s=jr(e,["desktop","install"],{detached:!0,stdio:["ignore",o,o],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});s.on("error",()=>{return}),s.unref()}finally{Dr(o)}}var X={open:async(t,e)=>{await Qr("/usr/bin/open",t,{signal:e,timeout:1e4,maxBuffer:8192})},request:(t,e)=>se(t,e),tile:ae,installDesktop:Xr},te=!1;async function ee(t,e,r){try{await e.open(["-a","Google Chrome",t],r)}catch{r.throwIfAborted(),await e.open([t],r)}}async function ie(t,e,r,o){if(await r.open([kr[e]],o).catch(()=>{}),t[0]&&!o.aborted)r.tile(k(k(k(t[0]))),e)}async function Wr(t,e,r,o,s){for(let a of r){if(!Y(t,`grant:${a}`))continue;s.throwIfAborted(),await o.request(e,a).catch(()=>null),await ie(e,a,o,s)}}var Hr={name:"open_tab",description:"Open a web page in the user's own Chrome on this Mac. Reason cannot read, screenshot or click in that tab, and no tab_id is returned: browser control needs Reason's Chrome extension. An actual browser call opens its setup page.",inputSchema:{type:"object",properties:{url:{type:"string",description:"An http or https URL."}},required:["url"],additionalProperties:!1}};function re(t){return{code:0,stderr:"",stdout:Buffer.from(JSON.stringify({ok:!0,...t}))}}function Kr(t){if(typeof t!=="string")return null;try{let e=new URL(t);return e.protocol==="https:"||e.protocol==="http:"?e.href:null}catch{return null}}async function ce(t,e=X){let{call:r,runId:o,signal:s}=t;if(r.kind==="browser"){if(r.operation==="discover")return re({result:{tools:[Hr]}});if(r.operation!=="call")throw new _("automation_browser_setup_required","Browser control is not set up on this Mac yet. Request a browser operation or connect Chrome from Reason to set it up.")}if(t.desktopMissing&&!te){te=!0;try{e.installDesktop()}catch{}}if(r.kind==="computer"){if(t.identity.length>0&&Y(o,"grant:probe")){let i=await e.request(t.identity).catch(()=>null),d=i?[...i.accessibility?[]:["accessibility"],...i.screen?[]:["screen"]]:[];for(let f of d)Y(o,`grant:${f}`);for(let f of d)await ie(t.identity,f,e,s)}throw new _("automation_computer_setup_required","Computer use is not set up on this Mac yet; Reason asked macOS for any missing permission.")}if(Y(o,"page:chrome-extension"))await ee(oe,e,s).catch(()=>{});let a=r.arguments,c=r.operation==="call"&&r.tool==="open_tab"&&a&&typeof a==="object"&&!Array.isArray(a)?Kr(a.url):null;if(!c)throw new _("automation_browser_setup_required","Browser control is not set up on this Mac yet; Reason opened its Chrome Web Store page. open_tab still opens pages.");return await ee(c,e,s),re({result:{content:[{type:"text",text:JSON.stringify({opened:c,browser:"the user's Chrome",controllable:!1,note:"Opened for the user to see. Reason cannot read or act in this tab until Reason's Chrome extension is added (its Chrome Web Store page is open)."})}]}})}async function ne(t,e=X){if(t.call.kind!=="computer"||t.call.operation!=="permission_status"||t.output.code!==0||t.identity.length===0)return t.output;let r;try{r=JSON.parse(t.output.stdout.toString("utf8"))}catch{return t.output}if(!r||typeof r!=="object"||Array.isArray(r))return t.output;let o=r.permissions;if(!o||typeof o!=="object")return t.output;let s=o,a=[...s.accessibility==="missing"?["accessibility"]:[],...s.screenRecording==="missing"?["screen"]:[]];if(a.length===0)return t.output;return await Wr(t.runId,t.identity,a,e,t.signal),{...t.output,stdout:Buffer.from(JSON.stringify({...r,requested:a}))}}var bt=172032,ao=18874368,io=8192,co=65536,no=55000,fo=60000,lo=4,_o=40000,uo=/^[0-9a-f-]{36}$/,_e=At,mo=Oe();function H(t){return Boolean(t)&&typeof t==="object"&&!Array.isArray(t)}function K(){throw new _("invalid_automation_request","Reason automation request is malformed.")}function qe(t){let e=Object.keys(t).sort().join(",");if(e==="call"||e==="browser,call"){let r=t.call,o=e==="browser,call";if(!H(r)||r.version!==1||r.kind!=="computer"&&r.kind!=="browser"||o&&(t.browser!==xe||r.kind!=="browser")||JSON.stringify(r).length>co)K();return{call:r,userChrome:o}}if(e==="offset,output_id"){if(typeof t.output_id!=="string"||!uo.test(t.output_id)||!Number.isSafeInteger(t.offset)||t.offset<0)K();return{output_id:t.output_id,offset:t.offset}}return K()}function Ws(t=process.platform,e=$){if(t==="darwin")return!0;return t==="linux"&&e()?.features.computer===!0}var bo="__computer-use";function wo(t){let e=(r)=>r?"granted":"missing";return`Permissions: accessibility=${e(t.accessibility)}, screenRecording=${e(t.screen)}
|
|
756
|
+
`}function xo(t,e,r,o={stdin:process.stdin,stdout:process.stdout}){return new Promise((s)=>{let a=I(t,e,{env:r,stdio:["pipe","pipe","inherit"]}),c=(n)=>{a.kill(n)},i=["SIGTERM","SIGINT","SIGHUP"];for(let n of i)process.on(n,c);o.stdin.pipe(a.stdin),a.stdin.on("error",()=>{return}),a.stdout.pipe(o.stdout,{end:!1});let d=!1,f=(n)=>{if(d)return;d=!0;for(let l of i)process.off(l,c);o.stdin.unpipe(a.stdin),o.stdout.write("",()=>s(n))};a.once("error",()=>f(127)),a.once("close",(n)=>f(n??1))})}async function Hs(t,e={}){let r=e.stderr??process.stderr,o=(e.identity??xt)(),s=(e.components??$)();if(o.length===0||s?.platform!=="darwin-arm64")return r.write(`Reason computer use: Reason's background identity cannot run Open Computer Use here (computer_use_identity_unavailable)
|
|
757
757
|
`),1;if(t.length===1&&t[0]==="doctor"){let i=await(e.grants??Ae)(o);if(!i)return r.write(`Reason computer use: Reason's permissions could not be read (computer_use_permission_status_unavailable)
|
|
758
758
|
`),1;return(e.stdout??process.stdout).write(wo(i)),0}if(t.length!==1||t[0]!=="mcp")return r.write(`Usage: reason __computer-use mcp|doctor
|
|
759
|
-
`),2;let[a,...c]=o;return(e.run??xo)(a,[...c,s.ocu,"mcp"],{...process.env,OPEN_COMPUTER_USE_DISABLE_APP_AGENT_PROXY:"1"})}function Ks(t=$){return t()?.userChrome??{code:"user_chrome_browser_use_missing"}}function Ce(t,e,r,o){return new Promise((s)=>{let a=I(t,e,{env:r,stdio:"ignore"}),c=setTimeout(()=>{a.kill("SIGKILL"),s(-1)},o);a.once("error",()=>{clearTimeout(c),s(-1)}),a.once("exit",(i)=>{clearTimeout(c),s(i??-1)})})}function So(t,e,r,o){return new Promise((s)=>{let a=I(t,e,{env:r,stdio:["ignore","pipe","ignore"]}),c="";a.stdout.setEncoding("utf8").on("data",(d)=>{c+=d});let i=setTimeout(()=>{a.kill("SIGKILL"),s(null)},o);a.once("error",()=>{clearTimeout(i),s(null)}),a.once("close",(d)=>{clearTimeout(i),s(d===0?c:null)})})}var po="/tmp/open-browser-use",yo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ao=33554432;function No(t,e){let r;try{r=t===null?null:JSON.parse(t)}catch{return null}let o=H(r)&&H(r.result)?r.result.metadata:null;if(!H(o)||o.extensionId!==e)return null;return typeof o.extensionInstanceId==="string"&&yo.test(o.extensionInstanceId)?o.extensionInstanceId:null}async function Be(t,e,r){let o=r.storages.map((i)=>{try{return V(i).filter((d)=>d.endsWith(".log")||d.endsWith(".ldb")).map((d)=>b(i,d))}catch{return[]}}),s;try{s=o.some((i)=>i.length>0)?V(r.socketDir).filter((i)=>i.endsWith(".sock")):[]}catch{return[]}let a=[];for(let i of s){let d=b(r.socketDir,i),f=No(await So(t,["info","--socket",d,"--timeout","2s"],e,5000),r.extensionId);if(f)a.push({instance:f,socket:d})}let c=[];for(let[i,d]of(a.length>0?o:[]).entries())for(let f of d)try{if(oo(f).size>Ao)continue;let n=ge(f),l=a.find((u)=>n.includes(u.instance));if(l){c.push({storage:r.storages[i],...l});break}}catch{}return c}async function Oo(t,e,r){return(await Be(t,e,r))[0]?.instance??null}function Ie(t,e,r){return Oo(t,e,{socketDir:po,extensionId:ut,storages:[b(r,"browser-profile","Default","Local Extension Settings",ut)]})}var ue=/^(Default|Profile ([0-9]+))$/;async function go(t,e,r=q(),o=pt){let s=b(r,"Library","Application Support","Google","Chrome"),a=[];try{a=V(s)}catch(n){if(n.code==="EPERM")throw new _("browser_use_chrome_access_denied","macOS blocked Reason from reading Chrome's profiles. Allow Full Disk Access for Reason on this Mac and try again.")}let c=(n)=>Number(ue.exec(n)?.[2]??-1),i=a.filter((n)=>ue.test(n)&&mt(b(s,n,"Extensions",W))).sort((n,l)=>c(n)-c(l)),d=(n)=>b(s,n,"Local Extension Settings",W);return(await Be(t,e,{socketDir:o,extensionId:W,storages:i.map(d)})).map(({storage:n,instance:l,socket:u})=>({profile:i.find((m)=>d(m)===n),instance:l,socket:u}))}async function To(t,e,r=q(),o=pt){let s=(await go(t,e,r,o))[0]?.instance;if(!s)throw new _("automation_user_chrome_not_connected","No Chrome profile on this Mac is connected to Reason. Open Chrome with the Reason extension, then try again.");return s}function me(t){return new Promise((e)=>{let r=so({path:t}),o=(s)=>{r.destroy(),e(s)};r.setTimeout(1000,()=>o(!1)),r.once("error",()=>o(!1)),r.once("connect",()=>o(!0))})}async function $e(t,e){let r=Date.now()+e;while(Date.now()<r){if(await t())return!0;await new Promise((o)=>setTimeout(o,200))}return!1}var lt=new Map;function _t(t,e){let r=lt.get(t);if(!r)r=e().finally(()=>lt.delete(t)),lt.set(t,r);return r}async function qo(t,e){if(await me(t))return;if(ro(t,{force:!0}),await Ce("dbus-daemon",["--session",`--address=unix:path=${t}`,"--fork"],e,1e4)!==0||!await $e(()=>me(t),5000))throw new _("automation_unavailable","Reason could not start the desktop session bus.")}async function be(t,e,r){let o=t.platform==="darwin-arm64"?async()=>await Ie(t.nativeHost,e,r)!==null:async()=>await Ce(t.nativeHost,["info"],e,5000)===0;if(await o())return;let s=["--profile-directory=Default",`--load-extension=${t.extensionDir}`,"--no-first-run","--no-default-browser-check","--window-size=1280,800","about:blank"],a,c=null,i=0;if(t.platform==="darwin-arm64"){let n=b(r,"browser-profile");z(n);let l=b(n,"NativeMessagingHosts");fe(l,{recursive:!0,mode:448});let u=xt(t.platform).nativeHostManifests[0];de(u,b(l,le(u)));let m=t.browser.slice(0,t.browser.indexOf(".app/")+4),S=s.filter((B)=>B!=="about:blank").concat("--no-startup-window","--use-mock-keychain");a=I("/usr/bin/open",["-g","-n","-a",m,"--args",`--user-data-dir=${n}`,...S],{env:e,stdio:"ignore"})}else{let n=b(e.HOME,".config","google-chrome"),l=b(n,"NativeMessagingHosts");fe(l,{recursive:!0,mode:448});let u=xt(t.platform).nativeHostManifests[0];de(u,b(l,le(u)));let m=process.geteuid?.()===0?["--no-sandbox"]:[];c=b(r,"browser.log");let S=vr(c,"a",384);i=Er(S).size,a=I(t.browser,[`--user-data-dir=${n}`,...s,...m,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",S,S],env:{...e,ACCESSIBILITY_ENABLED:"1"}}),Vr(S)}let d=!1;a.once("error",()=>{d=!0}),a.once("exit",(n)=>{d||=n!==0}),a.unref();let f=!1;if(await $e(async()=>d||(f=await o()),_o),!f){if(c&&ge(c).subarray(i).toString("utf8").includes("No usable sandbox"))throw new _("automation_browser_sandbox_unavailable","Chromium found no usable sandbox on this machine. Run the worker as a non-root user with unprivileged user namespaces enabled, or in a container with seccomp unconfined.");throw new _("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function Vs(t){await Ge(t,!0)}function Es(t){return Fe(t,Re(t))}function Fe(t,e){return t.platform==="darwin-arm64"?b(e,"browser-profile"):b(e,"home",".config","google-chrome")}function Re(t){let e=b(t.root,"automation");if(!mt(e)||!Co(t.automation))return t.automation;if(!Bo(Fe(t,e)))try{eo(e,t.automation)}catch{}return mt(e)?e:t.automation}function Co(t){try{return V(t).length===0}catch(e){return e.code==="ENOENT"}}function Bo(t){let e;try{e=to(b(t,"SingletonLock"))}catch{return!1}let r=Number(e.slice(e.lastIndexOf("-")+1));if(!Number.isSafeInteger(r)||r<=0)return!0;try{return process.kill(r,0),!0}catch(o){return o.code==="EPERM"}}async function Ge(t,e){pe({root:t.root,automation:t.automation,extensionDir:t.extensionDir});let r=Re(t);z(r);let o=Te().username,s={USER:o,LOGNAME:o,REASON_AUTOMATION_OCU:t.ocu,REASON_AUTOMATION_OBU:t.nativeHost};if(t.platform==="darwin-arm64"){let n={...s,HOME:q(),PATH:`${bt(t.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:bo};if(!e)return n;await _t("browser",()=>be(t,n,r));let l=await Ie(t.nativeHost,n,r);if(!l)throw new _("automation_browser_unavailable","Reason could not connect the desktop browser.");return{...n,REASON_AUTOMATION_OBU_INSTANCE:l,REASON_AUTOMATION_BACKGROUND_TABS:"1"}}let a=await Je(),c=b(r,"home"),i=b(r,"runtime");z(c),z(i);let d=b(r,"bus"),f={...s,HOME:c,PATH:`${bt(t.node)}:/usr/bin:/bin`,DISPLAY:a.display,XAUTHORITY:a.xauthority,XDG_RUNTIME_DIR:i,DBUS_SESSION_BUS_ADDRESS:`unix:path=${d}`,...a.sound?{PULSE_SERVER:Ne(a.sound)}:{}};if(await _t("bus",()=>qo(d,f)),e)await _t("browser",()=>be(t,f,r));return f}async function Io(t,e,r){let o=Te().username,s={USER:o,LOGNAME:o,HOME:q(),PATH:`${bt(t.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OBU:e,REASON_AUTOMATION_BACKGROUND_TABS:"1"},a=await To(e,s);return r.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:a}}function Ue(t,e,r,o){if(typeof _e!=="string")return Promise.reject(new _("automation_unavailable","This Reason build has no automation runtime."));let s=_e;return new Promise((a,c)=>{let i=I(t,["--input-type=module","--eval",s],{env:{...e,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:!0}),d=[],f=0,n="",l=null,u=!1,m=(w)=>{l??=w;try{process.kill(-i.pid,"SIGKILL")}catch{i.kill("SIGKILL")}},S=(w)=>{if(u)return;u=!0,clearTimeout(B),o.removeEventListener("abort",g),w()},B=setTimeout(()=>m(new _("automation_timed_out","Reason automation did not finish in time.")),no),g=()=>m(new _("cancelled","Reason cancelled the automation call."));if(o.addEventListener("abort",g,{once:!0}),i.stdout.on("data",(w)=>{if(f+=w.byteLength,f>ao)m(new _("automation_output_too_large","Reason automation output is too large."));else d.push(w)}),i.stderr.setEncoding("utf8").on("data",(w)=>{n=(n+w).slice(-io)}),i.stdin.on("error",()=>{}),i.once("error",()=>S(()=>c(l??new _("automation_unavailable","Reason could not start the automation runtime.")))),i.once("close",(w)=>S(()=>{if(l)c(l);else a({code:w??1,stdout:Buffer.concat(d),stderr:n})})),o.aborted)g();i.stdin.end(r)})}var C=new Map;function $o(t,e,r){for(let[s,a]of C)if(a.expiresAt<=r)C.delete(s);while(C.size>=lo)C.delete(C.keys().next().value);let o=Oe();return C.set(o,{runId:t,bytes:e,expiresAt:r+fo}),o}async function Le(t,e,r,o={}){let s=await(o.environment??Ge)(t,e.kind==="browser");return r.throwIfAborted(),await(o.runtime??Ue)(t.node,s,JSON.stringify(e),r)}async function vs(t,e){let r=qe({call:t});if(!("call"in r))K();let o=$();if(!o?.features.computer||r.call.kind==="browser"&&!o.features.browser)throw new _("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");return await Le(o,r.call,e)}function we(t,e,r){let o=t.stdout.byteLength>wt?$o(e,t.stdout,r):void 0;return{code:t.code,stderr:t.stderr,instance_id:mo,output_bytes:t.stdout.byteLength,chunk:t.stdout.subarray(0,wt).toString("base64"),...o?{output_id:o}:{}}}async function ta(t,e={}){let r=qe(t.payload),o=(e.now??Date.now)();if("output_id"in r){let m=C.get(r.output_id);if(!m||m.runId!==t.runId||m.expiresAt<=o||r.offset>m.bytes.byteLength)throw new _("automation_output_unavailable","Reason automation output expired.");return{chunk:m.bytes.subarray(r.offset,r.offset+wt).toString("base64")}}let s=(e.components??$)(),a=(e.platform??process.platform)==="darwin",c=a?(e.macIdentity??St)():[],i=e.macSetup??X,d=!s?.features.computer||r.call.kind==="browser"&&!r.userChrome&&!s.features.browser;if(a&&(d||c.length===0||r.call.kind==="browser"&&r.userChrome&&!t.userChrome))return we(await ft({runId:t.runId,call:r.call,identity:c,desktopMissing:d,signal:t.signal},i),t.runId,o);if(!s?.features.computer)throw new _("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let f=r.userChrome?t.userChrome:void 0;if(r.userChrome&&!f)throw new _("automation_user_chrome_unavailable","Your own Chrome is not enabled on this computer: run `reason desktop install` on this Mac (and `reason connect --user-chrome on` if you turned it off).");if(r.call.kind==="browser"&&!f&&!s.features.browser)throw new _("automation_browser_not_installed",s.platform==="darwin-arm64"?"Browser use is unavailable on this machine: re-run `reason desktop install`.":"Browser use is unavailable on this machine: install a non-snap Chromium at /usr/bin/chromium, then re-run `reason desktop install`.");t.signal.throwIfAborted();let n=await ye(t.runId,t.signal,e.now),l="account"in e?e.account??null:Se(),u;try{if(f){let m=await(e.userChromeEnvironment??Io)(s,f,t.signal);t.signal.throwIfAborted(),u=await(e.runtime??Ue)(s.node,m,JSON.stringify(r.call),t.signal)}else if(l)u=await(e.delegate??Ot)(l,r.call,t.signal);else u=await Le(s,r.call,t.signal,e)}catch(m){if(!a||!(m instanceof _)||m.code!=="automation_user_chrome_not_connected")throw m;u=await ft({runId:t.runId,call:r.call,identity:c,desktopMissing:!1,signal:t.signal},i)}finally{n()}if(a)u=await ne({runId:t.runId,call:r.call,identity:c,output:u,signal:t.signal},i);return we(u,t.runId,o)}
|
|
760
|
-
export{
|
|
759
|
+
`),2;let[a,...c]=o;return(e.run??xo)(a,[...c,s.ocu,"mcp"],{...process.env,OPEN_COMPUTER_USE_DISABLE_APP_AGENT_PROXY:"1"})}function Ks(t=$){return t()?.userChrome??{code:"user_chrome_browser_use_missing"}}function Ce(t,e,r,o){return new Promise((s)=>{let a=I(t,e,{env:r,stdio:"ignore"}),c=setTimeout(()=>{a.kill("SIGKILL"),s(-1)},o);a.once("error",()=>{clearTimeout(c),s(-1)}),a.once("exit",(i)=>{clearTimeout(c),s(i??-1)})})}function So(t,e,r,o){return new Promise((s)=>{let a=I(t,e,{env:r,stdio:["ignore","pipe","ignore"]}),c="";a.stdout.setEncoding("utf8").on("data",(d)=>{c+=d});let i=setTimeout(()=>{a.kill("SIGKILL"),s(null)},o);a.once("error",()=>{clearTimeout(i),s(null)}),a.once("close",(d)=>{clearTimeout(i),s(d===0?c:null)})})}var po="/tmp/open-browser-use",yo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ao=33554432;function No(t,e){let r;try{r=t===null?null:JSON.parse(t)}catch{return null}let o=H(r)&&H(r.result)?r.result.metadata:null;if(!H(o)||o.extensionId!==e)return null;return typeof o.extensionInstanceId==="string"&&yo.test(o.extensionInstanceId)?o.extensionInstanceId:null}async function Be(t,e,r){let o=r.storages.map((i)=>{try{return V(i).filter((d)=>d.endsWith(".log")||d.endsWith(".ldb")).map((d)=>b(i,d))}catch{return[]}}),s;try{s=o.some((i)=>i.length>0)?V(r.socketDir).filter((i)=>i.endsWith(".sock")):[]}catch{return[]}let a=[];for(let i of s){let d=b(r.socketDir,i),f=No(await So(t,["info","--socket",d,"--timeout","2s"],e,5000),r.extensionId);if(f)a.push({instance:f,socket:d})}let c=[];for(let[i,d]of(a.length>0?o:[]).entries())for(let f of d)try{if(oo(f).size>Ao)continue;let n=ge(f),l=a.find((u)=>n.includes(u.instance));if(l){c.push({storage:r.storages[i],...l});break}}catch{}return c}async function Oo(t,e,r){return(await Be(t,e,r))[0]?.instance??null}function Ie(t,e,r){return Oo(t,e,{socketDir:po,extensionId:_t,storages:[b(r,"browser-profile","Default","Local Extension Settings",_t)]})}var ue=/^(Default|Profile ([0-9]+))$/;async function go(t,e,r=q(),o=St){let s=b(r,"Library","Application Support","Google","Chrome"),a=[];try{a=V(s)}catch(n){if(n.code==="EPERM")throw new _("browser_use_chrome_access_denied","macOS blocked Reason from reading Chrome's profiles. Allow Full Disk Access for Reason on this Mac and try again.")}let c=(n)=>Number(ue.exec(n)?.[2]??-1),i=a.filter((n)=>ue.test(n)&&ut(b(s,n,"Extensions",W))).sort((n,l)=>c(n)-c(l)),d=(n)=>b(s,n,"Local Extension Settings",W);return(await Be(t,e,{socketDir:o,extensionId:W,storages:i.map(d)})).map(({storage:n,instance:l,socket:u})=>({profile:i.find((m)=>d(m)===n),instance:l,socket:u}))}async function To(t,e,r=q(),o=St){let s=(await go(t,e,r,o))[0]?.instance;if(!s)throw new _("automation_user_chrome_not_connected","No Chrome profile on this Mac is connected to Reason. Open Chrome with the Reason extension, then try again.");return s}function me(t){return new Promise((e)=>{let r=so({path:t}),o=(s)=>{r.destroy(),e(s)};r.setTimeout(1000,()=>o(!1)),r.once("error",()=>o(!1)),r.once("connect",()=>o(!0))})}async function $e(t,e){let r=Date.now()+e;while(Date.now()<r){if(await t())return!0;await new Promise((o)=>setTimeout(o,200))}return!1}var ft=new Map;function lt(t,e){let r=ft.get(t);if(!r)r=e().finally(()=>ft.delete(t)),ft.set(t,r);return r}async function qo(t,e){if(await me(t))return;if(ro(t,{force:!0}),await Ce("dbus-daemon",["--session",`--address=unix:path=${t}`,"--fork"],e,1e4)!==0||!await $e(()=>me(t),5000))throw new _("automation_unavailable","Reason could not start the desktop session bus.")}async function be(t,e,r){let o=t.platform==="darwin-arm64"?async()=>await Ie(t.nativeHost,e,r)!==null:async()=>await Ce(t.nativeHost,["info"],e,5000)===0;if(await o())return;let s=["--profile-directory=Default",`--load-extension=${t.extensionDir}`,"--no-first-run","--no-default-browser-check","--window-size=1280,800","about:blank"],a,c=null,i=0;if(t.platform==="darwin-arm64"){let n=b(r,"browser-profile");z(n);let l=b(n,"NativeMessagingHosts");fe(l,{recursive:!0,mode:448});let u=wt(t.platform).nativeHostManifests[0];de(u,b(l,le(u)));let m=t.browser.slice(0,t.browser.indexOf(".app/")+4),S=s.filter((B)=>B!=="about:blank").concat("--no-startup-window","--use-mock-keychain");a=I("/usr/bin/open",["-g","-n","-a",m,"--args",`--user-data-dir=${n}`,...S],{env:e,stdio:"ignore"})}else{let n=b(e.HOME,".config","google-chrome"),l=b(n,"NativeMessagingHosts");fe(l,{recursive:!0,mode:448});let u=wt(t.platform).nativeHostManifests[0];de(u,b(l,le(u)));let m=process.geteuid?.()===0?["--no-sandbox"]:[];c=b(r,"browser.log");let S=vr(c,"a",384);i=Er(S).size,a=I(t.browser,[`--user-data-dir=${n}`,...s,...m,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",S,S],env:{...e,ACCESSIBILITY_ENABLED:"1"}}),Vr(S)}let d=!1;a.once("error",()=>{d=!0}),a.once("exit",(n)=>{d||=n!==0}),a.unref();let f=!1;if(await $e(async()=>d||(f=await o()),_o),!f){if(c&&ge(c).subarray(i).toString("utf8").includes("No usable sandbox"))throw new _("automation_browser_sandbox_unavailable","Chromium found no usable sandbox on this machine. Run the worker as a non-root user with unprivileged user namespaces enabled, or in a container with seccomp unconfined.");throw new _("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function Vs(t){await Ge(t,!0)}function Es(t){return Fe(t,Re(t))}function Fe(t,e){return t.platform==="darwin-arm64"?b(e,"browser-profile"):b(e,"home",".config","google-chrome")}function Re(t){let e=b(t.root,"automation");if(!ut(e)||!Co(t.automation))return t.automation;if(!Bo(Fe(t,e)))try{eo(e,t.automation)}catch{}return ut(e)?e:t.automation}function Co(t){try{return V(t).length===0}catch(e){return e.code==="ENOENT"}}function Bo(t){let e;try{e=to(b(t,"SingletonLock"))}catch{return!1}let r=Number(e.slice(e.lastIndexOf("-")+1));if(!Number.isSafeInteger(r)||r<=0)return!0;try{return process.kill(r,0),!0}catch(o){return o.code==="EPERM"}}async function Ge(t,e){pe({root:t.root,automation:t.automation,extensionDir:t.extensionDir});let r=Re(t);z(r);let o=Te().username,s={USER:o,LOGNAME:o,REASON_AUTOMATION_OCU:t.ocu,REASON_AUTOMATION_OBU:t.nativeHost};if(t.platform==="darwin-arm64"){let n={...s,HOME:q(),PATH:`${mt(t.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:bo};if(!e)return n;await lt("browser",()=>be(t,n,r));let l=await Ie(t.nativeHost,n,r);if(!l)throw new _("automation_browser_unavailable","Reason could not connect the desktop browser.");return{...n,REASON_AUTOMATION_OBU_INSTANCE:l,REASON_AUTOMATION_BACKGROUND_TABS:"1"}}let a=await Je(),c=b(r,"home"),i=b(r,"runtime");z(c),z(i);let d=b(r,"bus"),f={...s,HOME:c,PATH:`${mt(t.node)}:/usr/bin:/bin`,DISPLAY:a.display,XAUTHORITY:a.xauthority,XDG_RUNTIME_DIR:i,DBUS_SESSION_BUS_ADDRESS:`unix:path=${d}`,...a.sound?{PULSE_SERVER:Ne(a.sound)}:{}};if(await lt("bus",()=>qo(d,f)),e)await lt("browser",()=>be(t,f,r));return f}async function Io(t,e,r){let o=Te().username,s={USER:o,LOGNAME:o,HOME:q(),PATH:`${mt(t.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OBU:e,REASON_AUTOMATION_BACKGROUND_TABS:"1"},a=await To(e,s);return r.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:a}}function Ue(t,e,r,o){if(typeof _e!=="string")return Promise.reject(new _("automation_unavailable","This Reason build has no automation runtime."));let s=_e;return new Promise((a,c)=>{let i=I(t,["--input-type=module","--eval",s],{env:{...e,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:!0}),d=[],f=0,n="",l=null,u=!1,m=(w)=>{l??=w;try{process.kill(-i.pid,"SIGKILL")}catch{i.kill("SIGKILL")}},S=(w)=>{if(u)return;u=!0,clearTimeout(B),o.removeEventListener("abort",g),w()},B=setTimeout(()=>m(new _("automation_timed_out","Reason automation did not finish in time.")),no),g=()=>m(new _("cancelled","Reason cancelled the automation call."));if(o.addEventListener("abort",g,{once:!0}),i.stdout.on("data",(w)=>{if(f+=w.byteLength,f>ao)m(new _("automation_output_too_large","Reason automation output is too large."));else d.push(w)}),i.stderr.setEncoding("utf8").on("data",(w)=>{n=(n+w).slice(-io)}),i.stdin.on("error",()=>{}),i.once("error",()=>S(()=>c(l??new _("automation_unavailable","Reason could not start the automation runtime.")))),i.once("close",(w)=>S(()=>{if(l)c(l);else a({code:w??1,stdout:Buffer.concat(d),stderr:n})})),o.aborted)g();i.stdin.end(r)})}var C=new Map;function $o(t,e,r){for(let[s,a]of C)if(a.expiresAt<=r)C.delete(s);while(C.size>=lo)C.delete(C.keys().next().value);let o=Oe();return C.set(o,{runId:t,bytes:e,expiresAt:r+fo}),o}async function Le(t,e,r,o={}){let s=await(o.environment??Ge)(t,e.kind==="browser");return r.throwIfAborted(),await(o.runtime??Ue)(t.node,s,JSON.stringify(e),r)}async function vs(t,e){let r=qe({call:t});if(!("call"in r))K();let o=$();if(!o?.features.computer||r.call.kind==="browser"&&!o.features.browser)throw new _("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");return await Le(o,r.call,e)}function we(t,e,r){let o=t.stdout.byteLength>bt?$o(e,t.stdout,r):void 0;return{code:t.code,stderr:t.stderr,instance_id:mo,output_bytes:t.stdout.byteLength,chunk:t.stdout.subarray(0,bt).toString("base64"),...o?{output_id:o}:{}}}async function ta(t,e={}){let r=qe(t.payload),o=(e.now??Date.now)();if("output_id"in r){let m=C.get(r.output_id);if(!m||m.runId!==t.runId||m.expiresAt<=o||r.offset>m.bytes.byteLength)throw new _("automation_output_unavailable","Reason automation output expired.");return{chunk:m.bytes.subarray(r.offset,r.offset+bt).toString("base64")}}let s=(e.components??$)(),a=(e.platform??process.platform)==="darwin",c=a?(e.macIdentity??xt)():[],i=e.macSetup??X,d=!s?.features.computer||r.call.kind==="browser"&&!r.userChrome&&!s.features.browser;if(a&&(d||c.length===0||r.call.kind==="browser"&&r.userChrome&&!t.userChrome))return we(await ce({runId:t.runId,call:r.call,identity:c,desktopMissing:d,signal:t.signal},i),t.runId,o);if(!s?.features.computer)throw new _("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let f=r.userChrome?t.userChrome:void 0;if(r.userChrome&&!f)throw new _("automation_user_chrome_unavailable","Your own Chrome is not enabled on this computer: run `reason desktop install` on this Mac (and `reason connect --user-chrome on` if you turned it off).");if(r.call.kind==="browser"&&!f&&!s.features.browser)throw new _("automation_browser_not_installed",s.platform==="darwin-arm64"?"Browser use is unavailable on this machine: re-run `reason desktop install`.":"Browser use is unavailable on this machine: install a non-snap Chromium at /usr/bin/chromium, then re-run `reason desktop install`.");t.signal.throwIfAborted();let n=await ye(t.runId,t.signal,e.now),l="account"in e?e.account??null:Se(),u;try{if(f){let m=await(e.userChromeEnvironment??Io)(s,f,t.signal);t.signal.throwIfAborted(),u=await(e.runtime??Ue)(s.node,m,JSON.stringify(r.call),t.signal)}else if(l)u=await(e.delegate??Nt)(l,r.call,t.signal);else u=await Le(s,r.call,t.signal,e)}finally{n()}if(a)u=await ne({runId:t.runId,call:r.call,identity:c,output:u,signal:t.signal},i);return we(u,t.runId,o)}
|
|
760
|
+
export{Ut as lc,at as mc,Dt as nc,A as oc,Mt as pc,cs as qc,kt as rc,ns as sc,dt as tc,Ur as uc,ds as vc,fs as wc,ls as xc,_s as yc,us as zc,ms as Ac,We as Bc,bt as Cc,qe as Dc,Ws as Ec,xo as Fc,Hs as Gc,Ks as Hc,go as Ic,To as Jc,Vs as Kc,Es as Lc,vs as Mc,ta as Nc};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$a as n6,Ea as u6,Ga as w4,Ha as O4,Ma as l6,Na as s6,Xa as I4,ab as r6,bb as S4,cb as k4,eb as a6,ga as U4,gb as B8,hb as y0,ia as W2,ib as m0,ja as X4,jb as c1,ka as W4,la as Y4,ma as S6,mb as i6,na as f6,oa as M4,pa as b6,pb as V8,qa as A3,qb as A4,ra as x6,sa as y6,sb as o6,ta as h6,ua as m6,va as L4,wa as v6,xa as p6}from"./vm-hands-entry-lite-naxss5d5.js";import{Ab as n0,Bb as r0,Ib as P0,tb as i3,ub as q6,vb as E6}from"./vm-hands-entry-lite-rrk5g62b.js";import{Jb as t6,Mb as e6,Ob as $7,Pb as J7}from"./vm-hands-entry-lite-ya1a2eep.js";import{Ub as d6}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Vb as _6,Wb as R6,Xb as P6,Yb as z6,Zb as L0}from"./vm-hands-entry-lite-n07kxrd1.js";import{$b as o1,ac as t1,bc as S3,dc as k3,fc as f3,gc as b3,kc as x3}from"./vm-hands-entry-lite-0ergg2ky.js";import{Bc as r1,Ec as H7,Nc as D7}from"./vm-hands-entry-lite-qdvts5kj.js";import{$c as d,$d as g8,Ad as w6,Cd as O6,Dd as j6,Ed as I6,Fd as A6,Gd as T6,Ld as D8,Md as M8,Nd as L8,Oc as L1,Od as w8,Pc as Q2,Pd as O8,Qc as e5,Qd as j8,Rc as I3,Sc as r3,Sd as I8,Tc as a3,Td as A8,Uc as M0,Ud as T8,Vd as _8,Wd as R8,Xd as P8,Yc as N0,Yd as z8,Zd as q8,_d as E8,ad as E1,dd as H8,fd as g1,hd as $6,id as J6,jd as Z6,kd as Q6,ld as K6,md as B6,nd as V6,od as G6,pd as U6,qd as X6,rd as W6,sd as Y6,td as F6,ud as N6,vd as C6,wd as H6,xd as D6,yd as M6,zd as L6}from"./vm-hands-entry-lite-8st97h7b.js";import{ae as V}from"./vm-hands-entry-lite-q6fshf3h.js";import{Ae as l1,be as W7,ce as Y7,de as F7,ee as N7,fe as C7,le as p5,pe as Q5,qe as T5,we as M7,ze as K5}from"./vm-hands-entry-lite-7zaerpzt.js";import{Ze as j4,ef as c6}from"./vm-hands-entry-lite-pf1ft65e.js";import{jf as M3,wf as g6}from"./vm-hands-entry-lite-q2pb31vh.js";import{Bg as Z7,Cg as Q7,Dg as K7,Eg as B7,Gg as V7,Hg as G7,Jg as U7,Kg as X7}from"./vm-hands-entry-lite-6j2yaa4n.js";import{Yg as n1}from"./vm-hands-entry-lite-7k65s010.js";import{$g as k6,_g as j1,ah as H4,bh as D4}from"./vm-hands-entry-lite-em388nee.js";import{dh as D3,fh as $1,lh as K8,mh as J4}from"./vm-hands-entry-lite-yp315y25.js";import{Kh as H}from"./vm-hands-entry-lite-xsq25kmd.js";import{Oh as a4}from"./vm-hands-entry-lite-hf0mk7vd.js";import{request as m7}from"http";import{request as v7}from"https";async function p7($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?v7:m7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:k3},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Error("custom_endpoint_timeout"))),K.end($.body)})}function u7($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function d7($,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 F=K[B-1];Y+=Z.copy(W,Y,0,B-F),B=F}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 y3($){$.signal.throwIfAborted();let J=b3.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=x3.parse(await $.credential($.signal));if(!f3(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=u7(Q.apiKey),X=d7(Q.apiKey,Y),F=async(N,D)=>{$.signal.throwIfAborted(),await new Promise((w,M)=>{let I=()=>{$.signal.removeEventListener("abort",I),M($.signal.reason)};if($.signal.addEventListener("abort",I,{once:!0}),$.signal.aborted){I();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,D)}).then(()=>{$.signal.removeEventListener("abort",I),w()},(O)=>{$.signal.removeEventListener("abort",I),M(O)})})},C=async(N)=>{if(G+=N.length,G>t1)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<N.length;D+=o1){if(W>=S3)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await F(`custom_endpoint.chunk.${W++}`,{eof:!1,data:N.subarray(D,D+o1).toString("base64")})}};try{let N=await p7({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=N.response,B=N.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 I=K.headers[M];if(typeof I==="string")w[M]=I.replaceAll(Q.apiKey,Y).slice(0,4096)}await F("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 I=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=I.length,U>t1)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await C(X(I))}return await C(X(Buffer.alloc(0),!0)),await F(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(N){if($.signal.throwIfAborted(),N instanceof H)throw N;throw new H("custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as h3}from"path";function l7($,J){return $===h3(J,".ara","workspace")||$===h3(J,".reason","workspace")}function m3($,J){let Z=$.filter((Q)=>l7(Q.path,J));return Z.length===1?Z[0].path:null}var s7=/^[a-f0-9]{64}$/;var e1=32,c7=/^\/[^\x00-\x1f\x7f\\]*$/;function H1($){if(typeof $!=="string"||$.length>4096||!c7.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function D1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!H1(J.home)||!Array.isArray(J.roots)||J.roots.length>e1)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"||!s7.test(K)||!H1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}import{spawn as r7}from"child_process";import*as z from"fs";import*as s from"path";import{homedir as a7}from"os";function $2($,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 v3($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var p3=[{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 J2($){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 u3($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function d3($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function M1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=u3(J).filter((G)=>!K.has(G));for(let G of $){let U=J2(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,F)=>X.offset-F.offset);if(Y.length>0){let X=[...new Set(Y.flatMap((F)=>Z.secretNames?.(F.secret)??[]))];Q.push({path:G.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:v3(W,Y[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of p3){let F=d3(X,W).find((C)=>!K.has(C[0]));if(F){Q.push({path:G.path,reason:`credential_pattern_detected: ${X.name}`,pattern:X.name,ruleId:X.name,line:v3(W,F.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function l3($,J=[]){let Z=u3(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 p3)for(let G of d3(B,K))Q.add(G[0])}return[...Q]}function n7($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function s3($,J,Z){let Q=(K,B)=>K.reduce((G,U)=>G+n7(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var T0=4194304,c3=536870912,Z2=/^[a-f0-9]{40}$/,i7=($,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=r7($,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=(N)=>{if(U??=Error(N),K.pid)try{process.kill(-K.pid,"SIGKILL")}catch{}},X=()=>Y("cancelled"),F=setTimeout(()=>Y("timeout"),Z.timeout);Z.signal?.addEventListener("abort",X,{once:!0});let C=(N)=>{if(W)return;W=!0,clearTimeout(F),Z.signal?.removeEventListener("abort",X),Q({status:N,stdout:B,stderr:G,...U?{error:U}:{}})};if(K.stdout.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)Y("output_limit");else B=Buffer.concat([B,N])}),K.stderr.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)Y("output_limit");else G=Buffer.concat([G,N])}),K.on("error",()=>{if(Y("spawn_failed"),!K.pid)C(null)}),K.on("close",(N)=>C(N)),K.stdin.on("error",()=>Y("input_failed")),K.stdin.end(Z.input),Z.signal?.aborted)X()}),o7={command:i7,gh:($,J)=>$2(z,s,$,J),home:a7};function A($){throw Error($)}var t7=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),e7=($)=>JSON.stringify($,(J,Z)=>t7.has(J)?void 0:Z);function n3($,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 o3($,J,Z=o7){let Q=L1.parse($);if(!["darwin","linux"].includes(process.platform))A("local_device_gh_platform_unavailable");J.assertCurrent();let K=z.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=M1([{path:"github-operation",content:e7(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!L.clean)n3(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=$2(z,s,K,"git"),W=J.privateDirectory?z.realpathSync(J.privateDirectory):z.realpathSync(G);if(!M0(Q)&&(!J.privateDirectory||W===K||W.startsWith(K+s.sep)))A("local_device_gh_private_scope_unavailable");let Y={PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:G,GH_CONFIG_DIR:s.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},F=async(L)=>(await X(B,L)).toString("utf8").trim(),C=async(L,T="application/vnd.github+json")=>{r3(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])>Q2)A("local_device_gh_response_too_large");let y={};for(let r of k[2].split(/\r?\n/)){let a=r.indexOf(":"),D0=r.slice(0,a).toLowerCase();if(["link","content-type"].includes(D0))y[D0]=r.slice(a+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 F(["api","graphql","--hostname","github.com","-f",`query=${a3}`,"-f",`owner=${L}`,"-f",`repo=${T}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(P)>Q2)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 F(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha]);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 F(["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 F(["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 N=z.realpathSync(J.repoPath);if(N!==K&&!N.startsWith(K+s.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 ("+i3+")")(),I=(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+s.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 r=s.join(N,".ara-local-gh-tmp");if(z.mkdirSync(r,{recursive:!0,mode:448}),z.lstatSync(r).isSymbolicLink()||z.realpathSync(r)!==r)A("local_device_gh_workspace_unavailable");J.assertCurrent();let a=await Z.command(...I(M(N,r),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:N,TMPDIR:r,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(),a.error||a.status!==0)A("local_device_gh_collection_failed");return a.stdout},R=async(L,T)=>(await O(L,T)).toString("utf8").trim(),E=async(L,T)=>{let P=s.join(L,".ara-local-gh-tmp");if(z.mkdirSync(P,{recursive:!0,mode:448}),z.lstatSync(P).isSymbolicLink()||z.realpathSync(P)!==P)A("local_device_gh_workspace_unavailable");J.assertCurrent();let k=await Z.command(...I(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(S,["cat-file","--batch"],[...new Set(L)].join(`
|
|
2
|
+
import{$a as n6,Ea as u6,Ga as w4,Ha as O4,Ma as l6,Na as s6,Xa as I4,ab as r6,bb as S4,cb as k4,eb as a6,ga as U4,gb as B8,hb as y0,ia as W2,ib as m0,ja as X4,jb as c1,ka as W4,la as Y4,ma as S6,mb as i6,na as f6,oa as M4,pa as b6,pb as V8,qa as A3,qb as A4,ra as x6,sa as y6,sb as o6,ta as h6,ua as m6,va as L4,wa as v6,xa as p6}from"./vm-hands-entry-lite-sg20hwxb.js";import{Ab as n0,Bb as r0,Ib as P0,tb as i3,ub as q6,vb as E6}from"./vm-hands-entry-lite-rrk5g62b.js";import{Jb as t6,Mb as e6,Ob as $7,Pb as J7}from"./vm-hands-entry-lite-ya1a2eep.js";import{Ub as d6}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Vb as _6,Wb as R6,Xb as P6,Yb as z6,Zb as L0}from"./vm-hands-entry-lite-n07kxrd1.js";import{$b as o1,ac as t1,bc as S3,dc as k3,fc as f3,gc as b3,kc as x3}from"./vm-hands-entry-lite-0ergg2ky.js";import{Bc as r1,Ec as H7,Nc as D7}from"./vm-hands-entry-lite-ncty87q3.js";import{$c as d,$d as g8,Ad as w6,Cd as O6,Dd as j6,Ed as I6,Fd as A6,Gd as T6,Ld as D8,Md as M8,Nd as L8,Oc as L1,Od as w8,Pc as Q2,Pd as O8,Qc as e5,Qd as j8,Rc as I3,Sc as r3,Sd as I8,Tc as a3,Td as A8,Uc as M0,Ud as T8,Vd as _8,Wd as R8,Xd as P8,Yc as N0,Yd as z8,Zd as q8,_d as E8,ad as E1,dd as H8,fd as g1,hd as $6,id as J6,jd as Z6,kd as Q6,ld as K6,md as B6,nd as V6,od as G6,pd as U6,qd as X6,rd as W6,sd as Y6,td as F6,ud as N6,vd as C6,wd as H6,xd as D6,yd as M6,zd as L6}from"./vm-hands-entry-lite-8st97h7b.js";import{ae as V}from"./vm-hands-entry-lite-q6fshf3h.js";import{Ae as l1,be as W7,ce as Y7,de as F7,ee as N7,fe as C7,le as p5,pe as Q5,qe as T5,we as M7,ze as K5}from"./vm-hands-entry-lite-bsfm2m38.js";import{Ze as j4,ef as c6}from"./vm-hands-entry-lite-pf1ft65e.js";import{jf as M3,wf as g6}from"./vm-hands-entry-lite-q2pb31vh.js";import{Bg as Z7,Cg as Q7,Dg as K7,Eg as B7,Gg as V7,Hg as G7,Jg as U7,Kg as X7}from"./vm-hands-entry-lite-6j2yaa4n.js";import{Yg as n1}from"./vm-hands-entry-lite-7k65s010.js";import{$g as k6,_g as j1,ah as H4,bh as D4}from"./vm-hands-entry-lite-em388nee.js";import{dh as D3,fh as $1,lh as K8,mh as J4}from"./vm-hands-entry-lite-yp315y25.js";import{Kh as H}from"./vm-hands-entry-lite-xsq25kmd.js";import{Oh as a4}from"./vm-hands-entry-lite-hf0mk7vd.js";import{request as m7}from"http";import{request as v7}from"https";async function p7($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?v7:m7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:k3},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Error("custom_endpoint_timeout"))),K.end($.body)})}function u7($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function d7($,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 F=K[B-1];Y+=Z.copy(W,Y,0,B-F),B=F}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 y3($){$.signal.throwIfAborted();let J=b3.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=x3.parse(await $.credential($.signal));if(!f3(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=u7(Q.apiKey),X=d7(Q.apiKey,Y),F=async(N,D)=>{$.signal.throwIfAborted(),await new Promise((w,M)=>{let I=()=>{$.signal.removeEventListener("abort",I),M($.signal.reason)};if($.signal.addEventListener("abort",I,{once:!0}),$.signal.aborted){I();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,D)}).then(()=>{$.signal.removeEventListener("abort",I),w()},(O)=>{$.signal.removeEventListener("abort",I),M(O)})})},C=async(N)=>{if(G+=N.length,G>t1)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<N.length;D+=o1){if(W>=S3)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await F(`custom_endpoint.chunk.${W++}`,{eof:!1,data:N.subarray(D,D+o1).toString("base64")})}};try{let N=await p7({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=N.response,B=N.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 I=K.headers[M];if(typeof I==="string")w[M]=I.replaceAll(Q.apiKey,Y).slice(0,4096)}await F("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 I=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=I.length,U>t1)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await C(X(I))}return await C(X(Buffer.alloc(0),!0)),await F(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(N){if($.signal.throwIfAborted(),N instanceof H)throw N;throw new H("custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as h3}from"path";function l7($,J){return $===h3(J,".ara","workspace")||$===h3(J,".reason","workspace")}function m3($,J){let Z=$.filter((Q)=>l7(Q.path,J));return Z.length===1?Z[0].path:null}var s7=/^[a-f0-9]{64}$/;var e1=32,c7=/^\/[^\x00-\x1f\x7f\\]*$/;function H1($){if(typeof $!=="string"||$.length>4096||!c7.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function D1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!H1(J.home)||!Array.isArray(J.roots)||J.roots.length>e1)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"||!s7.test(K)||!H1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}import{spawn as r7}from"child_process";import*as z from"fs";import*as s from"path";import{homedir as a7}from"os";function $2($,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 v3($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var p3=[{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 J2($){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 u3($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function d3($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function M1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=u3(J).filter((G)=>!K.has(G));for(let G of $){let U=J2(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,F)=>X.offset-F.offset);if(Y.length>0){let X=[...new Set(Y.flatMap((F)=>Z.secretNames?.(F.secret)??[]))];Q.push({path:G.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:v3(W,Y[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of p3){let F=d3(X,W).find((C)=>!K.has(C[0]));if(F){Q.push({path:G.path,reason:`credential_pattern_detected: ${X.name}`,pattern:X.name,ruleId:X.name,line:v3(W,F.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function l3($,J=[]){let Z=u3(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 p3)for(let G of d3(B,K))Q.add(G[0])}return[...Q]}function n7($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function s3($,J,Z){let Q=(K,B)=>K.reduce((G,U)=>G+n7(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var T0=4194304,c3=536870912,Z2=/^[a-f0-9]{40}$/,i7=($,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=r7($,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=(N)=>{if(U??=Error(N),K.pid)try{process.kill(-K.pid,"SIGKILL")}catch{}},X=()=>Y("cancelled"),F=setTimeout(()=>Y("timeout"),Z.timeout);Z.signal?.addEventListener("abort",X,{once:!0});let C=(N)=>{if(W)return;W=!0,clearTimeout(F),Z.signal?.removeEventListener("abort",X),Q({status:N,stdout:B,stderr:G,...U?{error:U}:{}})};if(K.stdout.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)Y("output_limit");else B=Buffer.concat([B,N])}),K.stderr.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)Y("output_limit");else G=Buffer.concat([G,N])}),K.on("error",()=>{if(Y("spawn_failed"),!K.pid)C(null)}),K.on("close",(N)=>C(N)),K.stdin.on("error",()=>Y("input_failed")),K.stdin.end(Z.input),Z.signal?.aborted)X()}),o7={command:i7,gh:($,J)=>$2(z,s,$,J),home:a7};function A($){throw Error($)}var t7=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),e7=($)=>JSON.stringify($,(J,Z)=>t7.has(J)?void 0:Z);function n3($,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 o3($,J,Z=o7){let Q=L1.parse($);if(!["darwin","linux"].includes(process.platform))A("local_device_gh_platform_unavailable");J.assertCurrent();let K=z.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=M1([{path:"github-operation",content:e7(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!L.clean)n3(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=$2(z,s,K,"git"),W=J.privateDirectory?z.realpathSync(J.privateDirectory):z.realpathSync(G);if(!M0(Q)&&(!J.privateDirectory||W===K||W.startsWith(K+s.sep)))A("local_device_gh_private_scope_unavailable");let Y={PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:G,GH_CONFIG_DIR:s.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},F=async(L)=>(await X(B,L)).toString("utf8").trim(),C=async(L,T="application/vnd.github+json")=>{r3(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])>Q2)A("local_device_gh_response_too_large");let y={};for(let r of k[2].split(/\r?\n/)){let a=r.indexOf(":"),D0=r.slice(0,a).toLowerCase();if(["link","content-type"].includes(D0))y[D0]=r.slice(a+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 F(["api","graphql","--hostname","github.com","-f",`query=${a3}`,"-f",`owner=${L}`,"-f",`repo=${T}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(P)>Q2)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 F(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha]);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 F(["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 F(["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 N=z.realpathSync(J.repoPath);if(N!==K&&!N.startsWith(K+s.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 ("+i3+")")(),I=(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+s.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 r=s.join(N,".ara-local-gh-tmp");if(z.mkdirSync(r,{recursive:!0,mode:448}),z.lstatSync(r).isSymbolicLink()||z.realpathSync(r)!==r)A("local_device_gh_workspace_unavailable");J.assertCurrent();let a=await Z.command(...I(M(N,r),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:N,TMPDIR:r,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(),a.error||a.status!==0)A("local_device_gh_collection_failed");return a.stdout},R=async(L,T)=>(await O(L,T)).toString("utf8").trim(),E=async(L,T)=>{let P=s.join(L,".ara-local-gh-tmp");if(z.mkdirSync(P,{recursive:!0,mode:448}),z.lstatSync(P).isSymbolicLink()||z.realpathSync(P)!==P)A("local_device_gh_workspace_unavailable");J.assertCurrent();let k=await Z.command(...I(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(S,["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,r,a]=P.subarray(k,x).toString("utf8").split(" ");if(x<0||!y||r!=="blob"||!/^[0-9]+$/.test(a??""))A("local_device_gh_object_invalid");T.set(y,P.subarray(x+1,x+1+Number(a)).toString("utf8")),k=x+1+Number(a)+1}return T},j=async(L,T,P)=>{let k=s.join(N,".ara-local-gh-tmp"),x=M(N,k)+`
|
|
5
5
|
(allow file-read* file-write* (subpath ${JSON.stringify(N)}))
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ch as $}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ch as $}from"./vm-hands-entry-lite-erxpqz9e.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 yh,Z as zh,S as Ah,k as Bh};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{t as d0}from"./vm-hands-entry-lite-bswnp5ve.js";import{A as Y5,B as G5,C as A7,D as R7,E as v3,F as a5,G as V5,H as _0,I as l$,J as p$,K as S0,L as J2,M as i5,N as n0,O as q6,P as Z3,Q as J6,U as Z6,ba as I7,ca as x7,da as E7,ea as S7,fa as u3,y as d6,z as l6}from"./vm-hands-entry-lite-
|
|
2
|
+
import{t as d0}from"./vm-hands-entry-lite-bswnp5ve.js";import{A as Y5,B as G5,C as A7,D as R7,E as v3,F as a5,G as V5,H as _0,I as l$,J as p$,K as S0,L as J2,M as i5,N as n0,O as q6,P as Z3,Q as J6,U as Z6,ba as I7,ca as x7,da as E7,ea as S7,fa as u3,y as d6,z as l6}from"./vm-hands-entry-lite-nqgg6v5n.js";import{Aa as B5,Ba as K5,Ca as W7,Da as L7,Fa as u,Ga as e,Ha as s,Ia as c,Ja as F5,Ka as j7,La as W$,Oa as V4,Pa as H4,Qa as RJ,Ra as CJ,Sa as PJ,Ta as y0,Ua as J0,Va as g,Wa as g3,Xa as E$,Ya as K2,Za as U0,_a as z7,db as N6,fb as h8,ha as n7,ib as u2,ka as j5,kb as s5,la as z5,lb as T3,nb as f5,oa as _5,qa as x5,rb as O7,sb as N3,ta as E5,ya as k5,za as y5}from"./vm-hands-entry-lite-sg20hwxb.js";import{Ab as S5,Bb as w5,Ib as b5}from"./vm-hands-entry-lite-rrk5g62b.js";import{Nb as H5}from"./vm-hands-entry-lite-ya1a2eep.js";import{Ub as c5}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Ac as G4,Ec as r5,Hc as C7,Kc as p6,Lc as c6,mc as i1,nc as G1,oc as F1,pc as L$,qc as VJ,rc as xJ,sc as EJ,tc as D$,uc as SJ,vc as e3,wc as wJ,xc as Y4,yc as W1,zc as E8}from"./vm-hands-entry-lite-ncty87q3.js";import{Bd as X5,Hd as $$,Rd as F2,Vc as b2,Zc as _7,_c as F7}from"./vm-hands-entry-lite-8st97h7b.js";import{ae as G}from"./vm-hands-entry-lite-q6fshf3h.js";import{ie as IJ,je as o2,me as P7,pe as n$,re as rJ,se as tJ,xe as $6}from"./vm-hands-entry-lite-bsfm2m38.js";import{$e as h1,Be as k0,Ce as k$,Ee as x0,Fe as j4,He as e0,Ie as z0,Je as y9,Ke as OJ,Le as AJ,Me as E2,Ne as q2,Oe as f3,Pe as I8,Qe as x8,Re as Y$,Se as v$,Te as Y0,Ue as T2,Ve as k7,We as y7,Xe as e1,Ye as R4,_e as Q3,af as v0,bf as y$,cf as X3,ff as m1}from"./vm-hands-entry-lite-pf1ft65e.js";import{jf as I5}from"./vm-hands-entry-lite-q2pb31vh.js";import{ig as WJ,lg as n5,mg as h3,og as N5}from"./vm-hands-entry-lite-8gr872ee.js";import{Xg as Z2,Yg as p5}from"./vm-hands-entry-lite-7k65s010.js";import{_g as V0,ah as K7}from"./vm-hands-entry-lite-em388nee.js";import{yh as r}from"./vm-hands-entry-lite-pct56639.js";import{Fh as D7}from"./vm-hands-entry-lite-wgx7z7gt.js";import{Kh as g0}from"./vm-hands-entry-lite-xsq25kmd.js";import{spawn as bJ,spawnSync as eK}from"child_process";import{closeSync as kJ,mkdirSync as $V,openSync as yJ,readdirSync as JV,realpathSync as B1,rmSync as z$}from"fs";import{hostname as ZV}from"os";import{dirname as $9,join as F0,resolve as QV}from"path";var eJ=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function U9($){let J=typeof $==="string"?eJ.exec($):null;return J?{major:Number(J[1]),minor:Number(J[2])}:null}import{createHash as BZ,randomBytes as z9}from"crypto";import{createInterface as KZ}from"readline";import{randomBytes as $Z}from"crypto";import{chmodSync as M9,existsSync as T9,lstatSync as JZ,mkdirSync as ZZ,readFileSync as _9,renameSync as QZ,unlinkSync as F9,writeFileSync as W9}from"fs";import{homedir as XZ}from"os";import{dirname as YZ,join as q9}from"path";function $1($=process.env,J=XZ()){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 ZZ(YZ(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)GZ($,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 GZ($,J,Z){let Q=`${$}.${process.pid}.${$Z(6).toString("hex")}.tmp`;try{let X=JZ($);if(!X.isFile()||X.uid!==process.geteuid?.())return;let Y=JSON.parse(J);if(W9(Q,`${JSON.stringify({...Y,apiOrigin:Z},null,2)}
|
|
4
4
|
`,{mode:384,flag:"wx"}),M9(Q,384),_9($,"utf8")!==J)throw Error("credentials_changed");QZ(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 gV=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=BZ("sha256").update($).digest("base64url");return{verifier:$,challenge:J,state:z9(32).toString("base64url")}}function VZ($,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 HZ($,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 VZ(Y,`OAuth token request failed (${X.status})`);return Y}var NZ=1e4;async function UZ($,J={}){let Z=J.fetchImpl??fetch,Q=await HZ($.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:$.clientId,refresh_token:$.refreshToken}),Z,AbortSignal.timeout(NZ)).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=UZ(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=KZ({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 qZ=G.object({label:G.string(),used_percent:G.number().min(0).max(100).nullable(),resets_at:G.string().nullable(),exhausted:G.boolean().nullable()}),MZ=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 TZ($){let J=MZ.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 G0 extends Error{status;code;suggestedModel;retryAfterMs;constructor($,J,Z,Q,X){super(Z);this.status=$;this.code=J;this.suggestedModel=Q;this.retryAfterMs=X;this.name="ApiError"}static rateLimitDelayMs($,J){if(!($ instanceof G0)||$.status!==429)return null;return Math.min(60000,Math.max(J,$.retryAfterMs??0))}}var _Z=["minimal","low","medium","high","xhigh","max"],FZ=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()}))}),WZ=G.object({devices:G.array(FZ),end_cursor:G.string().nullish(),has_next_page:G.boolean().optional()}),LZ=G.object({id:G.string().min(1),name:G.string()}),DZ=G.object({items:G.array(LZ)}),jZ=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)}),zZ=G.object({items:G.array(jZ)}),OZ=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)}),AZ=G.object({items:G.array(OZ).default([])}),RZ=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(RZ).default([])}),CZ=G.object({items:G.array(P9).default([]),end_cursor:G.string().nullish(),has_next_page:G.boolean().optional()}),PZ=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()}),IZ=G.object({items:G.array(PZ).default([])}),xZ=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([])}),EZ=G.enum(["linux","macos"]),I9=G.object({id:G.string().min(1),name:G.string().min(1),platform:EZ.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()})}),SZ=G.object({machines:G.array(I9)}),wZ=G.object({machine:I9}),bZ=G.object({deleted:G.literal(!0),revoked_workers:G.number().int(),revoked_tokens:G.number().int()}),kZ=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)}),yZ=x9.extend({organization_id:G.string().min(1)}),cV=G.object({id:G.string().min(1),name:G.string().min(1),state:G.enum(["waiting","placed"]),queue_position:G.number().int().nullable()});var sV=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 G0(502,Z,"Reason returned an unexpected response.");return Q.data}var fZ=G.object({error:G.object({type:G.string(),message:G.string()})});function E9($,J,Z){let Q=fZ.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 G0($,X,`${Y}${B}`,typeof J.suggested_model==="string"?J.suggested_model:void 0,Number.isFinite(V)&&V>=0?V*1000: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(yZ,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 G0&&(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(SZ,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(wZ,J,"invalid_machine").machine}async deleteMachine($){let J=await this.request(this.machinePath($),{method:"DELETE"});return P0(bZ,J,"invalid_machine_deletion")}async createMachineToken($){let J=await this.request(this.machinePath($,"/tokens"),{method:"POST",body:{}});return P0(kZ,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=DZ.safeParse($);if(!J.success)throw new G0(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(zZ,$,"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(AZ,$,"invalid_skill_list").items}catch($){if($ instanceof G0&&($.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=WZ.safeParse(Q);if(!X.success)throw new G0(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((Q)=>Q.hidden!==!0&&Q.available!==!1).map(({reasoning_efforts:Q,hidden:X,available:Y,...B})=>({...B,...Array.isArray(Q)?{reasoning_efforts:_Z.filter((V)=>Q.includes(V))}:{}})),Z=new Set(J.map((Q)=>Q.detail));return J.length>1&&Z.size===1?J.map(({detail:Q,...X})=>X):J}catch($){if($ instanceof G0&&($.status===403||$.status===404))return[];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 $=qZ.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!$.success)return null;let J;try{J=TZ(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...$.data,own_inference:J}}catch($){if($ instanceof G0&&($.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 G0)||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 G0&&(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(xZ,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(CZ,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(IZ,$,"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 hZ($){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:hZ(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 G0(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 mZ}from"crypto";import{unlinkSync as vZ}from"fs";import{platform as gZ}from"os";import{join as uZ}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=($)=>uZ($,"api-key.json");function O1($){let J=mZ("sha256").update(`reason-connect-api-key
|
|
5
5
|
${$}`).digest("hex");return new e1(T2(),gZ(),J)}function O4($,J,Z=O1($)){try{Z.deleteBinding(),Z.createBinding(new TextEncoder().encode(J)),c(f1($),{version:1,store:"keychain"});return}catch(Q){if(!(Q instanceof Y0))throw Q}c(f1($),{version:1,store:"file",api_key:J})}function p0($,J=O1($)){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 Y0))throw Q;throw Error("worker_api_key_unreadable")}}function k9($,J=O1($)){if(!u(f1($)))return;if(b9.parse(JSON.parse(s(f1($)))).store==="keychain")try{J.deleteBinding()}catch(Z){if(!(Z instanceof Y0))throw Z}vZ(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 G0&&(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 GQ,renameSync as BQ,rmSync as v1}from"fs";import{join as M0}from"path";import{createHash as dZ}from"crypto";import{realpathSync as lZ,statSync as pZ,unlinkSync as _2}from"fs";import{platform as cZ}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 sZ=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=sZ.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),nZ($);let Z=J??P4($),Q=new R4(g($));try{Z.deleteBinding(),Z.deleteKey(),Z.createFreshPublicKey()}catch(X){if(X instanceof Y0)return Q;throw X}return Q.deleteBinding(),Q.deleteKey(),Z}function P4($){return new e1(T2(),cZ(),aZ($))}function aZ($){let J=I4($);return dZ("sha256").update(`reason-worker
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ab as L9,Bb as n0,Ib as K0,wb as LQ,xb as Y8,yb as s9,zb as _0}from"./vm-hands-entry-lite-rrk5g62b.js";import{Qb as EQ,Rb as SQ,Sb as X4,Tb as J4,Ub as V8}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Zb as b0}from"./vm-hands-entry-lite-n07kxrd1.js";import{Bd as q0,Oc as t$,Rc as e$,ud as w9,vd as o0,wd as W8,xd as g0}from"./vm-hands-entry-lite-8st97h7b.js";import{ae as x}from"./vm-hands-entry-lite-q6fshf3h.js";import{Ke as mQ,Le as y8,Ze as fQ,df as i9,ef as f8}from"./vm-hands-entry-lite-pf1ft65e.js";import{Af as R8,Df as p9,Mf as I8,Nf as S0,Of as O0,Pf as u9,Wf as w8,Xf as XQ,Yf as i$,gf as jZ,jf as B9,sf as $Q,tf as QQ,vf as ZQ,xf as d9,yf as s$,zf as n$}from"./vm-hands-entry-lite-q2pb31vh.js";import{Yg as Q4}from"./vm-hands-entry-lite-7k65s010.js";import{$g as l9,_g as N8,ch as $4}from"./vm-hands-entry-lite-em388nee.js";import{dh as B8,eh as i0,fh as L8,gh as a0,hh as H9,ih as J8,jh as e8,kh as s0,lh as p0,mh as l$,xh as W$}from"./vm-hands-entry-lite-yp315y25.js";import{Ch as KZ}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ab as L9,Bb as n0,Ib as K0,wb as LQ,xb as Y8,yb as s9,zb as _0}from"./vm-hands-entry-lite-rrk5g62b.js";import{Qb as EQ,Rb as SQ,Sb as X4,Tb as J4,Ub as V8}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Zb as b0}from"./vm-hands-entry-lite-n07kxrd1.js";import{Bd as q0,Oc as t$,Rc as e$,ud as w9,vd as o0,wd as W8,xd as g0}from"./vm-hands-entry-lite-8st97h7b.js";import{ae as x}from"./vm-hands-entry-lite-q6fshf3h.js";import{Ke as mQ,Le as y8,Ze as fQ,df as i9,ef as f8}from"./vm-hands-entry-lite-pf1ft65e.js";import{Af as R8,Df as p9,Mf as I8,Nf as S0,Of as O0,Pf as u9,Wf as w8,Xf as XQ,Yf as i$,gf as jZ,jf as B9,sf as $Q,tf as QQ,vf as ZQ,xf as d9,yf as s$,zf as n$}from"./vm-hands-entry-lite-q2pb31vh.js";import{Yg as Q4}from"./vm-hands-entry-lite-7k65s010.js";import{$g as l9,_g as N8,ch as $4}from"./vm-hands-entry-lite-em388nee.js";import{dh as B8,eh as i0,fh as L8,gh as a0,hh as H9,ih as J8,jh as e8,kh as s0,lh as p0,mh as l$,xh as W$}from"./vm-hands-entry-lite-yp315y25.js";import{Ch as KZ}from"./vm-hands-entry-lite-erxpqz9e.js";import{Ih as Z4}from"./vm-hands-entry-lite-wgx7z7gt.js";import{Kh as q}from"./vm-hands-entry-lite-xsq25kmd.js";import{Lh as P1,Oh as YZ}from"./vm-hands-entry-lite-hf0mk7vd.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 C9($){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 q9($,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 q9(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 q9(Q.body,v.upload),{type:"request",id:Q.id,method:Q.method,path:C9(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 C4}from"http";import{pipeline as T4}from"stream";import{constants as A8,createBrotliCompress as O4,createGzip as D4}from"zlib";import{WebSocket as O9}from"ws";import{randomBytes as M4,timingSafeEqual as j4}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=M4(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");C9(j[2]);let O=!1,C=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$){C++;let g=Buffer.from(S[2].trim());O=g.length===Z.length&&j4(g,Buffer.from(Z))}else if(S[1].toLowerCase()!=="host")A.push(T)}if(!O||C!==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,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./vm-hands-entry-lite-11qqexwe.js";import"./vm-hands-entry-lite-8st97h7b.js";import"./vm-hands-entry-lite-q6fshf3h.js";import{Oh as A}from"./vm-hands-entry-lite-hf0mk7vd.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-11qqexwe.js";import"./vm-hands-entry-lite-8st97h7b.js";import"./vm-hands-entry-lite-q6fshf3h.js";import{Oh as A}from"./vm-hands-entry-lite-hf0mk7vd.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-q0z9bqyk.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-0h74s3jy.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-sg20hwxb.js";import"./vm-hands-entry-lite-rrk5g62b.js";import"./vm-hands-entry-lite-qvrnx0vk.js";import"./vm-hands-entry-lite-n07kxrd1.js";import"./vm-hands-entry-lite-8st97h7b.js";import"./vm-hands-entry-lite-q6fshf3h.js";import"./vm-hands-entry-lite-pf1ft65e.js";import"./vm-hands-entry-lite-q2pb31vh.js";import"./vm-hands-entry-lite-7k65s010.js";import"./vm-hands-entry-lite-em388nee.js";import"./vm-hands-entry-lite-yp315y25.js";import"./vm-hands-entry-lite-erxpqz9e.js";import"./vm-hands-entry-lite-wgx7z7gt.js";import"./vm-hands-entry-lite-xsq25kmd.js";import"./vm-hands-entry-lite-hf0mk7vd.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{Oh as E}from"./vm-hands-entry-lite-hf0mk7vd.js";async function Q(){let[{executeLocalOperation:G},{configureDesktopAccount:H},{configureWorkerSandbox:J}]=await Promise.all([import("./local-capabilities-
|
|
2
|
+
import{Oh as E}from"./vm-hands-entry-lite-hf0mk7vd.js";async function Q(){let[{executeLocalOperation:G},{configureDesktopAccount:H},{configureWorkerSandbox:J}]=await Promise.all([import("./local-capabilities-6rr3bahs.js"),import("./desktop-account-axaenf68.js"),import("./worker-sandbox-snmfpfax.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-11qqexwe.js";import{Wc as v}from"./vm-hands-entry-lite-8st97h7b.js";import"./vm-hands-entry-lite-q6fshf3h.js";import{Oh as F}from"./vm-hands-entry-lite-hf0mk7vd.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-axaenf68.js"),import("./worker-sandbox-snmfpfax.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-c4jz97dy.js"),import("./hands-worker-source-w477y8ad.js"),import("./network-contract-ggqak7gp.js"),import("./device-workspace-ecq3hfd6.js")]),{REASON_HANDS_PROTOCOL_VERSION:X}=await import("./reason-hands-protocol-as5477xr.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-axaenf68.js"),import("./worker-sandbox-snmfpfax.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-fwq7gd0d.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-6rr3bahs.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-fwq7gd0d.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-6rr3bahs.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};
|