@reason-machines/cli-linux-arm64-musl 0.2.356 → 0.2.357
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/{api-credentials-j2hvs3zw.js → api-credentials-emdf5nm5.js} +1 -1
- package/bin/vm-hands/{api-3wwh4c28.js → api-js29ghm5.js} +1 -1
- package/bin/vm-hands/ask-relay-3x4np5cy.js +8 -0
- package/bin/vm-hands/{connect-cli-9ejh8cwq.js → connect-cli-12z734eh.js} +1 -1
- package/bin/vm-hands/{local-automation-9140prjp.js → local-automation-rvwmkxjb.js} +1 -1
- package/bin/vm-hands/{local-capabilities-pkbbhe2r.js → local-capabilities-v0bd3pg1.js} +1 -1
- package/bin/vm-hands/{local-display-session-dq2zq4km.js → local-display-session-m55mqd0t.js} +1 -1
- package/bin/vm-hands/{permissions-pk6nqvvb.js → permissions-hvhfr5k0.js} +1 -1
- package/bin/vm-hands/{status-wag8c6d1.js → status-vfh269zs.js} +2 -2
- package/bin/vm-hands/{version-vybbppgb.js → version-07vvwhvf.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-7yt58nfv.js → vm-hands-entry-lite-2w440hvn.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-ta451p3v.js → vm-hands-entry-lite-953ekkrb.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-y7jx1x8p.js → vm-hands-entry-lite-95k4g3jj.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-x7j2br2s.js → vm-hands-entry-lite-d93n1cz7.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-w7gxe8ta.js → vm-hands-entry-lite-d9k3dzaq.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-ygpjdcdn.js → vm-hands-entry-lite-f6vhpgam.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-wd4mr754.js → vm-hands-entry-lite-njne26yc.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-v1tyvkvx.js → vm-hands-entry-lite-qk2t0xs7.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-c2tpjg7n.js → vm-hands-entry-lite-r5nskvf8.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-0amqkh5r.js → vm-hands-entry-lite-swz6ea7y.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-mhnm6t6b.js → vm-hands-entry-lite-t7wda1y5.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-trcg4jv7.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-4hr3rsjv.js → vm-hands-executor-4ee0fqc5.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-tmk5vdke.js → vm-hands-op-runner-s5nh8mpx.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-mh5apdv2.js → vm-hands-runtime-42azzb1d.js} +2 -2
- package/package.json +1 -1
- package/bin/vm-hands/ask-relay-4wjn3790.js +0 -8
- package/bin/vm-hands/vm-hands-entry-lite-fs3ahdgg.js +0 -3
package/bin/ara
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{v as a,w as b,x as c,y as d,z as e}from"./vm-hands-entry-lite-
|
|
2
|
+
import{v as a,w as b,x as c,y as d,z as e}from"./vm-hands-entry-lite-d9k3dzaq.js";import"./vm-hands-entry-lite-95k4g3jj.js";import"./vm-hands-entry-lite-trcg4jv7.js";import"./vm-hands-entry-lite-gcn3rmz6.js";import"./vm-hands-entry-lite-6qfax5p2.js";import"./vm-hands-entry-lite-5b29hq7h.js";import"./vm-hands-entry-lite-84d59wrf.js";import"./vm-hands-entry-lite-k17ntg9v.js";import"./vm-hands-entry-lite-nd1k2jz9.js";export{d as resolveApiCredentials,e as requireApiCredentials,b as explicitApiOrigin,c as environmentApiKey,a as apiOriginFromEnvironment};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{F as a,G as b,H as c,I as d,J as e,K as f}from"./vm-hands-entry-lite-
|
|
2
|
+
import{F as a,G as b,H as c,I as d,J as e,K as f}from"./vm-hands-entry-lite-95k4g3jj.js";import"./vm-hands-entry-lite-trcg4jv7.js";import"./vm-hands-entry-lite-6qfax5p2.js";import"./vm-hands-entry-lite-5b29hq7h.js";import"./vm-hands-entry-lite-84d59wrf.js";import"./vm-hands-entry-lite-k17ntg9v.js";import"./vm-hands-entry-lite-nd1k2jz9.js";export{d as sessionPlace,c as sessionMachine,e as createMachineEnrollmentTicketWithToken,f as ReasonApi,b as REASONING_EFFORTS,a as ApiError};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{L as _}from"./vm-hands-entry-lite-trcg4jv7.js";import{sf as c}from"./vm-hands-entry-lite-swz6ea7y.js";import"./vm-hands-entry-lite-2w440hvn.js";import"./vm-hands-entry-lite-k17ntg9v.js";import{wi as y}from"./vm-hands-entry-lite-nd1k2jz9.js";import{existsSync as Uz,mkdirSync as Cz,readFileSync as Mz,writeFileSync as Oz}from"fs";import{homedir as fz}from"os";import{dirname as w,join as Rz}from"path";import{spawnSync as W}from"child_process";import{createHash as m}from"crypto";import{chmodSync as a,existsSync as K,mkdirSync as S,mkdtempSync as i,readFileSync as t,renameSync as r,rmSync as s,statSync as n,writeFileSync as b}from"fs";import{connect as o}from"net";import{homedir as R}from"os";import{dirname as O,join as H}from"path";class V extends Error{}var D="reason-network",U="0.10.3",e={"aarch64-apple-darwin":"1e793a89ea8b53c603cddbc65ac08b0dd83f1dbfc30a1987858e2c52e2ed907c","x86_64-apple-darwin":"ef1f0f8d7d9e8a286de54eeb78f8ff8a53152c1a661c50b6182bfefa8eef8a02","aarch64-unknown-linux-musl":"75fdfd10314225ffb2875acc7ac73c66de23b5678b684d70b4678eb16ba35124","x86_64-unknown-linux-musl":"17111a623396eed0a2d98aa4d3bb03f00da37c25bdc39b6d0ba3ab202dfbe874"},zz="https://reasonmachines.com/cli/engine",G="REASON_AGENT_NETWORK_BIN";function Xz(){let z=process.arch==="arm64"?"aarch64":process.arch==="x64"?"x86_64":null,X=process.platform==="darwin"?"apple-darwin":process.platform==="linux"?"unknown-linux-musl":null;return z&&X?`${z}-${X}`:null}function Zz(z){let X=W(z,["--version"],{encoding:"utf8",timeout:5000}),[Z,$]=X.status===0?X.stdout.trim().split(/\s+/):[];return Z===D?$??null:null}function $z(z,X){let Z=z.split(".").map(Number),$=X.split(".").map(Number);for(let q=0;q<3;q+=1)if((Z[q]??0)!==($[q]??0))return(Z[q]??0)>($[q]??0);return!0}function E(){return H(R(),".reason","bin","reason-network")}async function qz(z=process.env){if(z[G])return z[G];let X=E(),Z=v();if(Z?.path===X&&T(X)===Z.fingerprint)return X;let $=K(X)?Zz(X):null;if(!$||!$z($,U))await Yz(X);let q=W(X,["setup",...Bz(z)?["--no-service"]:[]],{env:z,encoding:"utf8",timeout:60000});if(q.status!==0){let Q=P((q.stderr||q.stdout||"").trim().split(`
|
|
3
|
+
`).pop()??"");throw new V(`Couldn't connect this computer's agents to the network${Q?` (${Q})`:""}. Run reason network setup to try again.`)}return W(X,["stop"],{env:z,stdio:"ignore",timeout:15000}),Qz(X)}function Bz(z=process.env){return Boolean(z.REASON_NETWORK_NO_SERVICE||z.TINCAN_NO_SERVICE)}var f=()=>H(R(),".reason","ask-engine.json");function T(z){try{let X=n(z);return`${X.size}:${X.mtimeMs}:${X.ino}`}catch{return null}}function v(){try{let z=JSON.parse(t(f(),"utf8"));return typeof z.path==="string"&&typeof z.fingerprint==="string"&&z.version===U?{path:z.path,fingerprint:z.fingerprint}:null}catch{return null}}function Qz(z){let X=T(z);if(!X)return z;let Z=O(f());if(!K(Z))S(Z,{recursive:!0});return b(f(),JSON.stringify({path:z,fingerprint:X,version:U})),z}async function Yz(z){let X=Xz(),Z=X?e[X]:void 0;if(!X||!Z)throw new V(`Reason Network runs on macOS and Linux (arm64 or x64); this is ${process.platform} ${process.arch}.`);let $=`${zz}/${U}/${D}-${X}.tar.gz`,q;try{let Y=await fetch($,{signal:AbortSignal.timeout(120000)});if(!Y.ok)throw Error(`HTTP ${Y.status}`);q=Buffer.from(await Y.arrayBuffer())}catch(Y){let F=Y instanceof Error&&Y.name==="TimeoutError"?"no download within 2 minutes":Y instanceof Error?Y.message.replace(/\.$/,""):String(Y);throw new V(`Couldn't download the network engine from ${new URL($).host} (${F}). Check the connection and run reason network again.`)}if(m("sha256").update(q).digest("hex")!==Z)throw new V("The downloaded network engine didn't match its checksum, so it wasn't installed.");S(O(z),{recursive:!0});let B=i(H(O(z),".reason-engine-"));try{if(b(H(B,"engine.tar.gz"),q),W("tar",["-xzf",H(B,"engine.tar.gz"),"-C",B]).status!==0||!K(H(B,D)))throw new V("Couldn't unpack the network engine.");a(H(B,D),493),r(H(B,D),z)}finally{s(B,{recursive:!0,force:!0})}}function Hz(z=process.env,X=R()){let Z=z.REASON_NETWORK_HOME?.trim()||z.TINCAN_HOME?.trim();if(Z)return Z;let $=H(X,".reason","network"),q=H(X,".tincan");return!A($)&&A(q)?q:$}var A=(z)=>K(H(z,"network.db"))||K(H(z,"tincan.db"));function Jz(z){let X=K(H(z,"network.db"))||!K(H(z,"tincan.db")),Z=H(z,X?"network.sock":"tincan.sock");if(Buffer.byteLength(Z)<100)return Z;let $=0xcbf29ce484222325n;for(let q of Buffer.from(Z))$=BigInt.asUintN(64,($^BigInt(q))*0x100000001b3n);return H("/tmp",`${X?"reason-network":"tincan"}-${process.getuid?.()??0}`,`${$.toString(16).padStart(16,"0")}.sock`)}var u=15000,Kz=new Set(["who","team","inbox","unread","held"]),Vz=90000;class x{socket;nextId=1;buffer="";pending=new Map;closed=null;constructor(z){this.socket=z;z.setEncoding("utf8"),z.on("data",(Z)=>this.read(Z));let X=(Z)=>{this.closed=Z;for(let $ of this.pending.values())$.reject(Z);this.pending.clear()};z.on("error",(Z)=>X(Z)),z.on("close",()=>X(Error("the network daemon closed the connection")))}static open(z){return new Promise((X,Z)=>{let $=o(z);$.once("connect",()=>X(new x($))),$.once("error",Z)})}read(z){this.buffer+=z;let X=this.buffer.indexOf(`
|
|
4
|
+
`);while(X>=0){let Z=this.buffer.slice(0,X);if(this.buffer=this.buffer.slice(X+1),X=this.buffer.indexOf(`
|
|
5
|
+
`),!Z.trim())continue;let $;try{$=JSON.parse(Z)}catch{continue}if(typeof $.id!=="number")continue;let q=this.pending.get($.id);if(!q)continue;if(this.pending.delete($.id),$.ok)q.resolve($.result);else q.reject(Error(P($.error??"the network daemon refused the request")))}}call(z,X={},Z=u){if(this.closed)return Promise.reject(this.closed);let $=this.nextId++;return this.socket.write(`${JSON.stringify({id:$,op:z,...X})}
|
|
6
|
+
`),new Promise((q,Q)=>{let B=setTimeout(()=>{this.pending.delete($),Q(Error(`the network daemon didn't answer ${z} within ${Math.round(Z/1000)}s`))},Z);this.pending.set($,{resolve:(Y)=>{clearTimeout(B),q(Y)},reject:(Y)=>{clearTimeout(B),Q(Y)}})})}get isClosed(){return this.closed!==null}close(){this.socket.end()}}var M=/^(Claude Code|Grok|Codex) \u00B7 (.*)$/,Lz={"Claude Code":"claude-code",Grok:"grok",Codex:"codex"},Wz=/^ask-[0-9a-f]{6}$/;function j(z){return{id:z.id,from:z.from,fromAgent:z.from_agent,to:z.to,replyTo:z.reply_to,body:z.body,sentAt:z.sent_at}}function N(z){return{person:z.person,machine:z.machine,isMe:z.is_me,online:z.online,link:z.link,rttMs:z.rtt_ms}}class L{engine;env;connection=null;waits=new Set;constructor(z,X){this.engine=z;this.env=X}static async open(z=process.env){return new L(await qz(z),z)}static openInstalled(z=process.env){if(z[G])return new L(z[G],z);let X=E(),Z=v();return Z?.path===X&&T(X)===Z.fingerprint?new L(X,z):null}socketPath(){return Jz(Hz(this.env))}async open(){try{return await x.open(this.socketPath())}catch{return W(this.engine,["who","--json"],{env:this.env,stdio:"ignore",timeout:15000}),await x.open(this.socketPath())}}async call(z,X={},Z){if(!this.connection||this.connection.isClosed)this.connection=await this.open();try{return await this.connection.call(z,X,Z)}catch($){if(!/closed|ECONNRESET|EPIPE/.test(String($)))throw $;if(this.connection=await this.open(),!Kz.has(z))throw $;return await this.connection.call(z,X)}}async waitOn(z,X){let Z=await this.open();this.waits.add(Z);try{return await Z.call(z,X,X.wait_secs*1000+u)}finally{this.waits.delete(Z),Z.close()}}close(){this.connection?.close(),this.connection=null;for(let z of this.waits)z.close();this.waits.clear()}async team(){try{let z=await this.call("team");return{...z,machines:z.machines.map(N)}}catch(z){if(/team/i.test(String(z)))return null;throw z}}async snapshot(z={}){let X=await this.call("who",{all:Boolean(z.all),...z.filter?{filter:z.filter}:{}}),Z=new Set(X.sessions.filter((q)=>M.test(q.doing??"")).map((q)=>`${q.person}/${q.machine}:${q.cwd}`)),$=X.sessions.filter((q)=>z.all||!Wz.test(q.name)).filter((q)=>M.test(q.doing??"")||!Z.has(`${q.person}/${q.machine}:${q.cwd}`)).map((q)=>{let Q=M.exec(q.doing??"");return{address:q.address,name:q.name,person:q.person,machine:q.machine,agent:Q?Lz[Q[1]]:q.agent,cwd:q.cwd,repo:q.repo,branch:q.branch,status:Q?Q[2]==="ready for work"?"idle":Q[2]==="stopped"?"offline":"busy":q.status,since:q.since,doing:Q?Q[2]:q.doing,isMe:q.is_me,worker:Boolean(Q),tier:q.tier??null}});return{team:X.team,person:X.person,machine:X.machine,machines:X.machines.map(N),sessions:$}}async send(z,X,Z={}){if(!Z.from)await this.call("hook",{agent:"cli",event:"stop",session_id:"terminal",name:"terminal",cwd:process.cwd(),mail:!1});let $=await this.call("send",{from:Z.from??"terminal",to:z,body:X,...Z.replyTo?{reply_to:Z.replyTo}:{},wake:Z.wake??!0,...Z.notify?{notify:!0}:{}});return{ids:$.ids,recipients:$.recipients.map((q)=>q.address),deliveries:$.recipients.map((q)=>({address:q.address,state:q.state,note:q.note??""}))}}async session(z,X={}){let Z=X.agent??"cli",$=(B,Y={})=>this.call("hook",{agent:Z,event:B,session_id:z,name:z,cwd:process.cwd(),mail:!1,...Y}),q=await $("stop"),Q=`${Z}:${z}`;return{name:z,address:q.address??z,next:async(B)=>{return(await this.waitOn("inbox",{key:Q,wait_secs:B,peek:!0})).messages.map(j)},ack:async(B)=>{if(B.length)await this.call("delivered",{key:Q,ids:B})},busy:async(B)=>{if(await $("prompt"),B)await $("doing",{doing:B})},idle:async(B)=>{if(await $("stop"),B)await $("doing",{doing:B})},doing:async(B)=>{await $("doing",{doing:B})},send:(B,Y,F,p)=>this.send(B,Y,{from:Q,...F?{replyTo:F}:{},...p?.notify?{notify:!0}:{}})}}async inbox(z={}){let Z=(await this.waitOn("inbox",{key:"cli:terminal",wait_secs:z.waitSeconds??0,peek:!0}).catch(($)=>{if(/isn't registered/.test(String($)))return{messages:[]};throw $})).messages.map(j);if(Z.length&&!z.peek)await this.call("delivered",{key:"cli:terminal",ids:Z.map(($)=>$.id)});return Z}async link(z={}){return await this.call("link",{new:Boolean(z.new)})}async changeTeam(z,X){try{return await this.call(z,X,Vz)}finally{this.close()}}async changeOntoTeam(z,X){try{await this.changeTeam(z,X)}catch(Z){if(!/closed|ECONNRESET|EPIPE/.test(String(Z)))throw Z;if(await this.team())return;await this.changeTeam(z,X)}}async createTeam(z,X){await this.changeOntoTeam("create_team",{name:z,person:X})}async join(z,X){await this.changeOntoTeam("join",{ticket:z,person:X})}async leave(){return await this.changeTeam("leave",{force:!0})}async remove(z){return await this.call("remove",{who:z})}passthrough(z,X={}){this.close();let Z=W(this.engine,z,{stdio:["inherit","pipe","pipe"],encoding:"utf8",env:this.env});if(!X.quiet||Z.status!==0)process.stdout.write(P(Z.stdout??"")),process.stderr.write(P(Z.stderr??""));return Z.status??1}}function P(z){return z.replace(/not in a team yet:[^\n]*/g,"this computer isn't on a team yet: run `reason network setup`").replace(/`tincan (\w+)/g,"`reason network $1").replace(/\btincan (who|send|inbox|invite|join|team|link|setup|doctor|remove|leave|listen)\b/g,"reason network $1").replace(/(?<![\w./-])tincan(?![\w./-])/gi,"Reason Network")}import{existsSync as lz,mkdirSync as pz,readFileSync as Dz,writeFileSync as mz}from"fs";import{homedir as Fz,hostname as iz}from"os";import{dirname as rz,join as Gz}from"path";var xz=(z)=>Gz(z,".reason","ask.json");function Pz(z){try{let X=JSON.parse(Dz(xz(z),"utf8"));if(typeof X.orgId!=="string"||typeof X.team!=="string")return null;let Z=X.pendingRotation;return{orgId:X.orgId,team:X.team,...typeof X.checkedAt==="number"?{checkedAt:X.checkedAt}:{},...Z&&typeof Z.link==="string"&&typeof Z.team==="string"&&typeof Z.replaces==="string"?{pendingRotation:Z}:{}}}catch{return null}}function g(z=Fz()){let X=Pz(z);return X?{orgId:X.orgId,team:X.team}:null}var d=86400000,Tz=300,C=(z)=>Rz(z,".reason","ask-relay.json");function I(z){try{let X=JSON.parse(Mz(C(z),"utf8"));return{sessions:Array.isArray(X.sessions)?X.sessions.filter((Z)=>typeof Z?.name==="string"&&typeof Z.agent==="string"&&typeof Z.usedAt==="number"):[]}}catch{return{sessions:[]}}}function Iz(z,X){try{if(!Uz(w(C(z))))Cz(w(C(z)),{recursive:!0});Oz(C(z),`${JSON.stringify(X)}
|
|
7
|
+
`,{mode:384})}catch{}}var J=(z,X)=>new Promise((Z)=>{if(X.aborted)return Z();let $=setTimeout(q,z);$.unref?.();function q(){clearTimeout($),X.removeEventListener("abort",q),Z()}X.addEventListener("abort",q,{once:!0})});function h(z){let X=z?.status;return typeof X==="number"?X:null}var k=60000;function _z(z){return{address:z.address.slice(0,300),state:z.state.slice(0,40),note:z.note.slice(0,500)}}function Az(z){let X=Number.isFinite(z.sentAt)&&Math.abs(z.sentAt)<8640000000000000?z.sentAt:Date.now();return{id:z.id.slice(0,100),from:z.from.slice(0,300),from_agent:z.fromAgent?.slice(0,100)??null,to:z.to.slice(0,300),reply_to:z.replyTo?.slice(0,100)??null,sent_at:X,body:z.body.length>k?`${z.body.slice(0,k)}
|
|
8
|
+
[cut: the answer was ${z.body.length} characters]`:z.body}}class l{network;api;home;signal;log;team;sessions=new Map;readers=new Set;constructor(z,X,Z,$,q,Q){this.network=z;this.api=X;this.home=Z;this.signal=$;this.log=q;this.team=Q}async run(){let z=Date.now()-d;for(let Z of I(this.home).sessions)if(Z.usedAt>z)this.read(Z);let X=0;while(!this.signal.aborted){let Z=await this.network.team().catch(()=>null);if(!Z){await J(60000,this.signal);continue}if(Z.name!==this.team)return;let $;try{let q=await this.api.claimAgentNetworkRelayJob({machine:Z.machine,person:Z.person,team:Z.name,version:c,wait_seconds:_},AbortSignal.any([this.signal,AbortSignal.timeout((_+20)*1000)]));if(X=0,q.retry_after_seconds)await J(q.retry_after_seconds*1000,this.signal);$=q.job}catch(q){if(this.signal.aborted)return;let Q=h(q);if(Q===403||Q===401){await J(900000,this.signal);continue}if(Q===404||Q===405){await J(120000,this.signal);continue}X+=1,await J(Math.min(60000,1000*2**Math.min(X,6)),this.signal);continue}if($)this.carry($)}}async carry(z){let X;try{X=z.kind==="who"?{who:await this.who(z)}:{sent:await this.send(z)}}catch(Z){X={error:Z instanceof Error?Z.message:String(Z)}}for(let Z=1;;Z+=1)try{if(await this.api.completeAgentNetworkRelayJob(z.id,X),z.kind==="send")this.log(`relayed a message to ${z.to} from ${"sent"in X?X.sent.from:z.from_name}`);return}catch($){if(Z>=4||this.signal.aborted){this.log(`couldn't report a relayed call: ${$ instanceof Error?$.message:String($)}`);return}await J(Z*1000,this.signal)}}async who(z){let X=z.all===!0,Z=await this.network.snapshot({all:X});return{all:X,team:Z.team,sessions:Z.sessions.map(($)=>({address:$.address,person:$.person,machine:$.machine,agent:$.agent,repo:$.repo,branch:$.branch,status:$.status,since:$.since,doing:$.doing,worker:$.worker,...$.tier?{tier:$.tier.slice(0,10)}:{}})),machines:Z.machines.map(($)=>({person:$.person,machine:$.machine,online:$.online}))}}async send(z){let X={name:z.from_name,agent:z.from_agent},Z=await this.session(X),$=await Z.send(z.to,z.body,z.reply_to,{notify:z.notify===!0});return this.remember(X),this.read(X),{ids:$.ids,recipients:$.recipients,from:Z.address,deliveries:$.deliveries.slice(0,500).map(_z)}}session(z){let X=`${z.agent}:${z.name}`,Z=this.sessions.get(X);if(!Z)Z=this.network.session(z.name,{agent:z.agent}).then(async($)=>{return await $.idle(`personal agent (${z.agent}), through Reason`).catch(()=>{}),$}),Z.catch(()=>this.sessions.delete(X)),this.sessions.set(X,Z);return Z}remember(z){let Z=I(this.home).sessions.filter(($)=>$.name!==z.name||$.agent!==z.agent);Iz(this.home,{sessions:[...Z,{...z,usedAt:Date.now()}].slice(-50)})}read(z){let X=`${z.agent}:${z.name}`;if(this.readers.has(X))return;this.readers.add(X),(async()=>{let Z=0;try{while(!this.signal.aborted){let $=I(this.home).sessions.find((q)=>q.name===z.name&&q.agent===z.agent)?.usedAt??0;if(Date.now()-$>d)return;try{let q=await this.session(z),Q=await q.next(Tz);if(Q.length===0)continue;await this.api.recordAgentNetworkRelayReplies(Q.map(Az)).catch((B)=>{let Y=h(B);if(Y===null||Y>=500||Y===429||Y===401)throw B;this.log(`dropped ${Q.length} answer(s) the server refused (HTTP ${Y})`)}),await q.ack(Q.map((B)=>B.id)),Z=0}catch{if(this.signal.aborted)return;this.sessions.delete(X),Z+=1,await J(Math.min(60000,1000*2**Math.min(Z,6)),this.signal)}}}finally{this.readers.delete(X)}})()}}async function jz(z){await new l(z.network,z.api,z.home??fz(),z.signal,z.log??(()=>{}),z.team).run()}async function BX(z,X=()=>{}){while(!z.aborted){try{let Z=g(),$=Z?L.openInstalled():null;if(Z&&$){let[{requireApiCredentials:q},{ReasonApi:Q}]=await Promise.all([import("./api-credentials-emdf5nm5.js"),import("./api-js29ghm5.js")]),B=await q({});if(B.credentialKind!=="api_key"&&B.orgId.toLowerCase()===Z.orgId.toLowerCase())try{await jz({network:$,api:new Q(B),team:Z.team,signal:z,log:X})}finally{$.close()}}}catch(Z){X(`agent network relay: ${Z instanceof Error?Z.message:String(Z)}`)}await J(300000,z)}}export{BX as runBackgroundAskRelay,jz as runAskRelay};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{h as a,i as b,j as c,k as d,l as e,m as f,n as g,o as h,p as i,q as j,r as k,s as l,t as m}from"./vm-hands-entry-lite-
|
|
2
|
+
import{h as a,i as b,j as c,k as d,l as e,m as f,n as g,o as h,p as i,q as j,r as k,s as l,t as m}from"./vm-hands-entry-lite-f6vhpgam.js";import"./vm-hands-entry-lite-tdgbgcer.js";import"./vm-hands-entry-lite-d9k3dzaq.js";import"./vm-hands-entry-lite-95k4g3jj.js";import"./vm-hands-entry-lite-trcg4jv7.js";import"./vm-hands-entry-lite-t7wda1y5.js";import"./vm-hands-entry-lite-953ekkrb.js";import"./vm-hands-entry-lite-dyy62gt3.js";import"./vm-hands-entry-lite-wpx6sg6d.js";import"./vm-hands-entry-lite-nbtpm59m.js";import"./vm-hands-entry-lite-nvhzj5b0.js";import"./vm-hands-entry-lite-gcn3rmz6.js";import"./vm-hands-entry-lite-beannz0s.js";import"./vm-hands-entry-lite-r5nskvf8.js";import"./vm-hands-entry-lite-qf01e5f1.js";import"./vm-hands-entry-lite-qk2t0xs7.js";import"./vm-hands-entry-lite-xhjbc3e4.js";import"./vm-hands-entry-lite-njne26yc.js";import"./vm-hands-entry-lite-swz6ea7y.js";import"./vm-hands-entry-lite-2w440hvn.js";import"./vm-hands-entry-lite-c9wp99nr.js";import"./vm-hands-entry-lite-jfwz0br7.js";import"./vm-hands-entry-lite-33ttamma.js";import"./vm-hands-entry-lite-mybm2kyz.js";import"./vm-hands-entry-lite-6qfax5p2.js";import"./vm-hands-entry-lite-5b29hq7h.js";import"./vm-hands-entry-lite-84d59wrf.js";import"./vm-hands-entry-lite-k17ntg9v.js";import"./vm-hands-entry-lite-6f5eypjm.js";import"./vm-hands-entry-lite-tj1y61bg.js";import"./vm-hands-entry-lite-nd1k2jz9.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{$c as e,Xc as a,Yc as b,Zc as c,_c as d,ad as f,bd as g,cd as h,dd as i,ed as j,fd as k,gd as l}from"./vm-hands-entry-lite-
|
|
2
|
+
import{$c as e,Xc as a,Yc as b,Zc as c,_c as d,ad as f,bd as g,cd as h,dd as i,ed as j,fd as k,gd as l}from"./vm-hands-entry-lite-r5nskvf8.js";import"./vm-hands-entry-lite-qf01e5f1.js";import"./vm-hands-entry-lite-qk2t0xs7.js";import"./vm-hands-entry-lite-xhjbc3e4.js";import"./vm-hands-entry-lite-njne26yc.js";import"./vm-hands-entry-lite-swz6ea7y.js";import"./vm-hands-entry-lite-2w440hvn.js";import"./vm-hands-entry-lite-c9wp99nr.js";import"./vm-hands-entry-lite-jfwz0br7.js";import"./vm-hands-entry-lite-33ttamma.js";import"./vm-hands-entry-lite-mybm2kyz.js";import"./vm-hands-entry-lite-6qfax5p2.js";import"./vm-hands-entry-lite-5b29hq7h.js";import"./vm-hands-entry-lite-84d59wrf.js";import"./vm-hands-entry-lite-k17ntg9v.js";import"./vm-hands-entry-lite-6f5eypjm.js";import"./vm-hands-entry-lite-tj1y61bg.js";import"./vm-hands-entry-lite-nd1k2jz9.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{fa as c,ga as d,ha as e,ia as f,ja as g,ka as h,la as i,ma as j,na as k,oa as l,pa as m,qa as n,ra as o,sa as p,ta as q,ua as r,va as s,wa as t}from"./vm-hands-entry-lite-
|
|
2
|
+
import{fa as c,ga as d,ha as e,ia as f,ja as g,ka as h,la as i,ma as j,na as k,oa as l,pa as m,qa as n,ra as o,sa as p,ta as q,ua as r,va as s,wa as t}from"./vm-hands-entry-lite-t7wda1y5.js";import"./vm-hands-entry-lite-953ekkrb.js";import"./vm-hands-entry-lite-dyy62gt3.js";import"./vm-hands-entry-lite-wpx6sg6d.js";import"./vm-hands-entry-lite-nbtpm59m.js";import{lc as b}from"./vm-hands-entry-lite-nvhzj5b0.js";import"./vm-hands-entry-lite-gcn3rmz6.js";import"./vm-hands-entry-lite-beannz0s.js";import"./vm-hands-entry-lite-r5nskvf8.js";import"./vm-hands-entry-lite-qf01e5f1.js";import"./vm-hands-entry-lite-qk2t0xs7.js";import"./vm-hands-entry-lite-xhjbc3e4.js";import"./vm-hands-entry-lite-njne26yc.js";import"./vm-hands-entry-lite-swz6ea7y.js";import"./vm-hands-entry-lite-2w440hvn.js";import"./vm-hands-entry-lite-c9wp99nr.js";import"./vm-hands-entry-lite-jfwz0br7.js";import"./vm-hands-entry-lite-33ttamma.js";import"./vm-hands-entry-lite-mybm2kyz.js";import"./vm-hands-entry-lite-6qfax5p2.js";import"./vm-hands-entry-lite-5b29hq7h.js";import"./vm-hands-entry-lite-84d59wrf.js";import"./vm-hands-entry-lite-k17ntg9v.js";import"./vm-hands-entry-lite-6f5eypjm.js";import{qi as a}from"./vm-hands-entry-lite-tj1y61bg.js";import"./vm-hands-entry-lite-nd1k2jz9.js";export{g as spawnCaptured,f as sandboxProfile,e as safeEnvironment,j as runTransferCapability,i as runFileCapability,s as rebindLocalHandsControl,b as isProtectedLocalPath,t as executeLocalOperation,l as enrolledWorkspaceRootFingerprint,p as enrolledRootPaths,o as enrolledHomeContainedRootFingerprints,m as enrolledAccountRootPath,n as enrolledAccountRootFingerprint,r as deliverLocalHandsEnvironment,h as defaultLocalCommandRunner,d as confinedExecutionShell,q as capabilityInventoryForRoots,c as SHORT_REQUEST_CAPABILITIES,a as LocalCapabilityError,k as LOCAL_CAPABILITY_REGISTRY};
|
package/bin/vm-hands/{local-display-session-dq2zq4km.js → local-display-session-m55mqd0t.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ne as a,Oe as b,Pe as c,Qe as d,Re as e,Se as f,Te as g,Ue as h}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ne as a,Oe as b,Pe as c,Qe as d,Re as e,Se as f,Te as g,Ue as h}from"./vm-hands-entry-lite-qk2t0xs7.js";import"./vm-hands-entry-lite-xhjbc3e4.js";import"./vm-hands-entry-lite-njne26yc.js";import"./vm-hands-entry-lite-swz6ea7y.js";import"./vm-hands-entry-lite-2w440hvn.js";import"./vm-hands-entry-lite-c9wp99nr.js";import"./vm-hands-entry-lite-jfwz0br7.js";import"./vm-hands-entry-lite-33ttamma.js";import"./vm-hands-entry-lite-mybm2kyz.js";import"./vm-hands-entry-lite-6qfax5p2.js";import"./vm-hands-entry-lite-5b29hq7h.js";import"./vm-hands-entry-lite-84d59wrf.js";import"./vm-hands-entry-lite-k17ntg9v.js";import"./vm-hands-entry-lite-6f5eypjm.js";import"./vm-hands-entry-lite-tj1y61bg.js";import"./vm-hands-entry-lite-nd1k2jz9.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{if as a,jf as b,kf as c,lf as d,mf as e,nf as f,of as g,pf as h,qf as i,rf as j}from"./vm-hands-entry-lite-
|
|
2
|
+
import{if as a,jf as b,kf as c,lf as d,mf as e,nf as f,of as g,pf as h,qf as i,rf as j}from"./vm-hands-entry-lite-njne26yc.js";import"./vm-hands-entry-lite-swz6ea7y.js";import"./vm-hands-entry-lite-2w440hvn.js";import"./vm-hands-entry-lite-c9wp99nr.js";import"./vm-hands-entry-lite-5b29hq7h.js";import"./vm-hands-entry-lite-84d59wrf.js";import"./vm-hands-entry-lite-tj1y61bg.js";import"./vm-hands-entry-lite-nd1k2jz9.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{d as jq,e as Dq,f as Vq,g as kq,j as Hq,k as zq,p as Aq}from"./vm-hands-entry-lite-
|
|
2
|
+
import{d as jq,e as Dq,f as Vq,g as kq,j as Hq,k as zq,p as Aq}from"./vm-hands-entry-lite-f6vhpgam.js";import"./vm-hands-entry-lite-tdgbgcer.js";import{y as Fq}from"./vm-hands-entry-lite-d9k3dzaq.js";import{A as Wq,K as bq}from"./vm-hands-entry-lite-95k4g3jj.js";import"./vm-hands-entry-lite-trcg4jv7.js";import"./vm-hands-entry-lite-t7wda1y5.js";import"./vm-hands-entry-lite-953ekkrb.js";import"./vm-hands-entry-lite-dyy62gt3.js";import"./vm-hands-entry-lite-wpx6sg6d.js";import"./vm-hands-entry-lite-nbtpm59m.js";import"./vm-hands-entry-lite-nvhzj5b0.js";import"./vm-hands-entry-lite-gcn3rmz6.js";import"./vm-hands-entry-lite-beannz0s.js";import{Gc as Kq}from"./vm-hands-entry-lite-r5nskvf8.js";import"./vm-hands-entry-lite-qf01e5f1.js";import"./vm-hands-entry-lite-qk2t0xs7.js";import"./vm-hands-entry-lite-xhjbc3e4.js";import"./vm-hands-entry-lite-njne26yc.js";import{sf as N}from"./vm-hands-entry-lite-swz6ea7y.js";import"./vm-hands-entry-lite-2w440hvn.js";import"./vm-hands-entry-lite-c9wp99nr.js";import"./vm-hands-entry-lite-jfwz0br7.js";import{hg as Qq,mg as Bq}from"./vm-hands-entry-lite-33ttamma.js";import"./vm-hands-entry-lite-mybm2kyz.js";import{vh as z,wh as u,xh as s}from"./vm-hands-entry-lite-6qfax5p2.js";import{Kh as l}from"./vm-hands-entry-lite-5b29hq7h.js";import"./vm-hands-entry-lite-84d59wrf.js";import{ii as G}from"./vm-hands-entry-lite-k17ntg9v.js";import"./vm-hands-entry-lite-6f5eypjm.js";import"./vm-hands-entry-lite-tj1y61bg.js";import{wi as $q}from"./vm-hands-entry-lite-nd1k2jz9.js";import{createHash as aq,randomBytes as nq}from"crypto";import{readFileSync as eq,realpathSync as Pq,renameSync as q3,unlinkSync as x3,writeFileSync as J3}from"fs";import{dirname as X3,join as yq}from"path";import{spawnSync as wq}from"child_process";import{accessSync as Lq,constants as fq,existsSync as L,mkdirSync as Sq,readFileSync as hq,renameSync as Cq,writeFileSync as gq}from"fs";import{homedir as mq}from"os";import{delimiter as pq,dirname as dq,join as T}from"path";import{existsSync as vq,readFileSync as Eq}from"fs";import{join as Mq}from"path";var _q=`---
|
|
3
3
|
name: reason
|
|
4
4
|
description: Integrate software with Reason's public REST API using a scoped API key. Use for API clients, CI, service integrations, or cloud coding-session automation.
|
|
5
5
|
---
|
|
@@ -79,7 +79,7 @@ This computer
|
|
|
79
79
|
`),W.version)x.stdout.write(`Version: ${W.version}${W.version===N?"":` (${N} is installed; \`reason connect\` restarts it on that)`}
|
|
80
80
|
`);if(x.stdout.write(`Folder: ${W.folder}
|
|
81
81
|
`),x.stdout.write(`Sessions: ${W.sessions_running===null?"":`${W.sessions_running} running, `}${W.sessions_max===null?"every Session you start":W.sessions_max===1?"one at a time":`up to ${W.sessions_max} at once`}
|
|
82
|
-
`),A){let Z=A,H=await(J.readPermissionsSummary??(async()=>{let{permissionsSummary:Rq,readMacPermissions:Oq,reasonIdentity:Tq}=await import("./permissions-
|
|
82
|
+
`),A){let Z=A,H=await(J.readPermissionsSummary??(async()=>{let{permissionsSummary:Rq,readMacPermissions:Oq,reasonIdentity:Tq}=await import("./permissions-hvhfr5k0.js"),{macScreenStatus:Uq}=await import("./local-display-mac-gj72gkfb.js");return Rq(await Oq({identity:()=>Tq(),grants:Uq,worker:async()=>Z}))}))().catch(()=>null);if(H)x.stdout.write(`${H}
|
|
83
83
|
`);x.stdout.write(`Keep awake: ${A.keep_awake.enabled?"on":"off"}${A.keep_awake.holding?" (holding)":""}
|
|
84
84
|
`)}if(W.service)x.stdout.write(`Logs: ${W.service.logs}
|
|
85
85
|
`);for(let Z of W.workspaces??[]){let H=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)":""}: ${H}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{sf as a,tf as b,uf as c,vf as d}from"./vm-hands-entry-lite-
|
|
2
|
+
import{sf as a,tf as b,uf as c,vf as d}from"./vm-hands-entry-lite-swz6ea7y.js";import"./vm-hands-entry-lite-2w440hvn.js";import"./vm-hands-entry-lite-nd1k2jz9.js";export{c as compareCliVersions,d as cliAndAgentVersion,b as CLI_VERSION_PATTERN,a as CLI_VERSION};
|
|
@@ -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.357",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 wf};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Rb as kQ,Sb as fQ,Tb as z4,Ub as K4,Vb as F8}from"./vm-hands-entry-lite-wpx6sg6d.js";import{$b as n0,Wb as MQ,Xb as G8,Yb as n9,Zb as _0,_b as L9,gc as K0}from"./vm-hands-entry-lite-nbtpm59m.js";import{lc as b0}from"./vm-hands-entry-lite-nvhzj5b0.js";import{Rd as w9,Sd as o0,Td as B8,Ud as m0,Yd as q0,hd as $Q,md as QQ}from"./vm-hands-entry-lite-qf01e5f1.js";import{Ye as Y4}from"./vm-hands-entry-lite-xhjbc3e4.js";import{wf as UZ}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Rb as kQ,Sb as fQ,Tb as z4,Ub as K4,Vb as F8}from"./vm-hands-entry-lite-wpx6sg6d.js";import{$b as n0,Wb as MQ,Xb as G8,Yb as n9,Zb as _0,_b as L9,gc as K0}from"./vm-hands-entry-lite-nbtpm59m.js";import{lc as b0}from"./vm-hands-entry-lite-nvhzj5b0.js";import{Rd as w9,Sd as o0,Td as B8,Ud as m0,Yd as q0,hd as $Q,md as QQ}from"./vm-hands-entry-lite-qf01e5f1.js";import{Ye as Y4}from"./vm-hands-entry-lite-xhjbc3e4.js";import{wf as UZ}from"./vm-hands-entry-lite-2w440hvn.js";import{ig as hQ,og as a9,pg as m8}from"./vm-hands-entry-lite-33ttamma.js";import{Dg as ZQ,Eg as XQ,Gg as JQ,Ig as p9,Jg as n$,Kg as i$,Lg as E8,Og as u9,Xg as R8,Yg as S0,Zg as O0,_g as l9,fh as b8,gh as YQ,hh as a$,rg as OZ,ug as B9}from"./vm-hands-entry-lite-mybm2kyz.js";import{Bh as cQ,Ch as h8}from"./vm-hands-entry-lite-6qfax5p2.js";import{Kh as M8,Lh as s9,Oh as J4}from"./vm-hands-entry-lite-5b29hq7h.js";import{Ph as L8,Qh as i0,Rh as N8,Sh as a0,Th as H9,Uh as Y8,Vh as $$,Wh as s0,Xh as p0,Yh as s$,hi as B$}from"./vm-hands-entry-lite-84d59wrf.js";import{ii as x}from"./vm-hands-entry-lite-k17ntg9v.js";import{oi as G4}from"./vm-hands-entry-lite-6f5eypjm.js";import{qi as C}from"./vm-hands-entry-lite-tj1y61bg.js";import{ri as P1,wi as VZ}from"./vm-hands-entry-lite-nd1k2jz9.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 v9($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function P0($,Q,Z=Number.MAX_SAFE_INTEGER){return typeof $==="number"&&Number.isSafeInteger($)&&$>=Q&&$<=Z}function S$($){return typeof $==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test($)}function w$($,Q){let Z=Buffer.from($,"latin1");return Buffer.concat([Buffer.from([Z.length]),Z,Q])}function I0($){if(!v9($)||Object.keys($).length!==12||![$.organizationId,$.userId,$.runId,$.deviceId,$.rootId,$.jobId,$.fenceId].every(S$)||!P0($.attachmentRevision,0)||!P0($.grantRevision,1)||!P0($.generation,1)||!P0($.port,1024,65535)||!P0($.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...$})}function c0($,Q){return Object.keys($).every((Z)=>$[Z]===Q[Z])}function q9($){if($.length>4096||!$.startsWith("/")||$.startsWith("//")||/[\\\x00-\x20\x7f#]/.test($))throw Error("preview_path_invalid");let Q=decodeURIComponent($);if(Q.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(Q))throw Error("preview_path_invalid");return $}function E$($){return Array.isArray($)&&$.length<=64&&$.every((Q)=>Array.isArray(Q)&&Q.length===2&&typeof Q[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(Q[0])&&typeof Q[1]==="string"&&Q[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(Q[1]))}function C9($,Q=v.chunk){if($.length>Math.ceil(Q/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test($))throw Error("preview_data_invalid");let Z=Buffer.from($,"base64");if(Z.length>Q)throw Error("preview_data_too_large");return Z}function b$($){if(Array.isArray($))return Buffer.concat($);if(typeof $==="string")return Buffer.from($,"utf8");if($ instanceof ArrayBuffer)return Buffer.from($);return $}function k$($){if(Buffer.byteLength($)>v.upload*1.4+300000)throw Error("preview_frame_too_large");let Q=JSON.parse($);if(!v9(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(!S$(Q.id))throw Error("preview_frame_invalid");if(Q.type==="end"||Q.type==="cancel"||Q.type==="credit")return{type:Q.type,id:Q.id};if(Q.type==="ws"&&typeof Q.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(Q.protocol))return{type:"ws",id:Q.id,protocol:Q.protocol};if(Q.type==="data"&&typeof Q.data==="string"&&typeof Q.binary==="boolean")return C9(Q.data,v.upload),{type:"data",id:Q.id,data:Q.data,binary:Q.binary};if(Q.type==="head"&&P0(Q.status,200,599)&&E$(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"&&E$(Q.headers)&&typeof Q.body==="string"&&typeof Q.upgrade==="boolean")return C9(Q.body,v.upload),{type:"request",id:Q.id,method:Q.method,path:q9(Q.path),headers:Q.headers,body:Q.body,upgrade:Q.upgrade};throw Error("preview_frame_invalid")}function _8($){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 A8($){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 A8($)===!0}function c9($,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 f$($){if(!v9($)||Object.keys($).length!==2||typeof $.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:I0($.binding),deviceRelayUrl:c9($.deviceRelayUrl,"device")}}function m$($){if(!v9($)||Object.keys($).length!==1||!("binding"in $))throw Error("preview_close_invalid");return{binding:I0($.binding)}}import{request as D4}from"http";import{pipeline as _4}from"stream";import{constants as x8,createBrotliCompress as A4,createGzip as x4}from"zlib";import{WebSocket as O9}from"ws";import{randomBytes as q4,timingSafeEqual as T4}from"crypto";import{createServer as O4}from"net";var g$="x-preview-connection";async function y$($,Q){if(Q.aborted)throw Error("preview_closed");let Z=q4(32).toString("base64url"),X=new Set,J=!1,Y=O4((G)=>{if(J||Q.aborted||X.size>=v.streams*2)return G.destroy();X.add(G);let F=new AbortController;G.once("close",()=>{X.delete(G),F.abort()}),G.on("error",()=>G.destroy()),G.setTimeout(2000,()=>G.destroy());let B=Buffer.alloc(0),H=(L)=>{B=Buffer.concat([B,L]);let W=B.indexOf(`\r
|
|
3
3
|
\r
|
|
4
4
|
`);if(W<0){if(B.length>16384)G.destroy();return}if(G.pause(),G.off("data",H),W>16384||B.length>v.upload+16384)return G.destroy();z(B,W).catch(()=>G.destroy())};G.on("data",H);async function z(L,W){let U=L.subarray(0,W).toString("latin1").split(`\r
|
|
5
5
|
`),j=/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) (\S+) HTTP\/1\.1$/.exec(U.shift()??"");if(!j)throw Error("preview_request_invalid");q9(j[2]);let O=!1,q=0,A=[];for(let T of U){let S=/^([a-zA-Z0-9-]+):[ \t]*([^\x00-\x08\x0a-\x1f\x7f]*)$/.exec(T);if(!S)throw Error("preview_header_invalid");if(S[1].toLowerCase()===g$){q++;let m=Buffer.from(S[2].trim());O=m.length===Z.length&&T4(m,Buffer.from(Z))}else if(S[1].toLowerCase()!=="host")A.push(T)}if(!O||q!==1||J||F.signal.aborted)throw Error("preview_connection_denied");let R=await $.connect(F.signal);if(J||F.signal.aborted)throw R.destroy(),Error("preview_closed");X.add(R),R.on("error",()=>G.destroy()),R.once("close",()=>{X.delete(R),G.destroy()}),G.once("close",()=>R.destroy()),G.setTimeout(0);let P=[`${j[1]} ${j[2]} HTTP/1.1`,`Host: 127.0.0.1:${R.remotePort}`,...A,"",""].join(`\r
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{M as f}from"./vm-hands-entry-lite-
|
|
2
|
+
import{M as f}from"./vm-hands-entry-lite-trcg4jv7.js";import{Fh as T,sh as v,vh as K,yh as U,zh as y}from"./vm-hands-entry-lite-6qfax5p2.js";import{ii as $}from"./vm-hands-entry-lite-k17ntg9v.js";var u=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function _(x){let w=typeof x==="string"?u.exec(x):null;return w?{major:Number(w[1]),minor:Number(w[2])}:null}import{createHash as n,randomBytes as j}from"crypto";import{createInterface as o}from"readline";import{randomBytes as d}from"crypto";import{chmodSync as q,existsSync as C,lstatSync as l,mkdirSync as a,readFileSync as b,renameSync as p,unlinkSync as O,writeFileSync as L}from"fs";import{homedir as t}from"os";import{dirname as i,join as F}from"path";function B(x=process.env,w=t()){let H=x.XDG_CONFIG_HOME?.trim()||F(w,".config"),J=K({env:x})==="staging"?["staging"]:[];return F(T(H,...J),"credentials.json")}function A(x,w=B()){return a(i(w),{recursive:!0,mode:448}),L(w,`${JSON.stringify(x,null,2)}
|
|
3
3
|
`,{mode:384}),q(w,384),w}function M(x=B()){if(!C(x))return null;try{let w=b(x,"utf8"),H=JSON.parse(w);if(typeof H.apiOrigin!=="string"||typeof H.clientId!=="string"||typeof H.accessToken!=="string"||typeof H.refreshToken!=="string"||typeof H.expiresAt!=="string"||typeof H.orgId!=="string"||!Array.isArray(H.scopes))return null;let G=new URL(H.apiOrigin).origin,J=U(G);if(J!==G)s(x,w,J);return{apiOrigin:J,clientId:H.clientId,accessToken:H.accessToken,refreshToken:H.refreshToken,expiresAt:H.expiresAt,scopes:H.scopes.filter((Q)=>typeof Q==="string"),orgId:H.orgId}}catch{return null}}function s(x,w,H){let G=`${x}.${process.pid}.${d(6).toString("hex")}.tmp`;try{let J=l(x);if(!J.isFile()||J.uid!==process.geteuid?.())return;let Q=JSON.parse(w);if(L(G,`${JSON.stringify({...Q,apiOrigin:H},null,2)}
|
|
4
4
|
`,{mode:384,flag:"wx"}),q(G,384),b(x,"utf8")!==w)throw Error("credentials_changed");p(G,x)}catch{try{O(G)}catch{}}}function R(x=B()){if(!C(x))return!1;return O(x),!0}var S=["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 s0=S.filter((x)=>x!=="network:read"&&x!=="network:write");class D extends Error{oauthCode;constructor(x,w=null){super(x);this.oauthCode=w;this.name="LoginError"}}function n0(){let x=j(48).toString("base64url"),w=n("sha256").update(x).digest("base64url");return{verifier:x,challenge:w,state:j(32).toString("base64url")}}function r(x,w){let H=typeof x.error==="string"?x.error:null,G=typeof x.error_description==="string"?x.error_description:H?H:w;return new D(G,H)}async function e(x,w,H,G){let J=await H(`${x}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:w,signal:G}),Q=await J.json().catch(()=>({}));if(!J.ok)throw r(Q,`OAuth token request failed (${J.status})`);return Q}var x0=1e4;async function w0(x,w={}){let H=w.fetchImpl??fetch,G=await e(x.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:x.clientId,refresh_token:x.refreshToken}),H,AbortSignal.timeout(x0)).catch((Q)=>{if(Q instanceof Error&&Q.name==="TimeoutError")throw new D("Reason did not answer the login refresh in time. Check the network and retry.");throw Q});if(typeof G.access_token!=="string"||typeof G.refresh_token!=="string"||typeof G.expires_in!=="number")throw new D("Reason returned an incomplete refreshed login.");let J={...x,accessToken:G.access_token,refreshToken:G.refresh_token,expiresAt:new Date(Date.now()+G.expires_in*1000).toISOString(),scopes:typeof G.scope==="string"?G.scope.split(/\s+/).filter(Boolean):x.scopes};return A(J,w.path??B()),J}var z=new Map;function k(x,w){if(!w)return x;if(w.aborted)return Promise.reject(w.reason);return new Promise((H,G)=>{let J=()=>G(w.reason);w.addEventListener("abort",J,{once:!0}),x.then(H,G).finally(()=>w.removeEventListener("abort",J))})}async function P(x={}){let w=x.path??B(),H=M(w);if(!H)return null;let G=x.apiOrigin??v(process.env,"REASON_API_URL")?.trim();if(G&&!y(H.apiOrigin,new URL(G).origin))return null;let J=Date.parse(H.expiresAt)<=Date.now()+60000;if(!x.forceRefresh&&!J)return H;let Q=[w,H.apiOrigin,H.clientId,H.refreshToken].join("\x00"),V=z.get(Q);if(V)return k(V,x.signal);let Z;return Z=w0(H,{fetchImpl:x.fetchImpl,path:w}).catch(async(Y)=>{if(!(Y instanceof D)||Y.oauthCode!=="invalid_grant"&&Y.oauthCode!=="invalid_client")throw Y;let N=M(w),c=Y.oauthCode==="invalid_client"?N?.clientId!==H.clientId:N?.refreshToken!==H.refreshToken;if(N&&c)return P({fetchImpl:x.fetchImpl,path:w});return R(w),null}).finally(()=>{if(z.get(Q)===Z)z.delete(Q)}),z.set(Q,Z),k(Z,x.signal)}function o0(x,w){return new Promise((H)=>{let G=o({input:x}),J=!1,Q=(Z)=>{if(J)return;J=!0,w.removeEventListener("abort",V),G.close(),x.pause(),H(Z)},V=()=>Q(null);w.addEventListener("abort",V,{once:!0}),G.once("line",(Z)=>Q(Z)),G.once("close",()=>Q(null))})}var $0=$.object({label:$.string(),used_percent:$.number().min(0).max(100).nullable(),resets_at:$.string().nullable(),exhausted:$.boolean().nullable()}),H0=$.object({groups:$.array($.object({selectable:$.boolean().optional(),accounts:$.array($.object({source_id:$.string().min(1),model_ids:$.array($.string().min(1)).optional()}))}))});function G0(x){let w=H0.safeParse(x);if(!w.success)return;return w.data.groups.some((H)=>H.selectable!==!1&&H.accounts.some((G)=>G.model_ids===void 0||G.model_ids.length>0))}class X extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor(x,w,H,G,J,Q){super(H);this.status=x;this.code=w;this.suggestedModel=G;this.retryAfterMs=J;this.resolutionReason=Q;this.name="ApiError"}static rateLimitDelayMs(x,w){if(!(x instanceof X)||x.status!==429)return null;return Math.min(60000,Math.max(w,x.retryAfterMs??0))}}var J0=["minimal","low","medium","high","xhigh","max"],Q0=$.object({id:$.string().min(1),kind:$.string(),name:$.string(),custom_name:$.string().nullish(),status:$.string(),online:$.boolean(),compatible:$.boolean().optional(),compatibility_reason:$.string().nullish(),folder_lane_of:$.string().nullish(),roots:$.array($.object({id:$.string().min(1),label:$.string()}))}),W0=$.object({devices:$.array(Q0),end_cursor:$.string().nullish(),has_next_page:$.boolean().optional()}),Z0=$.object({id:$.string().min(1),name:$.string()}),V0=$.object({items:$.array(Z0)}),X0=$.object({id:$.string().min(1),name:$.string(),main:$.boolean(),mine:$.boolean(),session_id:$.string().nullish(),appearance:$.object({color:$.string().nullish()}).nullish().catch(null)}),Y0=$.object({items:$.array(X0)}),B0=$.object({skill_id:$.string().min(1),name:$.string(),description:$.string().nullish(),activation_keywords:$.array($.string()).default([]),is_enabled:$.boolean().default(!0)}),D0=$.object({items:$.array(B0).default([])}),z0=$.object({id:$.string().min(1),kind:$.string(),enabled:$.boolean(),schedule:$.object({expression:$.string().nullish(),every_seconds:$.number().nullish(),next_run_at:$.string().nullish()}).nullish(),github:$.object({event:$.string().nullish(),action:$.string().nullish(),repo:$.string().nullish()}).nullish(),last_fired_at:$.string().nullish()}),h=$.object({id:$.string().min(1),name:$.string().nullish(),instructions:$.string().nullish(),enabled:$.boolean(),triggers:$.array(z0).default([])}),N0=$.object({items:$.array(h).default([]),end_cursor:$.string().nullish(),has_next_page:$.boolean().optional()}),K0=$.object({id:$.string().min(1),slug:$.string().nullish(),name:$.string(),description:$.string().nullish(),transport:$.string().nullish(),url:$.string().nullish(),enabled:$.boolean()}),M0=$.object({items:$.array(K0).default([])}),P0=$.object({status:$.string(),summary:$.string().nullish(),category:$.string().nullish(),outcome:$.string().nullish(),message_count:$.number().nullish(),pr_url:$.string().nullish(),cost_usd:$.number().nullish(),generated_at:$.string().nullish()}),E=$.object({tags:$.array($.string()).default([])}),_0=$.enum(["linux","macos"]),m=$.object({id:$.string().min(1),name:$.string().min(1),platform:_0.nullable(),workers:$.object({total:$.number().int(),online:$.number().int(),busy:$.number().int(),idle:$.number().int()}),sessions:$.object({queued:$.number().int(),running:$.number().int()})}),F0=$.object({machines:$.array(m)}),U0=$.object({machine:m}),T0=$.object({deleted:$.literal(!0),revoked_workers:$.number().int(),revoked_tokens:$.number().int()}),q0=$.object({token:$.object({id:$.string().min(1),machine_id:$.string().min(1),token_prefix:$.string()}),secret:$.string().startsWith("rmt_")}),I=$.looseObject({machine_id:$.string().min(1),machine_name:$.string().min(1)}),C0=I.extend({organization_id:$.string().min(1)}),b0=$.object({id:$.string().min(1),name:$.string().min(1),state:$.enum(["waiting","placed"]),queue_position:$.number().int().nullable()});function H1(x){let w=b0.safeParse(x.machine);return w.success?w.data:null}var O0=$.union([$.object({kind:$.literal("cloud")}),$.object({kind:$.enum(["mac","headless"]),device_id:$.string().min(1),root_id:$.string().min(1)})]);function G1(x){let w=O0.safeParse(x.runs_on);return w.success?w.data:null}function W(x,w,H){let G=x.safeParse(w);if(!G.success)throw new X(502,H,"Reason returned an unexpected response.");return G.data}var L0=$.object({error:$.object({type:$.string(),message:$.string()})});function g(x,w,H){let G=L0.safeParse(w),J=typeof w.error==="string"?w.error:G.success?G.data.error.type:`http_${x}`,Q=typeof w.detail==="string"?w.detail:typeof w.message==="string"?w.message:G.success?G.data.error.message:`Reason request failed (${x}${typeof w.error==="string"?` ${w.error}`:""})`,V=J==="github_connection_required"&&typeof w.connect_url==="string"&&/^https?:\/\//.test(w.connect_url)?` Connect it at ${w.connect_url}`:"",Z=H===null||H.trim()===""?NaN:Number(H);return new X(x,J,`${Q}${V}`,typeof w.suggested_model==="string"?w.suggested_model:void 0,Number.isFinite(Z)&&Z>=0?Z*1000:void 0,typeof w.resolution_reason==="string"?w.resolution_reason:void 0)}async function J1(x){let w=await(x.fetchImpl??fetch)(`${x.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${x.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(x.body),signal:AbortSignal.timeout(30000),redirect:"error"}),H=await w.json().catch(()=>({}));if(!w.ok)throw g(w.status,H,w.headers.get("retry-after"));return W(C0,H,"invalid_machine_ticket")}class A0{options;credentials;constructor(x,w={}){this.options=w;this.credentials=x}trackEvent(x,w={}){}async request(x,w={},H=!1){let G=this.options.fetchImpl??fetch,J=await G(`${this.credentials.apiOrigin}/v3${x}`,{method:w.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":"reason-cli","x-reason-agent":"Reason CLI",...w.raw?{"content-type":w.raw.contentType}:w.body===void 0?{}:{"content-type":"application/json"},...w.headers},body:w.raw?w.raw.bytes:w.body===void 0?void 0:JSON.stringify(w.body),signal:w.signal,redirect:"error"}),Q=await J.json().catch(()=>({}));if(J.status===401&&!H&&w.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let V=await P({fetchImpl:G,path:this.options.credentialsPath,forceRefresh:!0,signal:w.signal});if(V)return this.credentials=V,this.request(x,w,!0)}if(!J.ok)throw g(J.status,Q,J.headers.get("retry-after"));return Q}createHeadlessDeviceEnrollmentTicket(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:x,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(x){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:x,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(w){if(w instanceof X&&(w.status===404||w.status===405||w.status===403&&w.code==="endpoint_not_available"))return null;throw w}}addDeviceRoot(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(x)}/roots`,{method:"POST",body:w,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(x)}/roots/${encodeURIComponent(w)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(x,w=""){let H=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return x===void 0?H:`${H}/${encodeURIComponent(x)}${w}`}async listMachines(){return W(F0,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(x){let w=await this.request(this.machinePath(),{method:"POST",body:{name:x.name,...x.platform?{platform:x.platform}:{}}});return W(U0,w,"invalid_machine").machine}async deleteMachine(x){let w=await this.request(this.machinePath(x),{method:"DELETE"});return W(T0,w,"invalid_machine_deletion")}async createMachineToken(x){let w=await this.request(this.machinePath(x,"/tokens"),{method:"POST",body:{}});return W(q0,w,"invalid_machine_token")}async createMachineEnrollmentTicket(x,w){let H=await this.request(this.machinePath(x,"/enrollment-tickets"),{method:"POST",body:w,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return W(I,H,"invalid_machine_ticket")}self(x){return this.request("/self",{signal:x})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:x,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:x,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(x,w){let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:x,signal:w});return W(f,H,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(x)}`,{method:"POST",body:w,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(x){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:{messages:x},signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((w)=>typeof w.email==="string"?[{email:w.email,role:typeof w.role==="string"?w.role:"member"}]:[])}claimExistingCliPairing(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:x}})}async claudeCodeSignIn(x){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:x?AbortSignal.any([x,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(x,w,H={}){let G=x.kind==="setup_token"?{setup_token:x.token}:{access_token:x.credential.access,refresh_token:x.credential.refresh,expires_at:new Date(x.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:H.retryUnauthorized,signal:H.signal,body:{...G,...w?{account_key:w}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((w)=>{let H=typeof w.full_name==="string"?w.full_name:typeof w.repo_full_name==="string"?w.repo_full_name:null;if(!H)return[];return[{repo_id:typeof w.repo_id==="string"?w.repo_id:void 0,full_name:H,provider:w.provider==="gitlab"?"gitlab":"github",default_branch:typeof w.default_branch==="string"?w.default_branch:null,private:typeof w.private==="boolean"?w.private:void 0}]})}async listProjects(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),w=V0.safeParse(x);if(!w.success)throw new X(502,"invalid_project_list","Reason returned an unexpected project list.");return w.data.items}async listReasons(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return W(Y0,x,"invalid_reason_list").items}async openReasonConversation(x){let w=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(x)}/conversation`,{method:"POST"});return W($.object({session_id:$.string().min(1)}),w,"invalid_reason_conversation").session_id}async listSkills(){try{let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return W(D0,x,"invalid_skill_list").items}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return[];throw x}}async listDevices(){let x=[],w=null;for(let H=0;H<50;H+=1){let G=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${w?`?after=${encodeURIComponent(w)}`:""}`),J=W0.safeParse(G);if(!J.success)throw new X(502,"invalid_device_list","Reason returned an unexpected machine list.");if(x.push(...J.data.devices),w=J.data.has_next_page?J.data.end_cursor??null:null,!w)break}return x}async listModels(){try{let w=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((J)=>J.hidden!==!0),H=w.filter((J)=>J.available!==!1).map(({reasoning_efforts:J,hidden:Q,available:V,...Z})=>({...Z,...Array.isArray(J)?{reasoning_efforts:J0.filter((Y)=>J.includes(Y))}:{}})),G=new Set(H.map((J)=>J.detail));return{models:H.length>1&&G.size===1?H.map(({detail:J,...Q})=>Q):H,runnable:H.length>0||w.length===0}}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return{models:[],runnable:!0};throw x}}async getAgentVersion(x){try{let w=await this.request("/deployment",{signal:x,retryUnauthorized:!1});return _(w.reason_version)?w.reason_version:null}catch{return null}}async getUsageQuota(){try{let x=$0.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!x.success)return null;let w;try{w=G0(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...x.data,own_inference:w}}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return null;throw x}}async listSessions(x=50,w,H={}){let G=new URLSearchParams({first:String(Math.min(Math.max(x,1),200)),status:H.status??"active"});if(w)G.set("project_id",w);if(H.origin)G.set("origin",H.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${G.toString()}`)).items??[]}getSession(x,w){let H=w?.fields.length?`?fields=${encodeURIComponent(w.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}${H}`)}async prestartSession(x){let w=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:x}});return w?.status==="starting"||w?.status==="ready"}async createSession(x){let w=x.mode==="ephemeral"||x.workspaceOwnership==="externally-managed";if(x.attachments?.length)await this.requireSessionAttachments();if(w||x.runtimeProfile){let J=await this.request("/deployment");if(w&&(!Array.isArray(J.session_modes)||!J.session_modes.includes(x.mode??"standard")||!Array.isArray(J.workspace_ownerships)||!J.workspace_ownerships.includes(x.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(x.runtimeProfile&&(!Array.isArray(J.experimental_runtime_profiles)||!J.experimental_runtime_profiles.includes(x.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:x.prompt,...x.attachments?.length?{attachments:x.attachments}:{},...x.mode?{mode:x.mode}:{},...x.workspaceOwnership?{workspace_ownership:x.workspaceOwnership}:{},...x.target?{target:x.target}:{},...x.repo?{repo:x.repo}:{},...x.provider?{provider:x.provider}:{},...x.model?{model:x.model}:{},...x.reasoningEffort?{reasoning_effort:x.reasoningEffort}:{},...x.runtimeProfile?{experimental_runtime_profile:x.runtimeProfile}:{},...x.ref?{ref:x.ref}:{},...x.branch?{branch:x.branch}:{},...x.completionMode?{completion_mode:x.completionMode}:{},...x.env&&Object.keys(x.env).length>0?{env:x.env}:{},...x.clientSessionId?{client_session_id:x.clientSessionId}:{},...x.longRunning?{long_running:{enabled:!0}}:{},...x.spendLimitRcu?{spend_limit_rcu:x.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),G=await this.getSession(H.session_id);if(w){let J=G.session_policy,Q=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!J||J.version!==1||J.mode!==(x.mode??"standard")||J.workspaceOwnership!==(x.workspaceOwnership??"managed")||!J.components||Q.some((V)=>J.components[V]!==!0))throw await this.cancelSession(H.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(x.runtimeProfile&&G.experimental_runtime_profile!==x.runtimeProfile)throw await this.cancelSession(H.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return G}async getEvents(x,w=-1,H={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/events?after_seq=${w}&limit=500${H.waitMs?`&wait_ms=${H.waitMs}`:""}`,H.signal?{signal:H.signal}:{})}catch(G){if(!(G instanceof X)||G.status!==403&&G.status!==404)throw G;return{session:await this.getSession(x),items:[],next_seq:w}}}async getMessages(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages?first=500${w===void 0?"":`&after_seq=${w}`}`)}async getAttachments(x,w){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/attachments${w?`?view=${w}`:""}`)).items??[]}catch(H){if(H instanceof X&&(H.status===403||H.status===404))return[];throw H}}async requireSessionAttachments(){let x=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(x.session_attachments!==!0){let w=typeof x.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(x.reason_version)?`Agent ${x.reason_version}`:null,H=typeof x.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(x.commit_sha)?`server ${x.commit_sha.slice(0,12)}`:null,G=[w,H].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${G?` (${G})`:""}. 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(x,w,H={}){if(H.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages`,{method:"POST",body:{message:w,...H.attachments?.length?{attachments:H.attachments}:{},...H.model?{model:H.model}:{},...H.reasoningEffort?{reasoning_effort:H.reasoningEffort}:{},...H.target?{target:H.target}:{},...H.delivery?{delivery:H.delivery}:{}}})}async steerQueuedMessage(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages/${encodeURIComponent(w)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages/${encodeURIComponent(w)}/queued`,{method:"DELETE"})}async getConversation(x){let w=[],H=null;for(let G=0;G<50;G+=1){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/conversation${H?`?after=${encodeURIComponent(H)}`:""}`);if(w.push(...J.items??[]),!J.has_next_page||!J.end_cursor)break;H=J.end_cursor}return w}createSharedLink(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/shared-links`,{method:"POST",body:{url:w.url,...w.label?{label:w.label}:{},...w.expiresInSeconds!==void 0?{expires_in_seconds:w.expiresInSeconds}:{}}})}sessionAction(x,w,H={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/${w}`,{method:"POST",body:H})}renameSession(x,w){return this.sessionAction(x,"rename",{title:w||null})}moveSessionToProject(x,w){return this.sessionAction(x,"project",{project_id:w})}compactSession(x){return this.sessionAction(x,"compact")}retrySession(x){return this.sessionAction(x,"retry")}rewindSession(x,w){return this.sessionAction(x,"rewind",{message_id:w.messageId,content:w.content,request_id:w.requestId})}forkSession(x,w){return this.sessionAction(x,"fork",{...w.message?{message:w.message}:{},client_session_id:w.clientSessionId})}cancelSession(x,w={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/cancel`,{method:"POST",body:w.mode==="hard"?{mode:"hard"}:{}})}sessionPath(x,w=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}${w}`}async archiveSession(x){await this.request(this.sessionPath(x,"/archive"),{method:"POST",body:{}})}async unarchiveSession(x){await this.request(this.sessionPath(x,"/unarchive"),{method:"POST",body:{}})}async deleteSession(x){await this.request(this.sessionPath(x),{method:"DELETE"})}async listSessionTags(x){return W(E,await this.request(this.sessionPath(x,"/tags")),"invalid_session_tags").tags}async appendSessionTags(x,w){let H=await this.request(this.sessionPath(x,"/tags"),{method:"POST",body:{tags:w}});return W(E,H,"invalid_session_tags").tags}async sessionInsight(x,w=!1){let H=await this.request(this.sessionPath(x,w?"/insights/generate":"/insights"),w?{method:"POST",body:{}}:{});return W(P0,H,"invalid_session_insight")}async listAutomations(){let x=[],w=null;for(let H=0;H<20;H+=1){let G=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${w?`&after=${encodeURIComponent(w)}`:""}`),J=W(N0,G,"invalid_automation_list");if(x.push(...J.items),w=J.has_next_page?J.end_cursor??null:null,!w)break}return x}async createScheduledAutomation(x,w){let H=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,G=W(h,await this.request(H,{method:"POST",body:{name:x.name,instructions:x.instructions,...x.repo?{repo:x.repo.full_name,provider:x.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${H}/${encodeURIComponent(G.id)}/triggers`,{method:"POST",body:w})}catch(J){throw await this.deleteAutomation(G.id).catch(()=>{return}),J}return G}async setAutomationEnabled(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(x)}`,{method:"PATCH",body:{enabled:w}})}async deleteAutomation(x){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(x)}`,{method:"DELETE"})}async transcribe(x,w){let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:x,contentType:w}});return W($.object({transcript:$.string()}),H,"invalid_transcript").transcript}async listMcpServers(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return W(M0,x,"invalid_mcp_server_list").items}async setSkillEnabled(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(x)}`,{method:"PUT",body:{is_enabled:w}})}}
|
|
5
5
|
export{B as A,M as B,n0 as C,P as D,o0 as E,X as F,J0 as G,H1 as H,G1 as I,J1 as J,A0 as K};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{qi as M}from"./vm-hands-entry-lite-tj1y61bg.js";import{wi as G}from"./vm-hands-entry-lite-nd1k2jz9.js";import{readdirSync as D,readFileSync as I}from"fs";import{userInfo as A}from"os";var O="--vm-hands-op-runner-kind=person";function x(q){let Q=new Set([q]),K=[];try{K=D("/proc")}catch{}for(let z of K){if(!/^\d+$/.test(z))continue;try{let X=I(`/proc/${z}/stat`,"utf8");if(Number(X.slice(X.lastIndexOf(")")+2).split(" ")[3])===q)Q.add(Number(z))}catch{}}for(let z of Q)try{process.kill(z,"SIGKILL")}catch{}}var C=(q)=>{let Q=globalThis.Bun;if(!Q)throw new M("pty_unavailable","Reason terminals require the Bun runtime.");let K=Q.spawn({cmd:[q.shell,...q.args],cwd:q.cwd,env:{...q.environment,TERM:"xterm-256color"},terminal:{cols:q.cols,rows:q.rows,data:(J,Y)=>q.onData(Y)}}),z=K.terminal,X=()=>{x(K.pid);try{z?.close()}catch{}};if(!z)throw X(),new M("pty_unavailable","Reason could not allocate a pseudo-terminal.");return{write:(J)=>z.write(J),resize:(J,Y)=>z.resize(J,Y),kill:X,exited:K.exited.then((J)=>typeof J==="number"?J:null,()=>null)}};function L(){let q=(()=>{try{return A().username}catch{return}})();return{PATH:process.env.PATH,HOME:process.env.HOME,SHELL:process.env.SHELL,LANG:"C.UTF-8",...q?{USER:q,LOGNAME:q}:{}}}async function P(){let[{executeLocalOperation:q,spawnCaptured:Q},{runLocalPtySession:K},{configureDesktopAccount:z},{configureWorkerSandbox:X}]=await Promise.all([import("./local-capabilities-
|
|
2
|
+
import{qi as M}from"./vm-hands-entry-lite-tj1y61bg.js";import{wi as G}from"./vm-hands-entry-lite-nd1k2jz9.js";import{readdirSync as D,readFileSync as I}from"fs";import{userInfo as A}from"os";var O="--vm-hands-op-runner-kind=person";function x(q){let Q=new Set([q]),K=[];try{K=D("/proc")}catch{}for(let z of K){if(!/^\d+$/.test(z))continue;try{let X=I(`/proc/${z}/stat`,"utf8");if(Number(X.slice(X.lastIndexOf(")")+2).split(" ")[3])===q)Q.add(Number(z))}catch{}}for(let z of Q)try{process.kill(z,"SIGKILL")}catch{}}var C=(q)=>{let Q=globalThis.Bun;if(!Q)throw new M("pty_unavailable","Reason terminals require the Bun runtime.");let K=Q.spawn({cmd:[q.shell,...q.args],cwd:q.cwd,env:{...q.environment,TERM:"xterm-256color"},terminal:{cols:q.cols,rows:q.rows,data:(J,Y)=>q.onData(Y)}}),z=K.terminal,X=()=>{x(K.pid);try{z?.close()}catch{}};if(!z)throw X(),new M("pty_unavailable","Reason could not allocate a pseudo-terminal.");return{write:(J)=>z.write(J),resize:(J,Y)=>z.resize(J,Y),kill:X,exited:K.exited.then((J)=>typeof J==="number"?J:null,()=>null)}};function L(){let q=(()=>{try{return A().username}catch{return}})();return{PATH:process.env.PATH,HOME:process.env.HOME,SHELL:process.env.SHELL,LANG:"C.UTF-8",...q?{USER:q,LOGNAME:q}:{}}}async function P(){let[{executeLocalOperation:q,spawnCaptured:Q},{runLocalPtySession:K},{configureDesktopAccount:z},{configureWorkerSandbox:X}]=await Promise.all([import("./local-capabilities-v0bd3pg1.js"),import("./local-pty-session-zen80k1k.js"),import("./desktop-account-gcysz0m3.js"),import("./worker-sandbox-yw24sxyp.js")]);X();let T=process.argv.includes(O),J=($,j,F)=>Q($,j[0]==="-lic"?["-lc",...j.slice(1)]:j,F),Y=(process.geteuid?.()??0)!==0,H=new Map,Z=($)=>{try{process.send?.($)}catch{}};process.on("message",($)=>{let j=$;if(j?.t==="cancel"){H.get(j.id)?.abort();return}if(j?.t!=="op")return;if(!Y){Z({t:"done",id:j.id,completion:{status:"failed",error_code:"vm_hands_payload_account_unavailable"}});return}let F=j.claim.capability;if(F==="pty.start"&&!T){Z({t:"done",id:j.id,completion:{status:"failed",error_code:"capability_not_granted"}});return}let U=new AbortController;H.set(j.id,U);let V=F==="pty.start"?{runPtySession:(B)=>K(B,{spawnPty:C,environment:L(),loadProxy:()=>null})}:{worker:j.worker,...F==="exec.full"?{spawnFullControl:J}:{}};q(j.state,j.claim,{...V,signal:U.signal,emit:(B)=>{let{deliverySignal:N,...W}=B;Z({t:"event",id:j.id,event:W})}}).then((B)=>Z({t:"done",id:j.id,completion:B}),(B)=>Z({t:"done",id:j.id,completion:{status:"failed",error_code:B&&typeof B==="object"&&"code"in B&&typeof B.code==="string"?B.code:"vm_hands_op_failed"}})).finally(()=>H.delete(j.id))}),process.on("disconnect",()=>process.exit(0)),await new Promise(()=>{})}
|
|
3
3
|
export{O as a,C as b,P as c};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{D as T,F as U}from"./vm-hands-entry-lite-
|
|
2
|
+
import{D as T,F as U}from"./vm-hands-entry-lite-95k4g3jj.js";import{mc as V}from"./vm-hands-entry-lite-gcn3rmz6.js";import{sh as G,vh as M,wh as Q}from"./vm-hands-entry-lite-6qfax5p2.js";function W(j,B){let k=G(j,"REASON_API_URL")?.trim();if(!k)return Q(B);let z=new URL(k);if(z.protocol!=="https:"&&!(z.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(z.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return z.origin}function X(j){return G(j,"REASON_API_URL")?.trim()?W(j,"production"):void 0}function $(j){return G(j,"REASON_API_KEY")?.trim()||void 0}async function N(j,B){let k=j.env??process.env,z=$(k);if(!z)return(j.getCredentials??T)({apiOrigin:X(k),signal:B});let J=W(k,j.channel??M({env:k})),D=await(j.fetchImpl??fetch)(J+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+z,accept:"application/json"},signal:B}),L=await D.json().catch(()=>({})),w=V(L)?L:{};if(!D.ok){let H=typeof w.detail==="string"?w.detail:typeof w.message==="string"?w.message:"API key authentication failed ("+D.status+")";throw new U(D.status,typeof w.error==="string"?w.error:"api_key_auth_failed",H)}if(typeof w.org_id!=="string"||!w.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let Z=Array.isArray(w.scopes)?w.scopes.filter((H)=>typeof H==="string"):[];return{credentialKind:"api_key",apiOrigin:J,accessToken:z,orgId:w.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:Z}}async function P(j){let B=await N(j),k=X(j.env??process.env);if(!B)throw Error(k?`Not signed in to ${k}. Set REASON_API_KEY, or run \`reason login --api-url ${k}\`.`:"Not signed in. Run `reason login`, or set REASON_API_KEY.");return B}
|
|
3
3
|
export{W as v,X as w,$ as x,N as y,P as z};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{u as g0}from"./vm-hands-entry-lite-tdgbgcer.js";import{v as Q2,x as N7,y as Y4}from"./vm-hands-entry-lite-
|
|
2
|
+
import{u as g0}from"./vm-hands-entry-lite-tdgbgcer.js";import{v as Q2,x as N7,y as Y4}from"./vm-hands-entry-lite-d9k3dzaq.js";import{A as q2,B as V7,C as M4,D as T4,E as u6,F as v0,J as d6,K as I$}from"./vm-hands-entry-lite-95k4g3jj.js";import{$ as h1,R as jJ,S as WJ,T as y8,U as f8,V as J6,W as Z6,X as b9,Y as A5,Z as v8,_ as _0,aa as m1,ba as P0,ca as n1,da as R5,ea as p5,fa as t3,ga as b5,ka as w5,sa as Y6,ta as G6,ua as K6,va as B6,wa as k9}from"./vm-hands-entry-lite-t7wda1y5.js";import{$a as oJ,Ba as o8,Bb as z5,Ca as e8,Cb as B9,Eb as H5,Fa as a8,Ha as G5,Ib as $6,Jb as X9,Ka as K5,Pa as N5,Qa as q5,Ra as h8,Sa as m8,Ta as nJ,Ua as rJ,Wa as u,Xa as e,Ya as s,Za as c,_a as i8,ab as _1,db as G3,eb as K3,fb as G7,gb as K7,hb as B7,ib as b0,jb as J0,kb as g,lb as w9,mb as R1,nb as Z2,ob as N0,pb as eJ,ub as d5,wb as H8,ya as I6,zb as m2}from"./vm-hands-entry-lite-953ekkrb.js";import{Ob as g8}from"./vm-hands-entry-lite-dyy62gt3.js";import{Vb as O5}from"./vm-hands-entry-lite-wpx6sg6d.js";import{$b as U5,_b as B5,gc as V5}from"./vm-hands-entry-lite-nbtpm59m.js";import{mc as H$}from"./vm-hands-entry-lite-gcn3rmz6.js";import{Bc as k8}from"./vm-hands-entry-lite-beannz0s.js";import{Hc as c$,Ic as X$,Jc as C$,Kc as F1,Lc as l6,Mc as q7,Nc as H7,Oc as L1,Pc as M7,Qc as s9,Rc as T7,Sc as Z3,Tc as T$,Uc as G8,Vc as Q3,Zc as C5,ad as Q6,dd as DJ,ed as OJ}from"./vm-hands-entry-lite-r5nskvf8.js";import{Yd as w8,ee as f6,fe as t$,pe as V2,qd as C2,ud as aJ,vd as iJ}from"./vm-hands-entry-lite-qf01e5f1.js";import{Ce as U7,De as n2,Ge as X6,Je as l1,Le as w7,Me as k7,Re as S5}from"./vm-hands-entry-lite-qk2t0xs7.js";import{Xe as r1,Ye as D5}from"./vm-hands-entry-lite-xhjbc3e4.js";import{$e as o6,cf as I5,df as x9,ff as u8}from"./vm-hands-entry-lite-njne26yc.js";import{sf as t}from"./vm-hands-entry-lite-swz6ea7y.js";import{$f as w1,ag as G0,bg as B2,cg as N6,dg as q6,eg as r$,fg as W3,gg as k2,hg as z4,jg as y2,kg as k$,lg as f0,mg as o$,ng as f2,qg as y$}from"./vm-hands-entry-lite-33ttamma.js";import{ug as Y5}from"./vm-hands-entry-lite-mybm2kyz.js";import{Ah as B4,Bh as Q7,Ch as X7,Eh as A2,Fh as Y7,Gh as E9,Hh as X8,Ih as Y8,Jh as Q1,sh as O$,th as E1,vh as Q$,yh as z$,zh as C0}from"./vm-hands-entry-lite-6qfax5p2.js";import{Kh as U0,Mh as vJ}from"./vm-hands-entry-lite-5b29hq7h.js";import{ii as U}from"./vm-hands-entry-lite-k17ntg9v.js";import{li as tJ}from"./vm-hands-entry-lite-6f5eypjm.js";import{qi as h0}from"./vm-hands-entry-lite-tj1y61bg.js";import{wi as JB}from"./vm-hands-entry-lite-nd1k2jz9.js";import{spawn as _7,spawnSync as ZB}from"child_process";import{closeSync as F7,mkdirSync as QB,openSync as L7,readdirSync as XB,realpathSync as Y$,rmSync as W1}from"fs";import{hostname as YB}from"os";import{dirname as a9,join as F0,resolve as GB}from"path";import{createHash as f7}from"crypto";import{unlinkSync as h7}from"fs";import{platform as m7}from"os";import{join as v7}from"path";var G4=U.discriminatedUnion("store",[U.strictObject({version:U.literal(1),store:U.literal("keychain")}),U.strictObject({version:U.literal(1),store:U.literal("file"),api_key:U.string().min(1).max(4096)})]),w$=($)=>v7($,"api-key.json");function L$($){let J=f7("sha256").update(`reason-connect-api-key
|
|
3
3
|
${$}`).digest("hex");return new r$(B2(),m7(),J)}function L3($,J,Z=L$($)){try{Z.deleteBinding(),Z.createBinding(new TextEncoder().encode(J)),c(w$($),{version:1,store:"keychain"});return}catch(Q){if(!(Q instanceof G0))throw Q}c(w$($),{version:1,store:"file",api_key:J})}function l0($,J=L$($)){if(!u(w$($)))return null;let Z=G4.parse(JSON.parse(s(w$($))));if(Z.store==="file")return Z.api_key;try{let Q=J.loadBinding();return Q?new TextDecoder().decode(Q):null}catch(Q){if(!(Q instanceof G0))throw Q;throw Error("worker_api_key_unreadable")}}function K4($,J=L$($)){if(!u(w$($)))return;if(G4.parse(JSON.parse(s(w$($)))).store==="keychain")try{J.deleteBinding()}catch(Z){if(!(Z instanceof G0))throw Z}h7(w$($))}async function j3($,J){let Z;try{Z=await Y4({env:{REASON_API_KEY:J,REASON_API_URL:$.apiOrigin},fetchImpl:b0($.proxy)})}catch(Q){if(Q instanceof v0&&(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 XZ,renameSync as YZ,rmSync as f$}from"fs";import{join as H0}from"path";import{createHash as g7}from"crypto";import{realpathSync as u7,statSync as d7,unlinkSync as U2}from"fs";import{platform as l7}from"os";import{join as w0}from"path";function d($){return{state:w0(g($),"device.json"),control:w0(g($),"control.json"),lock:w0(g($),"lifecycle.lock"),socket:w0(g($),"control.sock"),daemon:w0(g($),"daemon.json"),releaseCheck:w0(g($),"release-check.json"),updateDeferral:w0(g($),"update-deferral.json"),firstHeartbeat:w0(g($),"first-heartbeat.json")}}var p7=U.object({version:U.literal(1),device_id:U.string().min(1).max(160),offer:U.unknown().optional(),enrollment_ms:U.number().int().nonnegative().max(t$).optional()});function U4($,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 D3($,J){let Z=d($).firstHeartbeat;try{if(!u(Z))return null;let Q=p7.safeParse(JSON.parse(s(Z)));if(U2(Z),!Q.success||Q.data.device_id!==J)return null;let X=V2(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=w0(g($),Q);if(!u(X))return!1;return s(X),!0});return $.lifetime==="persistent"&&Z.join()==="device.json"?O3($):new W3(g($))}function N2($,J){T0($,!0),a7($);let Z=J??O3($),Q=new W3(g($));try{Z.deleteBinding(),Z.deleteKey(),Z.createFreshPublicKey()}catch(X){if(X instanceof G0)return Q;throw X}return Q.deleteBinding(),Q.deleteKey(),Z}function O3($){return new r$(B2(),l7(),c7($))}function c7($){let J=z3($);return g7("sha256").update(`reason-worker
|
|
4
4
|
${J?.directory??g($)}`).digest("hex")}function I1($,J){c(w0(g($),C1),{version:1,directory:z3($)?.directory??g($),devicePublicKey:J})}var C1="keychain-scope.json";function V4($){return u(w0(g($),C1))}var s7=U.strictObject({version:U.literal(1),directory:U.string().min(1),devicePublicKey:U.string().min(1)});function z3($){let J=w0(g($),C1);if(!u(J))return null;let Z=s7.safeParse(JSON.parse(s(J))),Q=d($).state;if(!Z.success||!u(Q))return null;return JSON.parse(s(Q))?.devicePublicKey===Z.data.devicePublicKey?Z.data:null}function a7($){let J=w0(g($),C1);if(!u(J))return;if(z3($))try{let Z=O3($);Z.deleteBinding(),Z.deleteKey()}catch(Z){if(!(Z instanceof G0))throw Z}U2(J)}function V$($){let J=u7($.workspaceRoot);if(J!==$.workspaceRoot||!d7(J).isDirectory()||!R1(J,$.stateDirectory))throw Error("worker_workspace_not_canonical_or_overlaps_state")}function o($){if(!u(g($)))return null;let J=k$(d($).state,{proofStore:T0($),repair:!1}),Z=J!==null&&B4($.apiOrigin,J.apiOrigin),Q=Z?[N0($),N0({...$,apiOrigin:J.apiOrigin})]:[N0($)];if(J&&(!Q.includes(J.worker?.configDigest??"")||J.worker.lifetime!==$.lifetime||J.apiOrigin!==$.apiOrigin&&!Z||J.roots.length>32||J.roots[0]?.path!==$.workspaceRoot||J.handsSlots!==$.slots))throw Error("worker_config_binding_mismatch");return J}var N4=U.strictObject({version:U.literal(1),drained:U.boolean(),revoked:U.boolean()});function $0($){let J=d($).control;return u(J)?N4.parse(JSON.parse(s(J))):{version:1,drained:!1,revoked:!1}}function I0($,J){c(d($).control,N4.parse(J))}function k0($){let J=T0($);J.deleteBinding(),J.deleteKey();let Z=w0(g($),C1);if(u(Z))U2(Z);let Q=d($).state;if(u(Q))U2(Q)}var i7=U.strictObject({read:U.boolean(),write:U.boolean(),execute:U.boolean(),discover_environment:U.boolean(),expose_mcp:U.literal(!1)}),A3=U.strictObject({version:U.literal(1),organization_id:U.string().min(1).max(160),enrollment_ticket:U.string().min(1).max(4096),code_verifier:U.string().regex(/^[A-Za-z0-9._~-]{43,128}$/),root_fingerprint_key:U.string().regex(/^[a-f0-9]{64}$/),root:U.strictObject({path_fingerprint:U.string().regex(/^[a-f0-9]{64}$/),permissions:i7,execution_mode:U.enum(["confined","host"]).default("confined")}),folders:U.array(U.strictObject({path_fingerprint:U.string().regex(/^[a-f0-9]{64}$/)})).min(1).max(31).optional()}),n7=U.object({device_id:U.string().min(1).max(160),organization_id:U.string().min(1).max(160),auth_scheme:U.literal("p256"),protocol_version:U.literal(2),roots:U.array(U.object({id:U.string().min(1),label:U.string(),path_fingerprint:U.string()})).min(1).max(32),headless:U.object({lifecycle:U.enum(["persistent","ephemeral"]),expires_at:U.iso.datetime({offset:!0})}),first_heartbeat:U.unknown().optional()}),R3=30000;class o0 extends Error{deviceRemoved;constructor($){super("worker_enrollment_rejected");this.deviceRemoved=$}}async function r7($,J,Z=fetch){let Q=await Z(`${$}/app/local-runtime/enroll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J),redirect:"error",signal:AbortSignal.timeout(R3)});if(!Q.ok){let X=Q.status===409?await Q.json().catch(()=>null):null;throw new o0(X?.error==="device_revoked")}return Q.json()}async function I3($,J,Z,Q){g0();let X=A3.parse(JSON.parse(s(J)));return e0($,X,Z,Q)}async function e0($,J,Z,Q=(Y,G)=>r7(Y,G,b0($.proxy)),X=performance.now()){let Y=H4($,J,Z),G=await Q($.apiOrigin,{...Y.request,enrollment_ticket:J.enrollment_ticket,code_verifier:J.code_verifier});return Y.receipt(G,X)}async function q4($,J,Z,Q,X=performance.now()){let Y=H4($,J,Z),G=await Q(Y.request,J.code_verifier);return G===null?null:Y.receipt(G,X)}function H4($,J,Z){if(g0(),J.root.execution_mode!==$.executionMode)throw Error("worker_enrollment_mode_mismatch");let Q=y$([$.workspaceRoot],J.root.permissions,Buffer.from(J.root_fingerprint_key,"hex"))[0];if(Q.path!==$.workspaceRoot||Q.pathFingerprint!==J.root.path_fingerprint)throw Error("worker_enrollment_root_mismatch");let X=($.folders??[]).map((K,N)=>{let H=y$([K],J.root.permissions,Buffer.from(J.root_fingerprint_key,"hex"))[0];if(H.path!==K||H.pathFingerprint!==J.folders?.[N]?.path_fingerprint)throw Error("worker_enrollment_root_mismatch");return H});if((J.folders?.length??0)!==X.length)throw Error("worker_enrollment_root_mismatch");let Y=[{...Q,label:"workspace"},...X],G;try{G=Z.loadPublicKey()}catch{G=Z.createFreshPublicKey()}return{request:{device_public_key:G,name:$.name,os:process.platform,architecture:process.arch,reason_runtime_version:t,bridge_version:t,protocol_version:2,capabilities:{supported_operations:[]},roots:Y.map((K)=>({label:K.label,path_fingerprint:K.pathFingerprint,permissions:J.root.permissions}))},receipt(K,N){let H=n7.parse(K);if(H.organization_id!==J.organization_id||H.roots.length!==Y.length||H.roots.some((q,M)=>q.path_fingerprint!==Y[M].pathFingerprint)||H.headless.lifecycle!==$.lifetime||Date.parse(H.headless.expires_at)<=Date.now())throw Error("worker_enrollment_receipt_mismatch");let B=V2(H.first_heartbeat);try{U4($,H.device_id,{...B?{offer:B}:{},enrollmentMs:Math.min(t$,Math.max(0,Math.round(performance.now()-N)))})}catch{}return{version:4,apiOrigin:$.apiOrigin,orgId:H.organization_id,deviceId:H.device_id,devicePublicKey:G,displayName:$.name,registeredAt:new Date().toISOString(),handsSlots:$.slots,worker:{configDigest:N0($),lifetime:$.lifetime,expiresAt:H.headless.expires_at},roots:H.roots.map((q,M)=>({id:q.id,label:q.label,path:Y[M].path,pathFingerprint:q.path_fingerprint,permissions:J.root.permissions}))}}}}import{randomBytes as t7,randomUUID as o7}from"crypto";import{unlinkSync as e7}from"fs";import{join as $Z}from"path";var _4=U.strictObject({version:U.literal(1),install_id:U.uuid(),fingerprint_key:U.string().regex(/^[a-f0-9]{64}$/)}),JZ=U.object({enrollment_ticket:U.string().min(1).max(4096),expires_at:U.iso.datetime({offset:!0}),device_kind:U.literal("headless"),lifecycle:U.enum(["persistent","ephemeral"]),device_expires_at:U.iso.datetime({offset:!0})});function C3($){return JZ.parse($)}var ZZ=U.object({credentialKind:U.enum(["oauth","api_key"]).optional(),apiOrigin:U.url(),clientId:U.string(),accessToken:U.string().min(1).max(32768),refreshToken:U.string().max(32768),expiresAt:U.iso.datetime({offset:!0}),scopes:U.array(U.string().max(128)).max(128),orgId:U.string().min(1).max(160)});function j$($){return q2(E1("REASON_CLI_CHANNEL",$.channel),U0())}async function W$($,J=j$($)){if(!u(J))return null;let Z=ZZ.parse(JSON.parse(s(J)));if(!C0(Z.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(Z.credentialKind==="api_key")return Date.parse(Z.expiresAt)>Date.now()?Z:null;let Q=b0($.proxy),X=Object.assign((G,V)=>Q(G,{...V,redirect:"error",signal:AbortSignal.timeout(30000)}),{preconnect:fetch.preconnect}),Y=await T4({path:J,fetchImpl:X});if(Y&&!C0(Y.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");return Y}async function F4($,J,Z){if(!C0(J.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(!J.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let Q=D$($);return Q.complete(J.orgId,await Z.createHeadlessDeviceEnrollmentTicket(Q.request))}async function L4($,J,Z,Q,X){let Y=performance.now();if(!C0(J.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(!J.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let G=D$($),V=X?void 0:Z.enrollHeadlessDevice?.bind(Z);if(V){let K=await q4($,G.direct(J.orgId),Q,(N,H)=>V({approval:G.request,code_verifier:H,registration:N}).catch((B)=>{throw QZ(B)}),Y);if(K)return K}return e0($,G.complete(J.orgId,await Z.createHeadlessDeviceEnrollmentTicket(G.request)),Q,X,Y)}function QZ($){if(!($ instanceof v0))return $;if($.status===409)return new o0($.code==="device_revoked");if($.status===410||$.status===401&&$.code==="invalid_enrollment_ticket"||$.status===403&&$.code==="grant_exceeded"||$.status===400&&$.code==="invalid_device_enrollment")return new o0(!1);return $}var P1=($)=>$Z(g($),"enrollment-install.json");function j4($){if(u(P1($)))e7(P1($))}function D$($,{stored:J=!0}={}){g0();let Z=P1($),Q=J&&u(Z)?_4.parse(JSON.parse(s(Z))):{version:1,install_id:o7(),fingerprint_key:t7(32).toString("hex")};if(J&&!u(Z))c(Z,Q);let X={read:!0,write:!0,execute:!0,discover_environment:!0,expose_mcp:!1},Y=Buffer.from(Q.fingerprint_key,"hex"),G=y$([$.workspaceRoot],X,Y)[0];if(G.path!==$.workspaceRoot)throw Error("worker_workspace_not_canonical_or_overlaps_state");let V=($.folders??[]).map((B)=>{let q=y$([B],X,Y)[0];if(q.path!==B)throw Error("worker_workspace_not_canonical_or_overlaps_state");return{path_fingerprint:q.pathFingerprint}}),K=M4(),N={install_id:Q.install_id,code_challenge:K.challenge,lifecycle:$.lifetime,roots:[G.pathFingerprint,...V.map((B)=>B.path_fingerprint)].map((B)=>({path_fingerprint:B,permissions:X,execution_mode:$.executionMode}))},H=(B)=>({version:1,organization_id:B,code_verifier:K.verifier,root_fingerprint_key:Q.fingerprint_key,root:{path_fingerprint:G.pathFingerprint,permissions:X,execution_mode:$.executionMode},...V.length?{folders:V}:{}});return{request:N,saveInstall(B){e(g(B),!0),c(P1(B),Q)},complete(B,q){let M=C3(q);if(M.lifecycle!==$.lifetime||Date.parse(M.expires_at)<=Date.now()||Date.parse(M.device_expires_at)<=Date.now())throw Error("worker_ticket_receipt_mismatch");return{...H(B),enrollment_ticket:M.enrollment_ticket}},direct:H}}function W4($,J,Z){let Q=P1($);if(!u(Q))throw Error("worker_folders_unavailable");let X=_4.parse(JSON.parse(s(Q)));return y$([J],Z,Buffer.from(X.fingerprint_key,"hex"))[0]}var H2=8,A4=600000,R4=15000,D4=new Set(["device_revoked","invalid_device_credential"]),M2=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,N$=($)=>H0(g($),"workspaces"),I4="account.json",P3=($)=>u(H0($,I4));function y0($){let J;try{J=XZ(N$($))}catch{return[]}return J.filter((Z)=>M2.test(Z)).sort().map((Z)=>{let Q=H0(N$($),Z),X=H0(Q,"worker.json"),Y=null;try{let G=J0.safeParse(JSON.parse(s(X)));if(G.success&&G.data.stateDirectory===Q)Y=G.data}catch{}return{organizationId:Z,directory:Q,configPath:X,config:Y,account:P3(Q)}})}function T2($,J){let Z=J.toLowerCase();if(!M2.test(Z))throw Error("worker_workspace_id_invalid");let Q=J0.parse({...$,stateDirectory:H0(N$($),Z)});return e(Q.stateDirectory,!0),c(H0(Q.stateDirectory,I4),{version:1}),{config:Q,configPath:H0(Q.stateDirectory,"worker.json")}}function _2($,J){try{let{config:Z,configPath:Q}=T2($,J);e(g(Z),!0),I0(Z,{version:1,drained:!0,revoked:!0}),c(Q,Z)}catch{}}function x1($,J){let Z=J.toLowerCase(),Q=null;try{Q=o($)?.orgId.toLowerCase()??null}catch{}return Q===Z||y0($).some((X)=>!X.account&&X.config!==null&&X.organizationId===Z)}var E3=["device.json","local-device.key","local-device.binding","keychain-scope.json","control.json","enrollment-install.json","first-heartbeat.json"];function O4($,J){let Z=o($);if(!Z?.worker)throw Error("worker_identity_missing");I1($,Z.devicePublicKey),e(g(J),!0);for(let Y of E3)f$(H0(g(J),Y),{force:!0});for(let Y of E3){let G=H0(g($),Y);if(u(G))YZ(G,H0(g(J),Y))}let Q=T0(J),X=k$(d(J).state,{proofStore:Q,repair:!1});if(!X?.worker)throw Error("worker_identity_missing");f0({...X,worker:{...X.worker,configDigest:N0(J)}},d(J).state,{proofStore:Q})}function x3($){for(let J of y0($)){if(J.account)continue;try{if(J.config&&u(d(J.config).state))k0(J.config)}catch{}f$(J.directory,{recursive:!0,force:!0})}f$(b3($),{force:!0})}function F2($,{prefer:J,keep:Z,live:Q=!1}){let X=Date.now(),Y=(B)=>Number(Date.parse(B.worker?.expiresAt??"")>X+60000),V=y0($).flatMap((B)=>{if(!B.account||!B.config)return[];try{if($0(B.config).revoked)return[];let q=o(B.config);return q&&q.orgId.toLowerCase()===B.organizationId&&(!Q||Y(q))?[{...B,config:B.config,state:q}]:[]}catch{return[]}}).sort((B,q)=>Number(q.organizationId===J)-Number(B.organizationId===J)||Y(q.state)-Y(B.state))[0];if(!V)return null;let K=null;try{K=$0($).revoked?null:o($)}catch{}let N=K?.orgId.toLowerCase()??"";if(Z&&K&&M2.test(N)&&N!==V.organizationId){let B=T2($,N);O4($,B.config),c(B.configPath,B.config)}else if(u(g($))){try{if(u(d($).state))k0($)}catch{}for(let B of E3)f$(H0(g($),B),{force:!0})}x3($);let H=J0.parse({...V.config,stateDirectory:$.stateDirectory});return O4(V.config,H),c(H0($.stateDirectory,"worker.json"),H),f$(V.directory,{recursive:!0,force:!0}),H}var S3={before($){for(let{config:J}of y0($))try{let Z=J?o(J):null;if(J&&Z)I1(J,Z.devicePublicKey)}catch{}},after($,J){for(let{organizationId:Z,directory:Q,configPath:X,config:Y}of y0(J)){if(Y)continue;try{let G=J0.parse(JSON.parse(s(X)));if(G.stateDirectory!==H0(N$($),Z))continue;let V=J0.parse({...G,stateDirectory:Q}),K=T0(V),N=k$(d(V).state,{proofStore:K,repair:!1});if(N?.worker?.configDigest===N0(G))f0({...N,worker:{...N.worker,configDigest:N0(V)}},d(V).state,{proofStore:K});c(X,V)}catch{}}}},b3=($)=>H0(N$($),"listed.json");function C4($){try{let J=JSON.parse(s(b3($))),Z=J.names&&typeof J.names==="object"&&!Array.isArray(J.names)?Object.fromEntries(Object.entries(J.names).filter((Q)=>typeof Q[1]==="string")):{};return{listed:J.listed===!0,reason:J.reason==="sign_in"?"sign_in":null,blocked:Array.isArray(J.blocked)?J.blocked.filter((Q)=>typeof Q==="string"):[],names:Z}}catch{return null}}function P4($,J){let Z=y0($),Q=Z.filter((K)=>K.account),X=Z.filter((K)=>!K.account),Y=C4($),G=Y&&!Y.listed?Y.reason:null,V=G||X.length===0&&Y&&!Y.listed?[]:X;if(Q.length===0&&V.length===0&&(G||Y&&!Y.listed))return{workspaces:null,off:G};return{off:G,workspaces:[...Q,...V].map(({organizationId:K,config:N,account:H})=>{let B=!1,q=null,M=!1,T=null;try{B=N?$0(N).revoked:!1,q=N&&!B?o(N):null;let _=N?o$(d(N).daemon):null;M=J&&!!q&&_?.state==="connected",T=M?z4(_,q):null}catch{}return{...T?{permission_recovery:T}:{},organization_id:K,device_id:q?.deviceId??null,name:Y?.names?.[K]??null,root:q?.roots[0]?{id:q.roots[0].id,permissions:q.roots[0].permissions}:null,state:B?"removed":M?"connected":"not_running",blocked:!H&&!B&&!M&&(Y?.blocked.includes(K)??!1),...H?{account:!0}:{}}})}}function E4($){let{config:J,state:Z,client:Q,signal:X}=$,Y=$.log??(()=>{return}),G=new Map,V=null,K=!1,N=C4(J)??{listed:!1,reason:null,blocked:[]},H=(L)=>{let{folders:W,...R}=J,E=Z.roots.slice(1).map((I)=>I.path);return J0.parse({...R,...E.length?{folders:E}:{},stateDirectory:H0(N$(J),L)})},B=async(L)=>{let W=G.get(L);if(!W)return;W.controller.abort(),await W.done},q=(L,W=!1)=>{let R=new AbortController,E=()=>R.abort();if(X.addEventListener("abort",E,{once:!0}),X.aborted)R.abort();let I={...L,controller:R,claims:0,done:Promise.resolve(),account:W};I.done=$.serve(L,R.signal,(C)=>{I.claims=C}).then(()=>{return},(C)=>{if(W&&C instanceof _0&&C.status===401&&D4.has(C.code)){try{I0(L.config,{version:1,drained:!0,revoked:!0})}catch{}Y(`Reason worker: workspace ${L.organizationId} (another account's) no longer accepts this computer (${C.code}); run \`reason connect\` signed in as that account to connect it again
|
|
5
5
|
`)}else if(C instanceof _0&&C.status===401&&D4.has(C.code)){try{k0(L.config)}catch{}Y(`Reason worker: workspace ${L.organizationId} no longer accepts this computer
|
|
@@ -312,7 +312,7 @@ Usage:
|
|
|
312
312
|
`),host:Z.host}),V=$8({...G,log:(M)=>Q.stderr.write(`${M}
|
|
313
313
|
`)}),{configPath:K}=V,N=V.saved;if(!N)return Q.stderr.write("Reason: this computer has no saved connection. Run `reason connect`.\n"),0;let H=(M,T)=>{let _=q3(Z.home,Z.channel),j;try{let O=null;try{O=T.keep?null:o(N)?.orgId.toLowerCase()??null}catch{}if(j=F2(N,{prefer:X2(Z.home,Z.channel,N),...T}),j&&O)_2(j,O)}finally{_()}if(!j)return!1;N=j;let D="";try{D=` (workspace ${o(j)?.orgId??"unknown"})`}catch{}return Q.stderr.write(`Reason: ${M}; this computer goes on running Sessions for its other Reason account${D}.
|
|
314
314
|
`),!0};if($0(N).revoked&&!H("this computer's connection was removed from Reason",{keep:!1}))return Q.stderr.write("Reason: this computer was removed from Reason. Run `reason connect` to connect it again.\n"),0;if(N.executionMode==="confined"||!j1(N)){let M=l0(N.stateDirectory)??void 0,T=M?null:X2(Z.home,Z.channel,N);if(!M&&!(T&&x1(N,T)))H("this computer's connection expired and its account is not signed in here",{keep:!0,live:!0})}let B=N.executionMode==="confined";if(B||!j1(N)){let M=l0(N.stateDirectory)??void 0;if(Q.stderr.write(B?O7:`Reason: this computer's connection expired; renewing it with ${M?"its API key":"your login"}\u2026
|
|
315
|
-
`),await i9(J0.parse({...N,executionMode:"host"}),K,Q,X,M)!==0)return Q.stderr.write(M?"Reason: could not renew this computer's connection. Run `reason connect --api-key KEY` with a valid key.\n":"Reason: could not renew this computer's connection. Run `reason login`, then `reason connect`.\n"),0}let q=new AbortController;if(!X.runWorker)import("./ask-relay-
|
|
315
|
+
`),await i9(J0.parse({...N,executionMode:"host"}),K,Q,X,M)!==0)return Q.stderr.write(M?"Reason: could not renew this computer's connection. Run `reason connect --api-key KEY` with a valid key.\n":"Reason: could not renew this computer's connection. Run `reason login`, then `reason connect`.\n"),0}let q=new AbortController;if(!X.runWorker)import("./ask-relay-3x4np5cy.js").then(({runBackgroundAskRelay:M})=>M(q.signal,(T)=>Q.stderr.write(`${T}
|
|
316
316
|
`))).catch(()=>{});try{for(;;){let M=l0(N.stateDirectory)===null?{ownerWorkspaces:X.worker?.ownerWorkspaces??{}}:{},T=X.runWorker?null:$3({stateDirectory:N.stateDirectory}),_=!1,j;try{j=await(X.runWorker??M$)(["start","--config",K],{deferOptionalLanes:!0,...X.worker,...M,ownComputer:!0,io:{stdout:Q.stdout,stderr:Q.stderr},onDeviceRevoked:()=>{_=!0}})}finally{T?.stop()}if(!_)return j;if(!H("this computer's connection was removed from Reason",{keep:!1}))break}return U3(Z.home,Z.channel,!0),Q.stderr.write("Reason: this computer was removed from Reason. Run `reason connect` to connect it again.\n"),0}finally{q.abort()}}async function MB($,J,Z){let{io:Q,options:X,home:Y,channel:G,environment:V}=Z;if(J&&await(X.controlWorker??V0)(J,"status").catch(()=>null))throw new p("This computer is already connected in the background (see `reason status`). Run `reason disconnect` first to connect it only while a command runs.");let K=u0(Y,G,!0),N=A7({parsed:$,saved:J,stateDirectory:K,lifetime:"ephemeral",home:Y,channel:G,options:X,environment:V}),H=R7(N,Z.apiKey??(J?l0(J.stateDirectory)??void 0:void 0)),B=F0(K,"worker.json");return e(K,!0),c(B,H),Q.stdout.write(p9(`Reason: connecting "${H.name}" while this command runs`,H,Z.host.platform,["Connecting\u2026"])),(X.runWorker??M$)(["start","--config",B],{...n9(X.worker,Z.apiKey),ownComputer:!0,io:{stdout:Q.stdout,stderr:Y3(Q.stderr)},onStartup:(q)=>{if(q==="ready")Q.stdout.write(`Connected. Start Sessions on "${H.name}" from Reason. Press Ctrl-C to stop.
|
|
317
317
|
`);X.worker?.onStartup?.(q)}})}function TB($,J,Z,Q){if(Z.platform!=="darwin")throw new p("--keep-awake is for macOS.");if(!J)throw new p("This computer is not connected to Reason. Run reason connect first.");e(g(J),!0),q8(d(J).daemon,$);let X=R2(d(J).daemon)==="battery_and_ac";return Q.stdout.write(`Keep awake: ${X?"on (this Mac stays awake while it runs Sessions)":"off"}
|
|
318
318
|
`),0}var _B=U.object({root:U.object({id:U.string().min(1).max(160),label:U.string().max(160),path_fingerprint:U.string()})});async function I7($,J,Z,Q){let X=await(n9(Q.worker,Z).enrollmentCredentials??W$)($,j$($));if(!X)throw Error("worker_session_login_required");if(!X.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let Y=Q.folderApi?.(X)??new I$(X,{credentialsPath:j$($),fetchImpl:b0($.proxy)}),G=(V)=>V instanceof v0&&V.status===404&&!["device_not_found","root_not_found"].includes(V.code);return{add:async(V)=>{let K=W4($,V,{...J.roots[0].permissions,expose_mcp:!1}),N=await Y.addDeviceRoot(J.deviceId,{path_fingerprint:K.pathFingerprint,label:K.label,permissions:{...K.permissions,expose_mcp:!1}}).catch((B)=>{if(G(B))throw Error("worker_folders_unavailable");if(B instanceof v0&&B.code==="root_limit_reached")throw new p("This computer already has the most folders Reason allows (32).");throw B}),H=_B.parse(N).root;if(H.path_fingerprint!==K.pathFingerprint)throw Error("worker_enrollment_receipt_mismatch");return{...K,id:H.id,label:H.label}},remove:async(V)=>{await Y.removeDeviceRoot(J.deviceId,V).catch((K)=>{if(G(K))throw Error("worker_folders_unavailable");if(!(K instanceof v0&&K.code==="root_not_found"))throw K})}}}function C7($,J,Z){f0({...J,roots:Z,handsSlots:$.slots,worker:{...J.worker,configDigest:N0($)}},d($).state,{proofStore:T0($)})}async function P7($,J,Z,Q){let{io:X,options:Y,host:G}=Q,V=J&&!Q.apiKey&&l0(J.stateDirectory)===null?X2(Q.home,Q.channel,J):null,K=J&&V&&P$(J)&&!x1(J,V)?y0(J).find((I)=>I.account&&I.organizationId===V)??null:void 0;if(K===null)throw new p("This computer is not connected for your account. Run reason connect first.");let N=K?K.config:J,H=K?K.configPath:Z,B=N&&P$(N)&&!$0(N).revoked?o(N):null;if(!J||!N||!B||N.lifetime!=="persistent")throw new p("This computer is not connected to Reason. Run reason connect first.");let q=$.addFolder!==void 0,M=q?$.addFolder:$.removeFolder,T=Y.cwd??process.cwd(),_;try{_=X3(T,M)}catch(I){if(q)throw new p(I instanceof Error?I.message:String(I));_=GB(T,M)}if(_===N.workspaceRoot)throw new p(`${_} is this computer's main folder. To use another one, run reason connect --folder PATH.`);let j=N.folders??[],D=B.roots.slice(1).find((I)=>I.path===_);if(!q&&!D&&!j.includes(_))throw new p(`${_} is not one of this computer's folders.`);if(q&&!R1(_,N.stateDirectory))throw new p(`${_} holds Reason's own settings.`);if(q&&!D&&j.length>=31)throw new p("This computer already has the most folders Reason allows (32).");let O=Q.apiKey??l0(N.stateDirectory)??void 0,F=await I7(N,B,O,Y),z=B.roots.filter((I)=>I.path!==_);if(q)z=[...z,await F.add(_)];else if(D)await F.remove(D.id);C7(N,B,z);let L=q?[...j.filter((I)=>I!==_),_]:j.filter((I)=>I!==_),{folders:W,...R}=N;if(c(H,J0.parse({...R,...L.length?{folders:L}:{}})),!await(Y.controlWorker??V0)(J,"reload_roots").then(()=>!0,()=>!1))T$(J,G,"connect");return X.stdout.write(q?`Added ${_}. Sessions on "${N.name}" may run in it.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{sf as A}from"./vm-hands-entry-lite-
|
|
2
|
+
import{sf as A}from"./vm-hands-entry-lite-swz6ea7y.js";import{Lf as wz,Mf as Nz}from"./vm-hands-entry-lite-c9wp99nr.js";import{Kh as N}from"./vm-hands-entry-lite-5b29hq7h.js";import{wi as Fz}from"./vm-hands-entry-lite-nd1k2jz9.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-vfh269zs.js")).connectionMacState(),open:(z)=>{iz("/usr/bin/open",z,{stdio:"ignore",timeout:1e4})},tile:Xz,restartConnection:async()=>(await import("./connect-cli-12z734eh.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{Ze as Zq}from"./vm-hands-entry-lite-xhjbc3e4.js";import{af as Aq}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ze as Zq}from"./vm-hands-entry-lite-xhjbc3e4.js";import{af as Aq}from"./vm-hands-entry-lite-njne26yc.js";import{Bf as H,Ef as L0,Hf as y0,If as T8,Jf as sq,Lf as $8,Of as iq,Qf as nq}from"./vm-hands-entry-lite-c9wp99nr.js";import{Zf as j0}from"./vm-hands-entry-lite-jfwz0br7.js";import{pg as U0}from"./vm-hands-entry-lite-33ttamma.js";import{Kh as d}from"./vm-hands-entry-lite-5b29hq7h.js";import{ji as W0}from"./vm-hands-entry-lite-6f5eypjm.js";import{qi as M}from"./vm-hands-entry-lite-tj1y61bg.js";import{execFile as tx,spawn as T0}from"child_process";import{randomBytes as ex}from"crypto";import{chmodSync as q1,existsSync as B0,lstatSync as x1,mkdirSync as X1,readFileSync as Q1,rmSync as P1,writeFileSync as o8}from"fs";import{connect as b1}from"net";import{join as _}from"path";var Uq="./desktop-wallpaper-0pjhgyfk.jpg";var Lq="./dock-browser-afp005mt.png";var yq="./dock-files-rywdm96b.png";var jq="./dock-terminal-s41cj1jp.png";var Tq=`# 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,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ce as xe}from"./vm-hands-entry-lite-qf01e5f1.js";import{Ae as W,Be as oe,De as _t,Ee as Ne,He as St,Ie as wt,Je as $,Se as z,Te as Je}from"./vm-hands-entry-lite-
|
|
2
|
+
import{ce as xe}from"./vm-hands-entry-lite-qf01e5f1.js";import{Ae as W,Be as oe,De as _t,Ee as Ne,He as St,Ie as wt,Je as $,Se as z,Te as Je}from"./vm-hands-entry-lite-qk2t0xs7.js";import{Ye as Se}from"./vm-hands-entry-lite-xhjbc3e4.js";import{_e as Jt,bf as xt,ef as Z,gf as zt,hf as ae}from"./vm-hands-entry-lite-njne26yc.js";import{Lf as Ae,Mf as se}from"./vm-hands-entry-lite-c9wp99nr.js";import{Eh as Ot,sh as v,uh as tt,vh as D}from"./vm-hands-entry-lite-6qfax5p2.js";import{Kh as q}from"./vm-hands-entry-lite-5b29hq7h.js";import{ji as pe,pi as ye}from"./vm-hands-entry-lite-6f5eypjm.js";import{qi as _}from"./vm-hands-entry-lite-tj1y61bg.js";import{spawn as I}from"child_process";import{randomUUID as Oe}from"crypto";import{closeSync as Vr,copyFileSync as de,existsSync as ut,fstatSync as Er,mkdirSync as fe,openSync as vr,readdirSync as V,readFileSync as ge,readlinkSync as to,renameSync as eo,rmSync as ro,statSync as oo}from"fs";import{connect as so}from"net";import{userInfo as Te}from"os";import{basename as le,dirname as mt,join as b}from"path";var At=`import { spawn, execFileSync } from "node:child_process";
|
|
3
3
|
import { createHash, randomUUID } from "node:crypto";
|
|
4
4
|
import { readFileSync, readlinkSync, lstatSync, realpathSync, statSync, mkdtempSync, mkdirSync, chmodSync, writeFileSync, readdirSync, rmSync, openSync, readSync, closeSync, renameSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{wf as $}from"./vm-hands-entry-lite-
|
|
2
|
+
import{wf as $}from"./vm-hands-entry-lite-2w440hvn.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 sf,Z as tf,S as uf,k as vf};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Aa as _4,Ab as J2,Ba as T4,Ca as P4,Da as s6,Db as X7,Ea as n6,Fa as S4,Ga as r6,Gb as j8,Ha as f3,Hb as h4,Ia as a6,Ja as i6,Jb as W7,Ka as o6,La as t6,Ma as k4,Na as e6,Oa as $7,Va as J7,Xa as f4,Ya as b4,bb as Q7,cb as B7,mb as y4,qb as V7,rb as G7,sb as n4,tb as r4,vb as U7,xa as A4,xb as O8,yb as h0,za as L2,zb as v0}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Aa as _4,Ab as J2,Ba as T4,Ca as P4,Da as s6,Db as X7,Ea as n6,Fa as S4,Ga as r6,Gb as j8,Ha as f3,Hb as h4,Ia as a6,Ja as i6,Jb as W7,Ka as o6,La as t6,Ma as k4,Na as e6,Oa as $7,Va as J7,Xa as f4,Ya as b4,bb as Q7,cb as B7,mb as y4,qb as V7,rb as G7,sb as n4,tb as r4,vb as U7,xa as A4,xb as O8,yb as h0,za as L2,zb as v0}from"./vm-hands-entry-lite-953ekkrb.js";import{Kb as Y7,Nb as F7,Pb as N7,Qb as H7}from"./vm-hands-entry-lite-dyy62gt3.js";import{Vb as Z7}from"./vm-hands-entry-lite-wpx6sg6d.js";import{$b as o0,_b as i0,gc as z0}from"./vm-hands-entry-lite-nbtpm59m.js";import{hc as j1,ic as I1,jc as A1,kc as _1,lc as L0}from"./vm-hands-entry-lite-nvhzj5b0.js";import{mc as V1}from"./vm-hands-entry-lite-gcn3rmz6.js";import{Bc as d6,oc as V2,pc as G2,qc as l3,sc as s3,uc as c3,vc as n3,zc as r3}from"./vm-hands-entry-lite-beannz0s.js";import{Wc as Q2,Zc as z7,gd as q7}from"./vm-hands-entry-lite-r5nskvf8.js";import{$d as h6,Ad as g8,Cd as m1,Ed as D6,Fd as M6,Gd as w6,Hd as L6,Id as O6,Jd as j6,Kd as I6,Ld as A6,Md as _6,Nd as T6,Od as P6,Pd as R6,Qd as z6,Rd as q6,Sd as E6,Td as g6,Ud as S6,Vd as k6,Wd as f6,Xd as b6,Zd as x6,_d as y6,ae as m6,be as v6,ce as p6,de as u6,hd as P1,id as R1,jd as S3,je as S8,kd as F2,ke as k8,ld as C6,le as f8,md as k3,me as b8,nd as W4,ne as x8,od as Y4,oe as y8,pd as w0,qe as h8,re as m8,se as v8,td as H0,te as p8,ue as u8,ve as d8,wd as d,we as l8,xd as h1,xe as s8,ye as c8,ze as n8}from"./vm-hands-entry-lite-qf01e5f1.js";import{Fe as Q6,Je as L5,Ke as v5,Qe as E7,Te as O5,Ue as e1}from"./vm-hands-entry-lite-qk2t0xs7.js";import{Ye as Z2}from"./vm-hands-entry-lite-xhjbc3e4.js";import{Af as w7,Cf as L7,Df as O7,Ff as j7,Gf as I7,xf as C7,yf as D7,zf as M7}from"./vm-hands-entry-lite-c9wp99nr.js";import{Rf as A7,Sf as _7,Tf as T7,Xf as P7,_f as R7}from"./vm-hands-entry-lite-jfwz0br7.js";import{ig as x4,pg as K7}from"./vm-hands-entry-lite-33ttamma.js";import{Hg as l6,ug as R3}from"./vm-hands-entry-lite-mybm2kyz.js";import{Kh as E1,Lh as c6,Mh as E4,Nh as g4}from"./vm-hands-entry-lite-5b29hq7h.js";import{Ph as P3,Rh as Q1,Xh as L8,Yh as D4}from"./vm-hands-entry-lite-84d59wrf.js";import{ii as V}from"./vm-hands-entry-lite-k17ntg9v.js";import{qi as C}from"./vm-hands-entry-lite-tj1y61bg.js";import{wi as W8}from"./vm-hands-entry-lite-nd1k2jz9.js";import{request as i7}from"http";import{request as o7}from"https";import{lookup as t7}from"dns/promises";import{isIP as e7}from"net";async function $9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let B=(J.protocol==="https:"?o7:i7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:s3},(K)=>Z({response:K,close:()=>{K.destroy(),B.destroy(),K.socket?.destroy()}}));B.once("error",Q),B.once("timeout",()=>B.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),B.end($.body)})}var a3=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),J9=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function i3($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(a3.has(Z))return"custom_endpoint_host_not_found";if(J9.has(Z))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let B=i3(Q,J+1);if(B)return B}return null}async function Z9($,J){let Z=i3($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||e7(Q)!==0)return Z;let B;return await Promise.race([t7(Q).then(()=>!0,(G)=>!a3.has(String(G?.code))),new Promise((G)=>{B=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(B))?Z:"custom_endpoint_host_not_found"}function Q9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function B9($,J){let Z=Buffer.from($),Q=Buffer.from(J),B=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=B[U-1];if(Z[G]===Z[U])U++;B[G]=U}let K=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+K),Y=0;for(let X of G){while(K&&Z[K]!==X){let F=B[K-1];Y+=Z.copy(W,Y,0,K-F),K=F}if(Z[K]===X){if(K++,K===Z.length)Y+=Q.copy(W,Y),K=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,K),K=0;return W.subarray(0,Y)}}async function o3($){$.signal.throwIfAborted();let J=n3.safeParse($.payload);if(!J.success)throw new C("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=r3.parse(await $.credential($.signal));if(!c3(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new C("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let B,K,G=0,U=0,W=0,Y=Q9(Q.apiKey),X=B9(Q.apiKey,Y),F=async(N,D)=>{$.signal.throwIfAborted(),await new Promise((L,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),L()},(P)=>{$.signal.removeEventListener("abort",I),M(P)})})},H=async(N)=>{if(G+=N.length,G>G2)throw new C("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<N.length;D+=V2){if(W>=l3)throw new C("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+V2).toString("base64")})}};try{let N=await $9({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});B=N.response,K=N.close;let D=B.statusCode??500;if(D>=300&&D<400)throw new C("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(B.headers["content-encoding"]&&B.headers["content-encoding"]!=="identity")throw new C("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let L={};for(let M of["content-type","retry-after","x-request-id","request-id"]){let I=B.headers[M];if(typeof I==="string")L[M]=I.replaceAll(Q.apiKey,Y).slice(0,4096)}await F("custom_endpoint.headers",{status:D,statusText:(B.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:L});for await(let M of B){$.signal.throwIfAborted();let I=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=I.length,U>G2)throw new C("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await H(X(I))}return await H(X(Buffer.alloc(0),!0)),await F(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(N){if($.signal.throwIfAborted(),N instanceof C)throw N;throw new C((B?null:await Z9(N,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{K?.()}}import{join as t3}from"path";function K9($,J){return $===t3(J,".ara","workspace")||$===t3(J,".reason","workspace")}function e3($,J){let Z=$.filter((Q)=>K9(Q.path,J));return Z.length===1?Z[0].path:null}var V9=/^[a-f0-9]{64}$/;var U2=32,G9=/^\/[^\x00-\x1f\x7f\\]*$/;function L1($){if(typeof $!=="string"||$.length>4096||!G9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function O1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!L1(J.home)||!Array.isArray(J.roots)||J.roots.length>U2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:B,path:K}=Q;if(typeof B!=="string"||!V9.test(B)||!L1(K))return;Z.push({path_fingerprint:B,path:K})}return{home:J.home,roots:Z}}function U9($){let J=/^Reason contributor (rc_[0-9a-f]{32})$/.exec($.name)?.[1];return $.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&J?J:void 0}function X9($){return U9($)??$.email.toLowerCase()}function X2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?X9({name:J[1],email:J[2]}):$.trim().toLowerCase()}var n0=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`),W9=[...j1.map(($)=>`/(${$.map(n0).join("/")})(/|$)`),...I1.map(($)=>`/(${$.map(n0).join("/")})(/|$)`),...[...A1].map(($)=>`/(${n0($)})$`),`/${n0(".env.")}[^/]*$`,..._1.map(($)=>`/[^/]*${n0($)}$`)],$4=`function localGithubSandboxProfile(root, temporary) {
|
|
3
3
|
return ['(version 1)','(deny default)','(import "system.sb")','(allow process-exec process-fork)',
|
|
4
4
|
'(allow file-read* (subpath "/bin") (subpath "/sbin") (subpath "/usr/bin") (subpath "/usr/sbin") (subpath "/usr/libexec") (subpath "/usr/share") (subpath "/private/var/select") (literal "/private/var/db/xcode_select_link"))',
|
|
5
5
|
'(allow file-read-metadata (path-ancestors "/opt/homebrew/bin") (path-ancestors "/usr/local/bin") (path-ancestors "/Library/Developer/CommandLineTools"))',
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ii as q}from"./vm-hands-entry-lite-k17ntg9v.js";var u=25,U=q.object({machine:q.string().min(1).max(200),person:q.string().min(1).max(200),team:q.string().min(1).max(200),version:q.string().max(64).optional(),wait_seconds:q.number().int().min(0).max(u).optional()}),x=q.discriminatedUnion("kind",[q.object({id:q.string(),kind:q.literal("who"),all:q.boolean().optional()}),q.object({id:q.string(),kind:q.literal("send"),to:q.string(),body:q.string(),from_name:q.string(),from_agent:q.string(),wake:q.boolean(),reply_to:q.string().max(100).optional(),notify:q.boolean().optional()})]),V=q.object({job:x.nullable(),retry_after_seconds:q.number().optional()}),B=q.object({address:q.string(),person:q.string(),machine:q.string(),agent:q.string(),repo:q.string().nullable(),branch:q.string().nullable(),status:q.string(),since:q.number().nullable(),doing:q.string().nullable(),worker:q.boolean(),tier:q.string().max(10).optional()}),F=q.object({person:q.string(),machine:q.string(),online:q.boolean()}),G=q.object({team:q.string().nullable(),sessions:q.array(B).max(2000),machines:q.array(F).max(500),all:q.boolean().optional()}),H=q.object({address:q.string().max(300),state:q.string().max(40),note:q.string().max(500)}),X=q.union([q.object({who:G}),q.object({sent:q.object({ids:q.array(q.string().max(100)).max(500),recipients:q.array(q.string().max(300)).max(500),from:q.string().max(300),deliveries:q.array(H).max(500).optional()})}),q.object({error:q.string().min(1).max(2000)})]),K=q.object({id:q.string().max(100),from:q.string().max(300),from_agent:q.string().max(100).nullable(),to:q.string().max(300),reply_to:q.string().max(100).nullable(),body:q.string().max(64000),sent_at:q.number()}),Z=q.object({messages:q.array(K).max(100)});
|
|
3
|
+
export{u as L,V as M};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./vm-hands-entry-lite-zrvaqawr.js";import"./vm-hands-entry-lite-qf01e5f1.js";import"./vm-hands-entry-lite-k17ntg9v.js";import{wi as A}from"./vm-hands-entry-lite-nd1k2jz9.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-zrvaqawr.js";import"./vm-hands-entry-lite-qf01e5f1.js";import"./vm-hands-entry-lite-k17ntg9v.js";import{wi as A}from"./vm-hands-entry-lite-nd1k2jz9.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-s5nh8mpx.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-42azzb1d.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{a as Mq}from"./vm-hands-entry-lite-
|
|
2
|
+
import{a as Mq}from"./vm-hands-entry-lite-d93n1cz7.js";import{$a as Uq,Fb as Fq,Ha as Lq,Jb as Tq}from"./vm-hands-entry-lite-953ekkrb.js";import"./vm-hands-entry-lite-wpx6sg6d.js";import"./vm-hands-entry-lite-nbtpm59m.js";import"./vm-hands-entry-lite-nvhzj5b0.js";import"./vm-hands-entry-lite-qf01e5f1.js";import"./vm-hands-entry-lite-xhjbc3e4.js";import"./vm-hands-entry-lite-2w440hvn.js";import"./vm-hands-entry-lite-33ttamma.js";import"./vm-hands-entry-lite-mybm2kyz.js";import"./vm-hands-entry-lite-6qfax5p2.js";import"./vm-hands-entry-lite-5b29hq7h.js";import"./vm-hands-entry-lite-84d59wrf.js";import"./vm-hands-entry-lite-k17ntg9v.js";import"./vm-hands-entry-lite-6f5eypjm.js";import"./vm-hands-entry-lite-tj1y61bg.js";import"./vm-hands-entry-lite-nd1k2jz9.js";import{spawn as Iq}from"child_process";import{chmodSync as vq,chownSync as Oq,existsSync as l,lstatSync as o,mkdirSync as e,mkdtempSync as bq,readdirSync as s,readFileSync as A,realpathSync as hq,rmdirSync as r,rmSync as xq,writeFileSync as E}from"fs";import{join as U}from"path";var wq="/sys/fs/cgroup/reason-payload",_="vm-hands",Vq="/run/ara-srt/fallbacks.jsonl",y="/reason-person",qq=5000,_q=1e4,zq="__VM_HANDS_PROOF_DIR__",Hq="__VM_HANDS_PROBE_NONCE__";class T extends Error{code;constructor(q,z){super(z);this.code=q}}function gq(q,z){if(!/^[0-9a-f-]{36}$/i.test(z))throw new T("vm_hands_bind_invalid","bad bind id");return U(q,_,`b-${z.toLowerCase()}`)}var kq=5000,Rq=(q)=>`'${q.replaceAll("'","'\\''")}'`;function iq(q){let z=q.cgroup??wq,J=q.init.layout.payload_uid,X=q.log??(()=>{}),G=new Map,W=new Map,B=0,P=()=>{try{let Z=A("/run/ara-srt/starts.jsonl","utf8"),Q=Z.slice(B>Z.length?0:B).split(`
|
|
3
3
|
`).filter(Boolean);B=Z.length;let Y=Q.map((L)=>{try{return Number(JSON.parse(L).elapsed_ms)||0}catch{return 0}});if(Y.length)X("vm_hands.srt_server_starts",{count:Y.length,elapsed_ms:Y.slice(0,8)})}catch{}},D=null,H=!1,O=q.srtCgroup??"/sys/fs/cgroup/reason-srt",C=()=>{D??=Gq()},b=0,h=()=>{try{let Z=A(Vq,"utf8"),Q=Z.slice(b>Z.length?0:b);b=Z.length;let Y=Q.split(`
|
|
4
4
|
`).filter(Boolean).slice(0,1000);if(!Y.length)return null;let L={},F=0;for(let M of Y)try{let R=JSON.parse(M),K=typeof R.code==="string"&&/^[a-z_]{1,40}$/.test(R.code)?R.code:"other";if(L[K]=(L[K]??0)+1,typeof R.elapsed_ms==="number")F=Math.max(F,R.elapsed_ms)}catch{L.unparsed=(L.unparsed??0)+1}return X("vm_hands.srt_fallbacks",{count:Y.length,codes:L,max_elapsed_ms:F}),{count:Y.length,codes:L,max_elapsed_ms:F}}catch{return null}},f=!1,m=(Z,Q,Y)=>{if(f)throw Error("vm_hands_pool_held");return Nq(Z,Q,Y)},d=(Z)=>(Q,Y,L)=>Iq("/bin/sh",["-c",`echo $$ > ${Rq(U(Z,"cgroup.procs"))} || exit 125; exec "$@"`,"vm-hands-join",Q,...Y],L),Nq=d(U(z,_)),u=U(z,_,"probe"),S=(Z)=>gq(z,Z),Aq=(Z)=>{let Q=S(Z);try{e(Q,{mode:493})}catch(Y){if(!(Y&&typeof Y==="object"&&("code"in Y)&&Y.code==="EEXIST"))throw new T("vm_hands_bind_failed","bind cgroup")}return Q},Pq=(Z)=>{try{r(S(Z))}catch{}},x=q.prespawn?Uq({spawnProcess:m,...q.relayDependencies?.sourceEntrypoint?{sourceEntrypoint:q.relayDependencies.sourceEntrypoint}:{},log:(Z,Q)=>X(Z,Q??{})}):null;x?.arm();let i=x?setInterval(()=>{x.arm()},kq):null;i?.unref?.();async function c(Z){let Q=G.get(Z);if(G.delete(Z),!Q)return;Q.abort.abort(),await Q.done}return{bindCgroup:S,async startExecutor(Z){if(C(),W.set(Z.bindId,Gq()),H=!0,!Z.claim)throw new T("vm_hands_bind_invalid","an executor needs the claim it serves");await c(Z.bindId);let{claim:Q,bindId:Y}=Z,L=Aq(Y),F=Q.owner;if(!F||typeof F.device_id!=="string"||typeof Q.root_id!=="string")throw new T("vm_hands_bind_invalid","claim without its owner Device or root");let M=new AbortController,R,K,j=new Promise(($,w)=>{R=$,K=w}),I,N=new Promise(($)=>{I=$}),V=Tq({headless:!0,hostExecution:!0,runtimeDirectory:q.runtimeDirectory,deviceIdentity:{deviceId:F.device_id,rootId:Q.root_id,apiOrigin:q.apiOrigin},claimOwner:Q.owner,root:q.root,runId:Q.run_id,operationId:Q.operation_id,attemptId:Q.attempt_id,payload:Object.fromEntries(Object.entries(Q.payload).filter(([$])=>!$.startsWith("vm_hands_"))),signal:M.signal,emitEvent:async($,w)=>{if($==="hands.ready"){R(w);return}if($==="hands.started"||$==="hands.stopped"||$==="hands.failed")return;await q.forward(Y,$,w)}},{...q.relayDependencies,spawnWorker:($)=>d(L)($.command,$.args,$.options),...x?{takePrespawnedWorker:($)=>{let w=x.take($);if(!w?.pid)return w;try{return E(U(L,"cgroup.procs"),String(w.pid)),w}catch{try{w.kill("SIGKILL")}catch{}return null}},adoptSpawnedWorker:x.adopt}:{}}).then(()=>{I("executor_stopped")},($)=>{let w=$&&typeof $==="object"&&"code"in $?String($.code):"executor_failed";K(new T(w,$ instanceof Error?$.message:String($))),I(w)}).finally(()=>K(new T("vm_hands_executor_exited","executor ended before it was ready")));G.set(Y,{abort:M,done:V,exited:N,operationId:Q.operation_id,runId:Q.run_id,expiresAtMs:Date.parse(String(Q.payload.expires_at??""))||0});let g=await j,a=g.executor_launch_id;if(typeof a!=="string")throw new T("vm_hands_bind_failed","executor ready without a launch id");return{launchId:a,readyData:g,applied:{hands_confinement:typeof Q.payload.hands_confinement==="string"?Q.payload.hands_confinement:null,browser_egress:Q.payload.browser_egress??null}}},takeSrtFallbacks:h,executorExited(Z){return G.get(Z)?.exited??new Promise(()=>{})},freezeBind(Z){let Q=S(Z);if(l(U(Q,"cgroup.freeze")))E(U(Q,"cgroup.freeze"),"1")},async killAndVerifyPayload(Z){let Q=new Set(Z?.keep??[]);if(Q.size||Z?.own)return Cq(Z?.bindId??null,Q,Z?.own===!0);f=!0;let Y=Yq();try{await Bq();let L=Promise.all([...G.keys()].map((K)=>c(K).catch(()=>{return})));P();let F=Date.now()+qq;await p(z,F,"payload"),await L;let M=(H||q.srtWarmLate?.()===!0)&&l(U(O,"cgroup.events"));if(M)await p(O,F,"srt");let R=Zq(J).filter((K)=>!v(K,y));if(D!==null){let K=Xq(D).filter((j)=>j!==process.pid&&!v(j,y));if(K.length)throw X("vm_hands.kill_strays",{strays:K.slice(0,16).map((j)=>{let I="?",N="?";try{I=A(`/proc/${j}/comm`,"utf8").trim().slice(0,32)}catch{}try{N=(A(`/proc/${j}/cgroup`,"utf8").split(`
|
|
5
5
|
`).find((V)=>V.startsWith("0::"))??"").slice(3,80)}catch{}return{pid:j,comm:I,cgroup:N}})}),new T("vm_hands_kill_unverified",`${K.length} process(es) the run started survived it`);D=null}if(H=!1,M)q.onSrtReset?.();if(R.length)throw X("vm_hands.kill_survivors",{pids:R.slice(0,16)}),new T("vm_hands_kill_unverified",`${R.length} payload-uid process(es) outside the payload cgroup`);W.clear();for(let K of Qq())try{r(U(z,_,K))}catch{}}finally{f=!1,Y()}if(x)setTimeout(()=>{if(!G.size)x.arm()},100).unref?.()},async killProbe(){let Z=Date.now()+qq;if(l(U(u,"cgroup.events"))){await p(u,Z,"probe");try{r(u)}catch{}}let Q=$q(process.pid);if(Q===null)throw new T("vm_hands_kill_unverified","agent start time unreadable");await yq(z,Q,Z);let Y=(F)=>{let M=$q(F);return M!==null&&M<=Q},L=Zq(J).filter((F)=>Y(F)&&!v(F,y));if(L.length)throw X("vm_hands.kill_survivors",{pids:L.slice(0,16),at:"attest"}),new T("vm_hands_kill_unverified",`${L.length} payload-uid process(es) from before this agent`);if(D!==null){let F=[z,U(z,_)].map((K)=>K.replace(/^\/sys\/fs\/cgroup/,"")),M=O.replace(/^\/sys\/fs\/cgroup/,""),R=Xq(D).filter((K)=>K!==process.pid&&!v(K,y)&&!v(K,"/reason-vm-hands")&&!v(K,M)&&!F.some((j)=>Wq(K,j)));if(R.length)throw X("vm_hands.kill_strays",{strays:R.slice(0,16).map((K)=>({pid:K})),at:"attest"}),new T("vm_hands_kill_unverified",`${R.length} process(es) the probe started survived it`);D=null}},async runProbe({nonce:Z,script:Q}){if(C(),!Q.includes(zq))throw new T("vm_hands_probe_failed","probe names no proof directory");let Y=q.proofParent??"/tmp/reason-vm-hands-proof";e(Y,{mode:457,recursive:!0});let L=o(Y);if(L.isSymbolicLink()||!L.isDirectory()||L.uid!==(process.getuid?.()??-1)||(L.mode&4095)!==457)throw new T("vm_hands_probe_failed","proof parent is not root's 0711 directory");let F=bq(U(Y,"p-")),M=!1;try{if(!/^[A-Za-z0-9/._-]+$/.test(F)||!/^[A-Za-z0-9_-]{1,128}$/.test(Z))throw new T("vm_hands_probe_failed","proof directory path or nonce");Oq(F,J,J),vq(F,448);let R=o(F).ino;try{e(u,{mode:493})}catch(N){if(!(N&&typeof N==="object"&&("code"in N)&&N.code==="EEXIST"))throw new T("vm_hands_probe_failed","probe cgroup")}let K=d(u)("/bin/bash",["-c",Q.replaceAll(zq,F).replaceAll(Hq,Z)],{cwd:"/",env:{PATH:"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},stdio:["ignore","pipe","ignore"]}),j="";K.stdout?.on("data",(N)=>{if(j.length<16384)j+=N.toString("utf8").slice(0,16384-j.length)});let I=await new Promise((N)=>{let V=setTimeout(()=>{M=!0,K.kill("SIGKILL"),N(124)},_q);K.once("error",()=>{clearTimeout(V),N(127)}),K.once("close",(g)=>{clearTimeout(V),N(g??1)})});return X("vm_hands.probe",{nonce_len:Z.length,exit_code:I}),{exitCode:I,markers:j,proofDirInode:R}}finally{if(!M)xq(F,{recursive:!0,force:!0})}},restatLayout(){let{session_root:Z,alias:Q}=q.init.layout,Y="invalid";try{Fq(Z),Y="0:0:755"}catch{}let L=!1,F=-1;try{let M=o(Q);F=M.uid,L=Y==="0:0:755"&&Q===U(Z,"repo")&&!M.isSymbolicLink()&&M.isDirectory()&&hq(Q)===Q&&M.uid===J}catch{}return{root_mode:Y,alias_ok:L,owner_uid:F}},installEnvironment(Z,Q){let Y=G.get(Z);if(!Y)throw new T("environment_unavailable","no executor owns an environment");return Lq({root:q.root,operationId:Y.operationId,payload:Q}).installed_revision},async stop(){if(i)clearInterval(i);x?.close(),await Promise.all([...G.keys()].map((Z)=>c(Z)))}};function Qq(){try{return s(U(z,_),{withFileTypes:!0}).filter((Z)=>Z.isDirectory()&&/^b-[0-9a-f-]{36}$/.test(Z.name)).map((Z)=>Z.name)}catch{return[]}}async function Cq(Z,Q,Y=!1){let L=new Set([...Q].map((M)=>M.toLowerCase())),F=Yq();try{await Bq();let M=Date.now()+qq,R=new Set(Qq().filter(($)=>!L.has($.slice(2))).map(($)=>$.slice(2)));if(Z)R.add(Z.toLowerCase());let K=null;for(let $ of R){let w=c($).catch(()=>{return}),n=W.get($);if(n!==void 0)K=K===null?n:Math.min(K,n);if(l(U(S($),"cgroup.events")))await p(S($),M,"bind");await w}let j=[...L].map(($)=>S($).replace(/^\/sys\/fs\/cgroup/,"")),I=[z,U(z,_)].map(($)=>$.replace(/^\/sys\/fs\/cgroup/,"")),N=O.replace(/^\/sys\/fs\/cgroup/,""),V=($)=>v($,y)||j.some((w)=>v($,w)),g=Y?[]:Zq(J).filter(($)=>!V($));if(g.length)throw X("vm_hands.kill_survivors",{pids:g.slice(0,16),beside:L.size}),new T("vm_hands_kill_unverified",`${g.length} payload-uid process(es) outside a live bind`);let a=($)=>!V($)&&!v($,"/reason-vm-hands")&&!v($,N)&&!I.some((w)=>Wq($,w));if(K!==null){let $=Xq(K).filter((w)=>w!==process.pid&&a(w));if($.length)throw X("vm_hands.kill_strays",{strays:$.slice(0,16).map((w)=>({pid:w})),beside:L.size}),new T("vm_hands_kill_unverified",`${$.length} process(es) the run started survived it`)}for(let $ of R)W.delete($),Pq($)}finally{F()}}}function $q(q,z="/proc"){try{let J=A(U(z,String(q),"stat"),"utf8"),X=Number(J.slice(J.lastIndexOf(")")+2).split(" ")[19]);return Number.isFinite(X)?X:null}catch{return null}}function Sq(q,z="/proc"){try{let J=A(U(z,String(q),"stat"),"utf8"),X=Number(J.slice(J.lastIndexOf(")")+2).split(" ")[1]);return Number.isFinite(X)?X:null}catch{return null}}async function yq(q,z,J){try{E(U(q,"cgroup.freeze"),"1")}catch(X){throw new T("vm_hands_kill_unverified",`payload cgroup.freeze: ${X instanceof Error?X.message:String(X)}`)}try{for(;;){let X=Dq(q).filter((W)=>fq(W,q)),G=new Set(X.filter((W)=>{let B=$q(W);return B!==null&&B<=z}));for(let W=!0;W;){W=!1;for(let B of X){if(G.has(B))continue;let P=Sq(B);if(P!==null&&G.has(P))G.add(B),W=!0}}if(G.size===0)return;if(Date.now()>J)throw new T("vm_hands_kill_unverified",`${G.size} previous-boot process(es) survived`);for(let W of G)try{process.kill(W,"SIGKILL")}catch{}await new Promise((W)=>setTimeout(W,10))}}finally{try{E(U(q,"cgroup.freeze"),"0")}catch{}}}function Wq(q,z,J="/proc"){try{return A(U(J,String(q),"cgroup"),"utf8").split(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{a,b,c}from"./vm-hands-entry-lite-
|
|
2
|
+
import{a,b,c}from"./vm-hands-entry-lite-d93n1cz7.js";import"./vm-hands-entry-lite-tj1y61bg.js";import"./vm-hands-entry-lite-nd1k2jz9.js";export{b as spawnSessionPty,c as runVmHandsOpRunner,a as VM_HANDS_OP_RUNNER_PERSON_ARG};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{N as k,O as m,P as l}from"./vm-hands-entry-lite-zrvaqawr.js";import{rd as v}from"./vm-hands-entry-lite-qf01e5f1.js";import"./vm-hands-entry-lite-k17ntg9v.js";import{wi as G}from"./vm-hands-entry-lite-nd1k2jz9.js";import{spawn as a}from"child_process";import{createHash as t}from"crypto";import{lstatSync as w,mkdirSync as s,readFileSync as i,statSync as e,writeFileSync as d}from"fs";var P="/run/reason-vm-hands",O="/run/reason-vm-hands/env",T="/home/runner/.reason/workspace",jj=/^https:\/\/[a-z0-9.-]+(?::\d{1,5})?$/,S="/sys/fs/cgroup/reason-srt",p="/usr/local/bin/ara-srt-exec",qj=65536,Jj=21600000;function Qj(Q,j="/run/ara-srt"){try{if((process.getuid?.()??-1)!==0)return;s(j,{recursive:!0,mode:448});let J=w(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 R(Q,j){let J=(F)=>{return j("srt_warm_skipped",{reason:F}),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>qj||Z.toString("base64")!==Q.srt_base_settings)return J("settings_invalid");try{let F=w(S);if(!F.isDirectory()||F.uid!==0||(F.mode&18)!==0)return J("cgroup_unsafe");for(let[H,g]of[[p,!1],["/usr/local/bin",!0]]){let Y=w(H);if((g?!Y.isDirectory():!Y.isFile())||Y.uid!==0||(Y.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 X=performance.now(),z=t("sha256").update(Z).digest("hex"),W=`${P}/srt-base-settings.json`;try{d(W,Z,{mode:384,flag:"w"})}catch{return J("settings_write")}let L=a("/bin/sh",["-c",`echo $$ > ${S}/cgroup.procs || exit 125; exec "$@"`,"vm-hands-srt",p,"--settings",W,"--idle-ms",String(Jj),"--","/bin/true"],{cwd:"/",env:{PATH:"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},stdio:"ignore"});return new Promise((F)=>{L.once("error",()=>{j("srt_warm_failed",{reason:"spawn"}),F()}),L.once("close",(H)=>{j(H===0?"srt_warm_done":"srt_warm_failed",{exit_code:H,warm_ms:Math.round(performance.now()-X),settings_sha256:z}),F()})})}var u=3000;function Lj(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let j=Q,J=j.layout,Z=j.device_key,X=j.credential;return typeof j.workspace_id==="string"&&Number.isSafeInteger(j.instance_generation)&&typeof j.api_origin==="string"&&jj.test(j.api_origin)&&typeof j.manifest_digest==="string"&&!!X&&typeof X.key_id==="string"&&Number.isSafeInteger(X.expires_at_ms)&&typeof X.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 y(Q){s(Q,{recursive:!0,mode:448});let j=e(Q);if(!j.isDirectory()||(j.mode&63)!==0||j.uid!==(process.getuid?.()??-1))throw Error(`vm_hands_runtime_directory_unsafe: ${Q}`)}async function Zj(Q){let[{CLI_VERSION:j},J,Z,X]=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 Fj(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:T,pathFingerprint:"0".repeat(64),permissions:{read:!0,write:!0,execute:!0,discover_environment:!0,expose_mcp:!1}}]}}async function Mj(Q,j){y(P),y(O),Qj(j);let J=R(Q,j),Z=!1,X=async()=>{if(!await Promise.race([J.then(()=>!0),new Promise(($)=>setTimeout(()=>$(!1),u).unref?.())]))Z=!0,j("srt_warm_late",{wait_ms:u})},[{configureDesktopAccount:z},{configureWorkerSandbox:W}]=await Promise.all([import("./desktop-account-gcysz0m3.js"),import("./worker-sandbox-yw24sxyp.js")]);W();try{z({value:String(Q.layout.payload_uid)})}catch{j("payload_account_unavailable"),await new Promise(()=>{setInterval(()=>{return},1073741824)})}let L=new AbortController;for(let q of["SIGTERM","SIGINT"])process.on(q,()=>L.abort());let F=new Map,H,g=new Promise((q)=>{H=q}),Y=g.then(()=>import("./vm-hands-executor-
|
|
3
|
+
`,{mode:420}),Q("srt_base_keyed",{})}catch{Q("srt_base_keyed_skipped",{reason:"error"})}}function R(Q,j){let J=(F)=>{return j("srt_warm_skipped",{reason:F}),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>qj||Z.toString("base64")!==Q.srt_base_settings)return J("settings_invalid");try{let F=w(S);if(!F.isDirectory()||F.uid!==0||(F.mode&18)!==0)return J("cgroup_unsafe");for(let[H,g]of[[p,!1],["/usr/local/bin",!0]]){let Y=w(H);if((g?!Y.isDirectory():!Y.isFile())||Y.uid!==0||(Y.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 X=performance.now(),z=t("sha256").update(Z).digest("hex"),W=`${P}/srt-base-settings.json`;try{d(W,Z,{mode:384,flag:"w"})}catch{return J("settings_write")}let L=a("/bin/sh",["-c",`echo $$ > ${S}/cgroup.procs || exit 125; exec "$@"`,"vm-hands-srt",p,"--settings",W,"--idle-ms",String(Jj),"--","/bin/true"],{cwd:"/",env:{PATH:"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},stdio:"ignore"});return new Promise((F)=>{L.once("error",()=>{j("srt_warm_failed",{reason:"spawn"}),F()}),L.once("close",(H)=>{j(H===0?"srt_warm_done":"srt_warm_failed",{exit_code:H,warm_ms:Math.round(performance.now()-X),settings_sha256:z}),F()})})}var u=3000;function Lj(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let j=Q,J=j.layout,Z=j.device_key,X=j.credential;return typeof j.workspace_id==="string"&&Number.isSafeInteger(j.instance_generation)&&typeof j.api_origin==="string"&&jj.test(j.api_origin)&&typeof j.manifest_digest==="string"&&!!X&&typeof X.key_id==="string"&&Number.isSafeInteger(X.expires_at_ms)&&typeof X.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 y(Q){s(Q,{recursive:!0,mode:448});let j=e(Q);if(!j.isDirectory()||(j.mode&63)!==0||j.uid!==(process.getuid?.()??-1))throw Error(`vm_hands_runtime_directory_unsafe: ${Q}`)}async function Zj(Q){let[{CLI_VERSION:j},J,Z,X]=await Promise.all([import("./version-07vvwhvf.js"),import("./hands-worker-source-hbp5n31r.js"),import("./network-contract-rm9x646s.js"),import("./device-workspace-7yg5x68n.js")]),{REASON_HANDS_PROTOCOL_VERSION:z}=await import("./reason-hands-protocol-3z7bas06.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:z,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:X.REASON_WORKSPACE_BASE,workspace_layout:X.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 V=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.list","ports.list","pty.start","jobs.control","automation.call.v1"],$j=new Set(["pty.start","jobs.control"]);function Xj(Q,j){let J=j([{id:"vm-hands",label:"workspace",path:T,pathFingerprint:"0".repeat(64),permissions:{read:!0,write:!0,execute:!0,discover_environment:!0,expose_mcp:!1}}],{worker:{executionMode:"unsandboxed",readiness:Object.fromEntries(V.map((z)=>[z,!0]))}}),Z=Q.capabilities,X={...Z.operation_constraints};for(let z of V)X[z]={...J.operation_constraints?.[z]??{},ready:!0,execution_mode:J.operation_constraints?.[z]?.execution_mode??"host"};return{...Q,capabilities:{...Z,supported_operations:["hands.connect",...V],operation_constraints:X}}}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 Fj(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:T,pathFingerprint:"0".repeat(64),permissions:{read:!0,write:!0,execute:!0,discover_environment:!0,expose_mcp:!1}}]}}async function Mj(Q,j){y(P),y(O),Qj(j);let J=R(Q,j),Z=!1,X=async()=>{if(!await Promise.race([J.then(()=>!0),new Promise(($)=>setTimeout(()=>$(!1),u).unref?.())]))Z=!0,j("srt_warm_late",{wait_ms:u})},[{configureDesktopAccount:z},{configureWorkerSandbox:W}]=await Promise.all([import("./desktop-account-gcysz0m3.js"),import("./worker-sandbox-yw24sxyp.js")]);W();try{z({value:String(Q.layout.payload_uid)})}catch{j("payload_account_unavailable"),await new Promise(()=>{setInterval(()=>{return},1073741824)})}let L=new AbortController;for(let q of["SIGTERM","SIGINT"])process.on(q,()=>L.abort());let F=new Map,H,g=new Promise((q)=>{H=q}),Y=g.then(()=>import("./vm-hands-executor-4ee0fqc5.js")).then(({createVmHandsExecutor:q})=>{let $=q({init:Q,root:T,runtimeDirectory:P,apiOrigin:Q.api_origin,prespawn:!0,onSrtReset:()=>{Z=!1,J=R(Q,j)},srtWarmLate:()=>Z,forward:(B,K,N)=>F.get(B)?.(K,N)??Promise.reject(Error("vm_hands_not_bound")),log:(B,K)=>j(B,K)});return j("executor_loaded"),$}),A=(q)=>async(...$)=>(await Y)[q](...$),C=null;Y.then((q)=>{C=($)=>q.executorExited($)});let M={startExecutor:async(...q)=>{return await X(),A("startExecutor")(...q)},killAndVerifyPayload:A("killAndVerifyPayload"),killProbe:A("killProbe"),runProbe:async(...q)=>{return await X(),A("runProbe")(...q)},restatLayout:()=>{throw Error("replaced below")},installEnvironment:()=>{throw Error("replaced below")},executorExited:(q)=>C?C(q):new Promise(()=>{}),takeSrtFallbacks:()=>null};Y.then((q)=>{M.restatLayout=()=>q.restatLayout(),M.installEnvironment=($,B)=>q.installEnvironment($,B),M.freezeBind=($)=>q.freezeBind($),M.takeSrtFallbacks=()=>q.takeSrtFallbacks?.()??null});let c=await k(Q),o=new m(Q,c,M,{envRoot:O}),h=Zj(Q),b=null,n=Promise.all([h,import("./local-capabilities-v0bd3pg1.js")]).then(([q,$])=>{b=Xj(q,$.capabilityInventoryForRoots),j("device_ops_loaded")}).catch((q)=>j("device_ops_unavailable",{error:q instanceof Error?q.name:"error"})),f=g.then(()=>import("./vm-hands-executor-4ee0fqc5.js")).then(({createVmHandsOpRunners:q,vmHandsBindCgroup:$,VM_HANDS_PAYLOAD_CGROUP:B})=>q({payloadUid:Q.layout.payload_uid,payloadGid:zj(Q.layout.payload_uid),bindCgroup:(K)=>$(B,K),log:(K,N)=>j(K,N)})).catch(()=>null);f.then((q)=>q?.warm("person")),j("agent_ready"),await l({apiOrigin:Q.api_origin,agent:o,signal:L.signal,heartbeat:async()=>b??await h,executeOp:async({kind:q,claim:$,bindId:B,signal:K,emit:N})=>{let x=Fj(Q,$);if(!x)return{status:"failed",error_code:"vm_hands_bind_invalid"};let E={executionMode:"unsandboxed",runtimeDirectory:P,readiness:Object.fromEntries(V.map((U)=>[U,!0]))},_=(U)=>{let D=typeof U.kind==="string"?U.kind:"";if(D)N({kind:D,...U.data&&typeof U.data==="object"?{data:U.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"};let r=$.capability==="pty.start"&&q==="person"&&!$.authority;if($j.has(String($.capability))&&!r){let{executeLocalOperation:U}=await import("./local-capabilities-v0bd3pg1.js");return U(x,$,{worker:E,signal:K,emit:(D)=>_(D)})}let I=await f;if(!I)return{status:"failed",error_code:"vm_hands_payload_account_unavailable"};return I.run(q,{id:String($.attempt_id),claim:$,state:x,worker:E},_,K,B)},readyData:({launchId:q})=>({executor_launch_id:q}),log:(q,$)=>{if(q==="vm_hands.registered"||q==="vm_hands.reconnected")H();j(q,$)},onTurn:(q,$)=>{if($)F.set(q,$);else F.delete(q)}}),await(await Y).stop(),(await f)?.stop()}export{R as startBaseSrtServer,Mj as runVmHands,Lj as parseVmHandsInit,Zj as heartbeatBody,Qj as enableBaseKeyedSrt};
|
package/package.json
CHANGED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{L as _}from"./vm-hands-entry-lite-fs3ahdgg.js";import{sf as c}from"./vm-hands-entry-lite-0amqkh5r.js";import"./vm-hands-entry-lite-7yt58nfv.js";import"./vm-hands-entry-lite-k17ntg9v.js";import{wi as g}from"./vm-hands-entry-lite-nd1k2jz9.js";import{existsSync as Pz,mkdirSync as Uz,readFileSync as Cz,writeFileSync as Mz}from"fs";import{homedir as Oz}from"os";import{dirname as w,join as fz}from"path";import{spawnSync as W}from"child_process";import{createHash as p}from"crypto";import{chmodSync as m,existsSync as K,mkdirSync as b,mkdtempSync as a,readFileSync as i,renameSync as t,rmSync as r,statSync as s,writeFileSync as S}from"fs";import{connect as n}from"net";import{homedir as R}from"os";import{dirname as O,join as H}from"path";class V extends Error{}var D="reason-network",U="0.10.3",o={"aarch64-apple-darwin":"1e793a89ea8b53c603cddbc65ac08b0dd83f1dbfc30a1987858e2c52e2ed907c","x86_64-apple-darwin":"ef1f0f8d7d9e8a286de54eeb78f8ff8a53152c1a661c50b6182bfefa8eef8a02","aarch64-unknown-linux-musl":"75fdfd10314225ffb2875acc7ac73c66de23b5678b684d70b4678eb16ba35124","x86_64-unknown-linux-musl":"17111a623396eed0a2d98aa4d3bb03f00da37c25bdc39b6d0ba3ab202dfbe874"},e="https://reasonmachines.com/cli/engine",G="REASON_AGENT_NETWORK_BIN";function zz(){let z=process.arch==="arm64"?"aarch64":process.arch==="x64"?"x86_64":null,X=process.platform==="darwin"?"apple-darwin":process.platform==="linux"?"unknown-linux-musl":null;return z&&X?`${z}-${X}`:null}function Xz(z){let X=W(z,["--version"],{encoding:"utf8",timeout:5000}),[Z,$]=X.status===0?X.stdout.trim().split(/\s+/):[];return Z===D?$??null:null}function Zz(z,X){let Z=z.split(".").map(Number),$=X.split(".").map(Number);for(let q=0;q<3;q+=1)if((Z[q]??0)!==($[q]??0))return(Z[q]??0)>($[q]??0);return!0}function E(){return H(R(),".reason","bin","reason-network")}async function $z(z=process.env){if(z[G])return z[G];let X=E(),Z=v();if(Z?.path===X&&T(X)===Z.fingerprint)return X;let $=K(X)?Xz(X):null;if(!$||!Zz($,U))await Qz(X);let q=W(X,["setup",...qz(z)?["--no-service"]:[]],{env:z,encoding:"utf8",timeout:60000});if(q.status!==0){let Q=P((q.stderr||q.stdout||"").trim().split(`
|
|
3
|
-
`).pop()??"");throw new V(`Couldn't connect this computer's agents to the network${Q?` (${Q})`:""}. Run reason network setup to try again.`)}return W(X,["stop"],{env:z,stdio:"ignore",timeout:15000}),Bz(X)}function qz(z=process.env){return Boolean(z.REASON_NETWORK_NO_SERVICE||z.TINCAN_NO_SERVICE)}var f=()=>H(R(),".reason","ask-engine.json");function T(z){try{let X=s(z);return`${X.size}:${X.mtimeMs}:${X.ino}`}catch{return null}}function v(){try{let z=JSON.parse(i(f(),"utf8"));return typeof z.path==="string"&&typeof z.fingerprint==="string"&&z.version===U?{path:z.path,fingerprint:z.fingerprint}:null}catch{return null}}function Bz(z){let X=T(z);if(!X)return z;let Z=O(f());if(!K(Z))b(Z,{recursive:!0});return S(f(),JSON.stringify({path:z,fingerprint:X,version:U})),z}async function Qz(z){let X=zz(),Z=X?o[X]:void 0;if(!X||!Z)throw new V(`Reason Network runs on macOS and Linux (arm64 or x64); this is ${process.platform} ${process.arch}.`);let $=`${e}/${U}/${D}-${X}.tar.gz`,q;try{let Y=await fetch($,{signal:AbortSignal.timeout(120000)});if(!Y.ok)throw Error(`HTTP ${Y.status}`);q=Buffer.from(await Y.arrayBuffer())}catch(Y){let F=Y instanceof Error&&Y.name==="TimeoutError"?"no download within 2 minutes":Y instanceof Error?Y.message.replace(/\.$/,""):String(Y);throw new V(`Couldn't download the network engine from ${new URL($).host} (${F}). Check the connection and run reason network again.`)}if(p("sha256").update(q).digest("hex")!==Z)throw new V("The downloaded network engine didn't match its checksum, so it wasn't installed.");b(O(z),{recursive:!0});let B=a(H(O(z),".reason-engine-"));try{if(S(H(B,"engine.tar.gz"),q),W("tar",["-xzf",H(B,"engine.tar.gz"),"-C",B]).status!==0||!K(H(B,D)))throw new V("Couldn't unpack the network engine.");m(H(B,D),493),t(H(B,D),z)}finally{r(B,{recursive:!0,force:!0})}}function Yz(z=process.env,X=R()){let Z=z.REASON_NETWORK_HOME?.trim()||z.TINCAN_HOME?.trim();if(Z)return Z;let $=H(X,".reason","network"),q=H(X,".tincan");return!A($)&&A(q)?q:$}var A=(z)=>K(H(z,"network.db"))||K(H(z,"tincan.db"));function Hz(z){let X=K(H(z,"network.db"))||!K(H(z,"tincan.db")),Z=H(z,X?"network.sock":"tincan.sock");if(Buffer.byteLength(Z)<100)return Z;let $=0xcbf29ce484222325n;for(let q of Buffer.from(Z))$=BigInt.asUintN(64,($^BigInt(q))*0x100000001b3n);return H("/tmp",`${X?"reason-network":"tincan"}-${process.getuid?.()??0}`,`${$.toString(16).padStart(16,"0")}.sock`)}var u=15000,Jz=new Set(["who","team","inbox","unread","held"]),Kz=90000;class x{socket;nextId=1;buffer="";pending=new Map;closed=null;constructor(z){this.socket=z;z.setEncoding("utf8"),z.on("data",(Z)=>this.read(Z));let X=(Z)=>{this.closed=Z;for(let $ of this.pending.values())$.reject(Z);this.pending.clear()};z.on("error",(Z)=>X(Z)),z.on("close",()=>X(Error("the network daemon closed the connection")))}static open(z){return new Promise((X,Z)=>{let $=n(z);$.once("connect",()=>X(new x($))),$.once("error",Z)})}read(z){this.buffer+=z;let X=this.buffer.indexOf(`
|
|
4
|
-
`);while(X>=0){let Z=this.buffer.slice(0,X);if(this.buffer=this.buffer.slice(X+1),X=this.buffer.indexOf(`
|
|
5
|
-
`),!Z.trim())continue;let $;try{$=JSON.parse(Z)}catch{continue}if(typeof $.id!=="number")continue;let q=this.pending.get($.id);if(!q)continue;if(this.pending.delete($.id),$.ok)q.resolve($.result);else q.reject(Error(P($.error??"the network daemon refused the request")))}}call(z,X={},Z=u){if(this.closed)return Promise.reject(this.closed);let $=this.nextId++;return this.socket.write(`${JSON.stringify({id:$,op:z,...X})}
|
|
6
|
-
`),new Promise((q,Q)=>{let B=setTimeout(()=>{this.pending.delete($),Q(Error(`the network daemon didn't answer ${z} within ${Math.round(Z/1000)}s`))},Z);this.pending.set($,{resolve:(Y)=>{clearTimeout(B),q(Y)},reject:(Y)=>{clearTimeout(B),Q(Y)}})})}get isClosed(){return this.closed!==null}close(){this.socket.end()}}var M=/^(Claude Code|Grok|Codex) \u00B7 (.*)$/,Vz={"Claude Code":"claude-code",Grok:"grok",Codex:"codex"},Lz=/^ask-[0-9a-f]{6}$/;function j(z){return{id:z.id,from:z.from,fromAgent:z.from_agent,to:z.to,replyTo:z.reply_to,body:z.body,sentAt:z.sent_at}}function N(z){return{person:z.person,machine:z.machine,isMe:z.is_me,online:z.online,link:z.link,rttMs:z.rtt_ms}}class L{engine;env;connection=null;waits=new Set;constructor(z,X){this.engine=z;this.env=X}static async open(z=process.env){return new L(await $z(z),z)}static openInstalled(z=process.env){if(z[G])return new L(z[G],z);let X=E(),Z=v();return Z?.path===X&&T(X)===Z.fingerprint?new L(X,z):null}socketPath(){return Hz(Yz(this.env))}async open(){try{return await x.open(this.socketPath())}catch{return W(this.engine,["who","--json"],{env:this.env,stdio:"ignore",timeout:15000}),await x.open(this.socketPath())}}async call(z,X={},Z){if(!this.connection||this.connection.isClosed)this.connection=await this.open();try{return await this.connection.call(z,X,Z)}catch($){if(!/closed|ECONNRESET|EPIPE/.test(String($)))throw $;if(this.connection=await this.open(),!Jz.has(z))throw $;return await this.connection.call(z,X)}}async waitOn(z,X){let Z=await this.open();this.waits.add(Z);try{return await Z.call(z,X,X.wait_secs*1000+u)}finally{this.waits.delete(Z),Z.close()}}close(){this.connection?.close(),this.connection=null;for(let z of this.waits)z.close();this.waits.clear()}async team(){try{let z=await this.call("team");return{...z,machines:z.machines.map(N)}}catch(z){if(/team/i.test(String(z)))return null;throw z}}async snapshot(z={}){let X=await this.call("who",{all:Boolean(z.all),...z.filter?{filter:z.filter}:{}}),Z=new Set(X.sessions.filter((q)=>M.test(q.doing??"")).map((q)=>`${q.person}/${q.machine}:${q.cwd}`)),$=X.sessions.filter((q)=>z.all||!Lz.test(q.name)).filter((q)=>M.test(q.doing??"")||!Z.has(`${q.person}/${q.machine}:${q.cwd}`)).map((q)=>{let Q=M.exec(q.doing??"");return{address:q.address,name:q.name,person:q.person,machine:q.machine,agent:Q?Vz[Q[1]]:q.agent,cwd:q.cwd,repo:q.repo,branch:q.branch,status:Q?Q[2]==="ready for work"?"idle":Q[2]==="stopped"?"offline":"busy":q.status,since:q.since,doing:Q?Q[2]:q.doing,isMe:q.is_me,worker:Boolean(Q)}});return{team:X.team,person:X.person,machine:X.machine,machines:X.machines.map(N),sessions:$}}async send(z,X,Z={}){if(!Z.from)await this.call("hook",{agent:"cli",event:"stop",session_id:"terminal",name:"terminal",cwd:process.cwd(),mail:!1});let $=await this.call("send",{from:Z.from??"terminal",to:z,body:X,...Z.replyTo?{reply_to:Z.replyTo}:{},wake:Z.wake??!0});return{ids:$.ids,recipients:$.recipients.map((q)=>q.address)}}async session(z,X={}){let Z=X.agent??"cli",$=(B,Y={})=>this.call("hook",{agent:Z,event:B,session_id:z,name:z,cwd:process.cwd(),mail:!1,...Y}),q=await $("stop"),Q=`${Z}:${z}`;return{name:z,address:q.address??z,next:async(B)=>{return(await this.waitOn("inbox",{key:Q,wait_secs:B,peek:!0})).messages.map(j)},ack:async(B)=>{if(B.length)await this.call("delivered",{key:Q,ids:B})},busy:async(B)=>{if(await $("prompt"),B)await $("doing",{doing:B})},idle:async(B)=>{if(await $("stop"),B)await $("doing",{doing:B})},doing:async(B)=>{await $("doing",{doing:B})},send:(B,Y,F)=>this.send(B,Y,{from:Q,...F?{replyTo:F}:{}})}}async inbox(z={}){let Z=(await this.waitOn("inbox",{key:"cli:terminal",wait_secs:z.waitSeconds??0,peek:!0}).catch(($)=>{if(/isn't registered/.test(String($)))return{messages:[]};throw $})).messages.map(j);if(Z.length&&!z.peek)await this.call("delivered",{key:"cli:terminal",ids:Z.map(($)=>$.id)});return Z}async link(z={}){return await this.call("link",{new:Boolean(z.new)})}async changeTeam(z,X){try{return await this.call(z,X,Kz)}finally{this.close()}}async changeOntoTeam(z,X){try{await this.changeTeam(z,X)}catch(Z){if(!/closed|ECONNRESET|EPIPE/.test(String(Z)))throw Z;if(await this.team())return;await this.changeTeam(z,X)}}async createTeam(z,X){await this.changeOntoTeam("create_team",{name:z,person:X})}async join(z,X){await this.changeOntoTeam("join",{ticket:z,person:X})}async leave(){return await this.changeTeam("leave",{force:!0})}async remove(z){return await this.call("remove",{who:z})}passthrough(z,X={}){this.close();let Z=W(this.engine,z,{stdio:["inherit","pipe","pipe"],encoding:"utf8",env:this.env});if(!X.quiet||Z.status!==0)process.stdout.write(P(Z.stdout??"")),process.stderr.write(P(Z.stderr??""));return Z.status??1}}function P(z){return z.replace(/not in a team yet:[^\n]*/g,"this computer isn't on a team yet: run `reason network setup`").replace(/`tincan (\w+)/g,"`reason network $1").replace(/\btincan (who|send|inbox|invite|join|team|link|setup|doctor|remove|leave|listen)\b/g,"reason network $1").replace(/(?<![\w./-])tincan(?![\w./-])/gi,"Reason Network")}import{existsSync as kz,mkdirSync as cz,readFileSync as Wz,writeFileSync as lz}from"fs";import{homedir as Dz,hostname as mz}from"os";import{dirname as iz,join as Fz}from"path";var Gz=(z)=>Fz(z,".reason","ask.json");function xz(z){try{let X=JSON.parse(Wz(Gz(z),"utf8"));if(typeof X.orgId!=="string"||typeof X.team!=="string")return null;let Z=X.pendingRotation;return{orgId:X.orgId,team:X.team,...typeof X.checkedAt==="number"?{checkedAt:X.checkedAt}:{},...Z&&typeof Z.link==="string"&&typeof Z.team==="string"&&typeof Z.replaces==="string"?{pendingRotation:Z}:{}}}catch{return null}}function y(z=Dz()){let X=xz(z);return X?{orgId:X.orgId,team:X.team}:null}var d=86400000,Rz=300,C=(z)=>fz(z,".reason","ask-relay.json");function I(z){try{let X=JSON.parse(Cz(C(z),"utf8"));return{sessions:Array.isArray(X.sessions)?X.sessions.filter((Z)=>typeof Z?.name==="string"&&typeof Z.agent==="string"&&typeof Z.usedAt==="number"):[]}}catch{return{sessions:[]}}}function Tz(z,X){try{if(!Pz(w(C(z))))Uz(w(C(z)),{recursive:!0});Mz(C(z),`${JSON.stringify(X)}
|
|
7
|
-
`,{mode:384})}catch{}}var J=(z,X)=>new Promise((Z)=>{if(X.aborted)return Z();let $=setTimeout(q,z);$.unref?.();function q(){clearTimeout($),X.removeEventListener("abort",q),Z()}X.addEventListener("abort",q,{once:!0})});function h(z){let X=z?.status;return typeof X==="number"?X:null}var k=60000;function Iz(z){let X=Number.isFinite(z.sentAt)&&Math.abs(z.sentAt)<8640000000000000?z.sentAt:Date.now();return{id:z.id.slice(0,100),from:z.from.slice(0,300),from_agent:z.fromAgent?.slice(0,100)??null,to:z.to.slice(0,300),reply_to:z.replyTo?.slice(0,100)??null,sent_at:X,body:z.body.length>k?`${z.body.slice(0,k)}
|
|
8
|
-
[cut: the answer was ${z.body.length} characters]`:z.body}}class l{network;api;home;signal;log;team;sessions=new Map;readers=new Set;constructor(z,X,Z,$,q,Q){this.network=z;this.api=X;this.home=Z;this.signal=$;this.log=q;this.team=Q}async run(){let z=Date.now()-d;for(let Z of I(this.home).sessions)if(Z.usedAt>z)this.read(Z);let X=0;while(!this.signal.aborted){let Z=await this.network.team().catch(()=>null);if(!Z){await J(60000,this.signal);continue}if(Z.name!==this.team)return;let $;try{let q=await this.api.claimAgentNetworkRelayJob({machine:Z.machine,person:Z.person,team:Z.name,version:c,wait_seconds:_},AbortSignal.any([this.signal,AbortSignal.timeout((_+20)*1000)]));if(X=0,q.retry_after_seconds)await J(q.retry_after_seconds*1000,this.signal);$=q.job}catch(q){if(this.signal.aborted)return;let Q=h(q);if(Q===403||Q===401){await J(900000,this.signal);continue}if(Q===404||Q===405){await J(120000,this.signal);continue}X+=1,await J(Math.min(60000,1000*2**Math.min(X,6)),this.signal);continue}if($)this.carry($)}}async carry(z){let X;try{X=z.kind==="who"?{who:await this.who()}:{sent:await this.send(z)}}catch(Z){X={error:Z instanceof Error?Z.message:String(Z)}}for(let Z=1;;Z+=1)try{if(await this.api.completeAgentNetworkRelayJob(z.id,X),z.kind==="send")this.log(`relayed a message to ${z.to} from ${"sent"in X?X.sent.from:z.from_name}`);return}catch($){if(Z>=4||this.signal.aborted){this.log(`couldn't report a relayed call: ${$ instanceof Error?$.message:String($)}`);return}await J(Z*1000,this.signal)}}async who(){let z=await this.network.snapshot();return{team:z.team,sessions:z.sessions.map((X)=>({address:X.address,person:X.person,machine:X.machine,agent:X.agent,repo:X.repo,branch:X.branch,status:X.status,since:X.since,doing:X.doing,worker:X.worker})),machines:z.machines.map((X)=>({person:X.person,machine:X.machine,online:X.online}))}}async send(z){let X={name:z.from_name,agent:z.from_agent},Z=await this.session(X),$=await Z.send(z.to,z.body);return this.remember(X),this.read(X),{ids:$.ids,recipients:$.recipients,from:Z.address}}session(z){let X=`${z.agent}:${z.name}`,Z=this.sessions.get(X);if(!Z)Z=this.network.session(z.name,{agent:z.agent}).then(async($)=>{return await $.idle(`personal agent (${z.agent}), through Reason`).catch(()=>{}),$}),Z.catch(()=>this.sessions.delete(X)),this.sessions.set(X,Z);return Z}remember(z){let Z=I(this.home).sessions.filter(($)=>$.name!==z.name||$.agent!==z.agent);Tz(this.home,{sessions:[...Z,{...z,usedAt:Date.now()}].slice(-50)})}read(z){let X=`${z.agent}:${z.name}`;if(this.readers.has(X))return;this.readers.add(X),(async()=>{let Z=0;try{while(!this.signal.aborted){let $=I(this.home).sessions.find((q)=>q.name===z.name&&q.agent===z.agent)?.usedAt??0;if(Date.now()-$>d)return;try{let q=await this.session(z),Q=await q.next(Rz);if(Q.length===0)continue;await this.api.recordAgentNetworkRelayReplies(Q.map(Iz)).catch((B)=>{let Y=h(B);if(Y===null||Y>=500||Y===429||Y===401)throw B;this.log(`dropped ${Q.length} answer(s) the server refused (HTTP ${Y})`)}),await q.ack(Q.map((B)=>B.id)),Z=0}catch{if(this.signal.aborted)return;this.sessions.delete(X),Z+=1,await J(Math.min(60000,1000*2**Math.min(Z,6)),this.signal)}}}finally{this.readers.delete(X)}})()}}async function _z(z){await new l(z.network,z.api,z.home??Oz(),z.signal,z.log??(()=>{}),z.team).run()}async function $X(z,X=()=>{}){while(!z.aborted){try{let Z=y(),$=Z?L.openInstalled():null;if(Z&&$){let[{requireApiCredentials:q},{ReasonApi:Q}]=await Promise.all([import("./api-credentials-j2hvs3zw.js"),import("./api-3wwh4c28.js")]),B=await q({});if(B.credentialKind!=="api_key"&&B.orgId.toLowerCase()===Z.orgId.toLowerCase())try{await _z({network:$,api:new Q(B),team:Z.team,signal:z,log:X})}finally{$.close()}}}catch(Z){X(`agent network relay: ${Z instanceof Error?Z.message:String(Z)}`)}await J(300000,z)}}export{$X as runBackgroundAskRelay,_z as runAskRelay};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{ii as j}from"./vm-hands-entry-lite-k17ntg9v.js";var q=25,K=j.object({machine:j.string().min(1).max(200),person:j.string().min(1).max(200),team:j.string().min(1).max(200),version:j.string().max(64).optional(),wait_seconds:j.number().int().min(0).max(q).optional()}),v=j.discriminatedUnion("kind",[j.object({id:j.string(),kind:j.literal("who")}),j.object({id:j.string(),kind:j.literal("send"),to:j.string(),body:j.string(),from_name:j.string(),from_agent:j.string(),wake:j.boolean()})]),P=j.object({job:v.nullable(),retry_after_seconds:j.number().optional()}),x=j.object({address:j.string(),person:j.string(),machine:j.string(),agent:j.string(),repo:j.string().nullable(),branch:j.string().nullable(),status:j.string(),since:j.number().nullable(),doing:j.string().nullable(),worker:j.boolean()}),B=j.object({person:j.string(),machine:j.string(),online:j.boolean()}),F=j.object({team:j.string().nullable(),sessions:j.array(x).max(2000),machines:j.array(B).max(500)}),Q=j.union([j.object({who:F}),j.object({sent:j.object({ids:j.array(j.string().max(100)).max(500),recipients:j.array(j.string().max(300)).max(500),from:j.string().max(300)})}),j.object({error:j.string().min(1).max(2000)})]),G=j.object({id:j.string().max(100),from:j.string().max(300),from_agent:j.string().max(100).nullable(),to:j.string().max(300),reply_to:j.string().max(100).nullable(),body:j.string().max(64000),sent_at:j.number()}),U=j.object({messages:j.array(G).max(100)});
|
|
3
|
-
export{q as L,P as M};
|