@reason-machines/cli-linux-arm64-musl 0.2.293 → 0.2.295
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/ara +1 -1
- package/bin/vm-hands/{connect-cli-n5zpejsx.js → connect-cli-pwvhzdn1.js} +1 -1
- package/bin/vm-hands/{local-automation-ca01a717.js → local-automation-jg8850x7.js} +1 -1
- package/bin/vm-hands/{local-capabilities-jh28c9b9.js → local-capabilities-vr1j2605.js} +1 -1
- package/bin/vm-hands/{local-display-session-gfq7zzes.js → local-display-session-9tbyrsqk.js} +1 -1
- package/bin/vm-hands/{permissions-k8vhjm6s.js → permissions-5bmhsbwr.js} +1 -1
- package/bin/vm-hands/{status-4dae6xxk.js → status-4cjfsvqj.js} +2 -2
- package/bin/vm-hands/{version-hvv128q6.js → version-eyf47yc7.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-mqca81p4.js → vm-hands-entry-lite-32d3ydnw.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-h6f81k57.js → vm-hands-entry-lite-ggkqyxmp.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-06kmrfep.js → vm-hands-entry-lite-qz9mkksp.js} +21 -21
- package/bin/vm-hands/{vm-hands-entry-lite-0y4ch1zw.js → vm-hands-entry-lite-tf9322ea.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-vawn3fzx.js → vm-hands-entry-lite-tm7mv31d.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-yxaee8hg.js → vm-hands-entry-lite-x3ytsxjm.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-s78s7v65.js → vm-hands-entry-lite-yvftswfy.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-kjfzs3tf.js → vm-hands-entry-lite-zeay5yc9.js} +37 -37
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-xq4scwek.js → vm-hands-executor-w3k6wwx4.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-87w1f333.js → vm-hands-op-runner-34mh58h8.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-dmx5z0sk.js → vm-hands-runtime-ws1x5fg0.js} +2 -2
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{t as u0}from"./vm-hands-entry-lite-250sqsry.js";import{A as Q5,B as X5,C as z7,D as O7,E as v3,F as c5,G as B5,H as _0,I as l$,J as p$,K as E0,L as J2,M as s5,N as i0,O as N6,P as Z3,Q as e5,U as $6,ba as C7,ca as I7,da as P7,ea as x7,fa as u3,y as g6,z as u6}from"./vm-hands-entry-lite-
|
|
2
|
+
import{t as u0}from"./vm-hands-entry-lite-250sqsry.js";import{A as Q5,B as X5,C as z7,D as O7,E as v3,F as c5,G as B5,H as _0,I as l$,J as p$,K as E0,L as J2,M as s5,N as i0,O as N6,P as Z3,Q as e5,U as $6,ba as C7,ca as I7,da as P7,ea as x7,fa as u3,y as g6,z as u6}from"./vm-hands-entry-lite-zeay5yc9.js";import{Aa as Y5,Ba as G5,Ca as _7,Da as F7,Fa as u,Ga as e,Ha as s,Ia as c,Ja as T5,Ka as L7,La as W$,Oa as V4,Pa as H4,Qa as OJ,Ra as AJ,Sa as RJ,Ta as k0,Ua as J0,Va as g,Wa as g3,Xa as E$,Ya as K2,Za as U0,_a as D7,db as V6,fb as y8,ha as a7,ib as u2,ka as L5,kb as p5,la as D5,lb as T3,nb as k5,oa as M5,qa as I5,rb as j7,sb as N3,ta as P5,ya as w5,za as b5}from"./vm-hands-entry-lite-qz9mkksp.js";import{Ab as x5,Bb as E5,Ib as S5}from"./vm-hands-entry-lite-5rbj89cs.js";import{Nb as K5}from"./vm-hands-entry-lite-mk9p22xa.js";import{Ub as l5}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Ac as G4,Ec as i5,Hc as A7,Kc as d6,Lc as l6,mc as i1,nc as Y1,oc as _1,pc as L$,qc as BJ,rc as IJ,sc as PJ,tc as D$,uc as xJ,vc as e3,wc as EJ,xc as Y4,yc as F1,zc as P8}from"./vm-hands-entry-lite-ggkqyxmp.js";import{Bd as Z5,Hd as $$,Rd as F2,Vc as b2,Zc as M7,_c as T7}from"./vm-hands-entry-lite-5zzey257.js";import{ae as B}from"./vm-hands-entry-lite-h7ndfgwc.js";import{ie as CJ,je as o2,me as R7,pe as n$,re as iJ,se as nJ,xe as o5}from"./vm-hands-entry-lite-yvftswfy.js";import{$e as h1,Be as b0,Ce as k$,Ee as P0,Fe as j4,He as o0,Ie as z0,Je as b9,Ke as jJ,Le as zJ,Me as E2,Ne as q2,Oe as f3,Pe as C8,Qe as I8,Re as Y$,Se as v$,Te as Y0,Ue as T2,Ve as w7,We as b7,Xe as e1,Ye as R4,_e as Q3,af as m0,bf as y$,cf as X3,ff as m1}from"./vm-hands-entry-lite-zmf3vn3w.js";import{jf as C5}from"./vm-hands-entry-lite-mysjgrwy.js";import{hg as _J,kg as a5,lg as h3,ng as V5}from"./vm-hands-entry-lite-32d3ydnw.js";import{Wg as Z2,Xg as d5}from"./vm-hands-entry-lite-cfjx91rj.js";import{$g as G7,Zg as V0}from"./vm-hands-entry-lite-pr65ksfz.js";import{xh as r}from"./vm-hands-entry-lite-tm7mv31d.js";import{Eh as W7}from"./vm-hands-entry-lite-d94sv87n.js";import{Jh as v0}from"./vm-hands-entry-lite-sn3vjjgx.js";import{spawn as SJ,spawnSync as pK}from"child_process";import{closeSync as wJ,mkdirSync as cK,openSync as bJ,readdirSync as sK,realpathSync as G1,rmSync as z$}from"fs";import{hostname as aK}from"os";import{dirname as $9,join as F0,resolve as iK}from"path";var tJ=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function U9($){let J=typeof $==="string"?tJ.exec($):null;return J?{major:Number(J[1]),minor:Number(J[2])}:null}import{createHash as YZ,randomBytes as z9}from"crypto";import{createInterface as GZ}from"readline";import{randomBytes as oJ}from"crypto";import{chmodSync as M9,existsSync as T9,lstatSync as eJ,mkdirSync as $Z,readFileSync as _9,renameSync as JZ,unlinkSync as F9,writeFileSync as W9}from"fs";import{homedir as ZZ}from"os";import{dirname as QZ,join as q9}from"path";function e0($=process.env,J=ZZ()){let Z=$.XDG_CONFIG_HOME?.trim()||q9(J,".config"),X=P0({env:$})==="staging"?["staging"]:[];return q9(q2(Z,...X),"credentials.json")}function L9($,J=e0()){return $Z(QZ(J),{recursive:!0,mode:448}),W9(J,`${JSON.stringify($,null,2)}
|
|
3
3
|
`,{mode:384}),M9(J,384),J}function P$($=e0()){if(!T9($))return null;try{let J=_9($,"utf8"),Z=JSON.parse(J);if(typeof Z.apiOrigin!=="string"||typeof Z.clientId!=="string"||typeof Z.accessToken!=="string"||typeof Z.refreshToken!=="string"||typeof Z.expiresAt!=="string"||typeof Z.orgId!=="string"||!Array.isArray(Z.scopes))return null;let Q=new URL(Z.apiOrigin).origin,X=o0(Q);if(X!==Q)XZ($,J,X);return{apiOrigin:X,clientId:Z.clientId,accessToken:Z.accessToken,refreshToken:Z.refreshToken,expiresAt:Z.expiresAt,scopes:Z.scopes.filter((Y)=>typeof Y==="string"),orgId:Z.orgId}}catch{return null}}function XZ($,J,Z){let Q=`${$}.${process.pid}.${oJ(6).toString("hex")}.tmp`;try{let X=eJ($);if(!X.isFile()||X.uid!==process.geteuid?.())return;let Y=JSON.parse(J);if(W9(Q,`${JSON.stringify({...Y,apiOrigin:Z},null,2)}
|
|
4
|
-
`,{mode:384,flag:"wx"}),M9(Q,384),_9($,"utf8")!==J)throw Error("credentials_changed");JZ(Q,$)}catch{try{F9(Q)}catch{}}}function D9($=e0()){if(!T9($))return!1;return F9($),!0}var j9=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var SV=j9.filter(($)=>$!=="network:read"&&$!=="network:write");class x$ extends Error{oauthCode;constructor($,J=null){super($);this.oauthCode=J;this.name="LoginError"}}function A9(){let $=z9(48).toString("base64url"),J=YZ("sha256").update($).digest("base64url");return{verifier:$,challenge:J,state:z9(32).toString("base64url")}}function BZ($,J){let Z=typeof $.error==="string"?$.error:null,Q=typeof $.error_description==="string"?$.error_description:Z?Z:J;return new x$(Q,Z)}async function KZ($,J,Z,Q){let X=await Z(`${$}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:J,signal:Q}),Y=await X.json().catch(()=>({}));if(!X.ok)throw BZ(Y,`OAuth token request failed (${X.status})`);return Y}var VZ=1e4;async function HZ($,J={}){let Z=J.fetchImpl??fetch,Q=await KZ($.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:$.clientId,refresh_token:$.refreshToken}),Z,AbortSignal.timeout(VZ)).catch((Y)=>{if(Y instanceof Error&&Y.name==="TimeoutError")throw new x$("Reason did not answer the login refresh in time. Check the network and retry.");throw Y});if(typeof Q.access_token!=="string"||typeof Q.refresh_token!=="string"||typeof Q.expires_in!=="number")throw new x$("Reason returned an incomplete refreshed login.");let X={...$,accessToken:Q.access_token,refreshToken:Q.refresh_token,expiresAt:new Date(Date.now()+Q.expires_in*1000).toISOString(),scopes:typeof Q.scope==="string"?Q.scope.split(/\s+/).filter(Boolean):$.scopes};return L9(X,J.path??e0()),X}var M2=new Map;function O9($,J){if(!J)return $;if(J.aborted)return Promise.reject(J.reason);return new Promise((Z,Q)=>{let X=()=>Q(J.reason);J.addEventListener("abort",X,{once:!0}),$.then(Z,Q).finally(()=>J.removeEventListener("abort",X))})}async function b1($={}){let J=$.path??e0(),Z=P$(J);if(!Z)return null;let Q=$.apiOrigin??b0(process.env,"REASON_API_URL")?.trim();if(Q&&!z0(Z.apiOrigin,new URL(Q).origin))return null;let X=Date.parse(Z.expiresAt)<=Date.now()+60000;if(!$.forceRefresh&&!X)return Z;let Y=[J,Z.apiOrigin,Z.clientId,Z.refreshToken].join("\x00"),G=M2.get(Y);if(G)return O9(G,$.signal);let V;return V=HZ(Z,{fetchImpl:$.fetchImpl,path:J}).catch(async(K)=>{if(!(K instanceof x$)||K.oauthCode!=="invalid_grant"&&K.oauthCode!=="invalid_client")throw K;let N=P$(J),q=K.oauthCode==="invalid_client"?N?.clientId!==Z.clientId:N?.refreshToken!==Z.refreshToken;if(N&&q)return b1({fetchImpl:$.fetchImpl,path:J});return D9(J),null}).finally(()=>{if(M2.get(Y)===V)M2.delete(Y)}),M2.set(Y,V),O9(V,$.signal)}function R9($,J){return new Promise((Z)=>{let Q=GZ({input:$}),X=!1,Y=(V)=>{if(X)return;X=!0,J.removeEventListener("abort",G),Q.close(),$.pause(),Z(V)},G=()=>Y(null);J.addEventListener("abort",G,{once:!0}),Q.once("line",(V)=>Y(V)),Q.once("close",()=>Y(null))})}var NZ=B.object({label:B.string(),used_percent:B.number().min(0).max(100).nullable(),resets_at:B.string().nullable(),exhausted:B.boolean().nullable()}),UZ=B.object({groups:B.array(B.object({selectable:B.boolean().optional(),accounts:B.array(B.object({source_id:B.string().min(1),model_ids:B.array(B.string().min(1)).optional()}))}))});function qZ($){let J=UZ.safeParse($);if(!J.success)return;return J.data.groups.some((Z)=>Z.selectable!==!1&&Z.accounts.some((Q)=>Q.model_ids===void 0||Q.model_ids.length>0))}class G0 extends Error{status;code;suggestedModel;retryAfterMs;constructor($,J,Z,Q,X){super(Z);this.status=$;this.code=J;this.suggestedModel=Q;this.retryAfterMs=X;this.name="ApiError"}static rateLimitDelayMs($,J){if(!($ instanceof G0)||$.status!==429)return null;return Math.min(60000,Math.max(J,$.retryAfterMs??0))}}var MZ=["minimal","low","medium","high","xhigh","max"],TZ=B.object({id:B.string().min(1),kind:B.string(),name:B.string(),custom_name:B.string().nullish(),status:B.string(),online:B.boolean(),compatible:B.boolean().optional(),compatibility_reason:B.string().nullish(),folder_lane_of:B.string().nullish(),roots:B.array(B.object({id:B.string().min(1),label:B.string()}))}),_Z=B.object({devices:B.array(TZ),end_cursor:B.string().nullish(),has_next_page:B.boolean().optional()}),FZ=B.object({id:B.string().min(1),name:B.string()}),WZ=B.object({items:B.array(FZ)}),LZ=B.object({skill_id:B.string().min(1),name:B.string(),description:B.string().nullish(),activation_keywords:B.array(B.string()).default([]),is_enabled:B.boolean().default(!0)}),DZ=B.object({items:B.array(LZ).default([])}),jZ=B.enum(["linux","macos"]),C9=B.object({id:B.string().min(1),name:B.string().min(1),platform:jZ.nullable(),workers:B.object({total:B.number().int(),online:B.number().int(),busy:B.number().int(),idle:B.number().int()}),sessions:B.object({queued:B.number().int(),running:B.number().int()})}),zZ=B.object({machines:B.array(C9)}),OZ=B.object({machine:C9}),AZ=B.object({deleted:B.literal(!0),revoked_workers:B.number().int(),revoked_tokens:B.number().int()}),RZ=B.object({token:B.object({id:B.string().min(1),machine_id:B.string().min(1),token_prefix:B.string()}),secret:B.string().startsWith("rmt_")}),I9=B.looseObject({machine_id:B.string().min(1),machine_name:B.string().min(1)}),CZ=I9.extend({organization_id:B.string().min(1)}),fV=B.object({id:B.string().min(1),name:B.string().min(1),state:B.enum(["waiting","placed"]),queue_position:B.number().int().nullable()});var hV=B.union([B.object({kind:B.literal("cloud")}),B.object({kind:B.enum(["mac","headless"]),device_id:B.string().min(1),root_id:B.string().min(1)})]);function k1($,J,Z){let Q=$.safeParse(J);if(!Q.success)throw new G0(502,Z,"Reason returned an unexpected response.");return Q.data}var IZ=B.object({error:B.object({type:B.string(),message:B.string()})});function P9($,J,Z){let Q=IZ.safeParse(J),X=typeof J.error==="string"?J.error:Q.success?Q.data.error.type:`http_${$}`,Y=typeof J.detail==="string"?J.detail:typeof J.message==="string"?J.message:Q.success?Q.data.error.message:`Reason request failed (${$}${typeof J.error==="string"?` ${J.error}`:""})`,G=X==="github_connection_required"&&typeof J.connect_url==="string"&&/^https?:\/\//.test(J.connect_url)?` Connect it at ${J.connect_url}`:"",V=Z===null||Z.trim()===""?NaN:Number(Z);return new G0($,X,`${Y}${G}`,typeof J.suggested_model==="string"?J.suggested_model:void 0,Number.isFinite(V)&&V>=0?V*1000:void 0)}async function x9($){let J=await($.fetchImpl??fetch)(`${$.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${$.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify($.body),signal:AbortSignal.timeout(30000),redirect:"error"}),Z=await J.json().catch(()=>({}));if(!J.ok)throw P9(J.status,Z,J.headers.get("retry-after"));return k1(CZ,Z,"invalid_machine_ticket")}class N1{options;credentials;constructor($,J={}){this.options=J;this.credentials=$}trackEvent($,J={}){}async request($,J={},Z=!1){let Q=this.options.fetchImpl??fetch,X=await Q(`${this.credentials.apiOrigin}/v3${$}`,{method:J.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":"reason-cli","x-reason-agent":"Reason CLI",...J.body===void 0?{}:{"content-type":"application/json"},...J.headers},body:J.body===void 0?void 0:JSON.stringify(J.body),signal:J.signal,redirect:"error"}),Y=await X.json().catch(()=>({}));if(X.status===401&&!Z&&J.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let G=await b1({fetchImpl:Q,path:this.options.credentialsPath,forceRefresh:!0,signal:J.signal});if(G)return this.credentials=G,this.request($,J,!0)}if(!X.ok)throw P9(X.status,Y,X.headers.get("retry-after"));return Y}createHeadlessDeviceEnrollmentTicket($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:$,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice($){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:$,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(J){if(J instanceof G0&&(J.status===404||J.status===405||J.status===403&&J.code==="endpoint_not_available"))return null;throw J}}addDeviceRoot($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent($)}/roots`,{method:"POST",body:J,signal:AbortSignal.timeout(30000)})}removeDeviceRoot($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent($)}/roots/${encodeURIComponent(J)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath($,J=""){let Z=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return $===void 0?Z:`${Z}/${encodeURIComponent($)}${J}`}async listMachines(){return k1(zZ,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine($){let J=await this.request(this.machinePath(),{method:"POST",body:{name:$.name,...$.platform?{platform:$.platform}:{}}});return k1(OZ,J,"invalid_machine").machine}async deleteMachine($){let J=await this.request(this.machinePath($),{method:"DELETE"});return k1(AZ,J,"invalid_machine_deletion")}async createMachineToken($){let J=await this.request(this.machinePath($,"/tokens"),{method:"POST",body:{}});return k1(RZ,J,"invalid_machine_token")}async createMachineEnrollmentTicket($,J){let Z=await this.request(this.machinePath($,"/enrollment-tickets"),{method:"POST",body:J,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return k1(I9,Z,"invalid_machine_ticket")}self($){return this.request("/self",{signal:$})}claimExistingCliPairing($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:$}})}connectAnthropicProvider($,J,Z={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:Z.retryUnauthorized,signal:Z.signal,body:{access_token:$.access,refresh_token:$.refresh,expires_at:new Date($.expires).toISOString(),...J?{account_key:J}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((J)=>{let Z=typeof J.full_name==="string"?J.full_name:typeof J.repo_full_name==="string"?J.repo_full_name:null;if(!Z)return[];return[{repo_id:typeof J.repo_id==="string"?J.repo_id:void 0,full_name:Z,provider:J.provider==="gitlab"?"gitlab":"github",default_branch:typeof J.default_branch==="string"?J.default_branch:null,private:typeof J.private==="boolean"?J.private:void 0}]})}async listProjects(){let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),J=WZ.safeParse($);if(!J.success)throw new G0(502,"invalid_project_list","Reason returned an unexpected project list.");return J.data.items}async listSkills(){try{let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return k1(DZ,$,"invalid_skill_list").items}catch($){if($ instanceof G0&&($.status===403||$.status===404))return[];throw $}}async listDevices(){let $=[],J=null;for(let Z=0;Z<50;Z+=1){let Q=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${J?`?after=${encodeURIComponent(J)}`:""}`),X=_Z.safeParse(Q);if(!X.success)throw new G0(502,"invalid_device_list","Reason returned an unexpected machine list.");if($.push(...X.data.devices),J=X.data.has_next_page?X.data.end_cursor??null:null,!J)break}return $}async listModels(){try{let J=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((Q)=>Q.hidden!==!0&&Q.available!==!1).map(({reasoning_efforts:Q,hidden:X,available:Y,...G})=>({...G,...Array.isArray(Q)?{reasoning_efforts:MZ.filter((V)=>Q.includes(V))}:{}})),Z=new Set(J.map((Q)=>Q.detail));return J.length>1&&Z.size===1?J.map(({detail:Q,...X})=>X):J}catch($){if($ instanceof G0&&($.status===403||$.status===404))return[];throw $}}async getAgentVersion($){try{let J=await this.request("/deployment",{signal:$,retryUnauthorized:!1});return U9(J.reason_version)?J.reason_version:null}catch{return null}}async getUsageQuota(){try{let $=NZ.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!$.success)return null;let J;try{J=qZ(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...$.data,own_inference:J}}catch($){if($ instanceof G0&&($.status===403||$.status===404))return null;throw $}}async listSessions($=50,J,Z={}){let Q=new URLSearchParams({first:String(Math.min(Math.max($,1),200)),status:Z.status??"active"});if(J)Q.set("project_id",J);if(Z.origin)Q.set("origin",Z.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${Q.toString()}`)).items??[]}getSession($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}`)}async prestartSession($){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:$}});return J?.status==="starting"||J?.status==="ready"}async createSession($){let J=$.mode==="ephemeral"||$.workspaceOwnership==="externally-managed";if($.attachments?.length)await this.requireSessionAttachments();if(J||$.runtimeProfile){let X=await this.request("/deployment");if(J&&(!Array.isArray(X.session_modes)||!X.session_modes.includes($.mode??"standard")||!Array.isArray(X.workspace_ownerships)||!X.workspace_ownerships.includes($.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if($.runtimeProfile&&(!Array.isArray(X.experimental_runtime_profiles)||!X.experimental_runtime_profiles.includes($.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let Z=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:$.prompt,...$.attachments?.length?{attachments:$.attachments}:{},...$.mode?{mode:$.mode}:{},...$.workspaceOwnership?{workspace_ownership:$.workspaceOwnership}:{},...$.target?{target:$.target}:{},...$.repo?{repo:$.repo}:{},...$.provider?{provider:$.provider}:{},...$.model?{model:$.model}:{},...$.reasoningEffort?{reasoning_effort:$.reasoningEffort}:{},...$.runtimeProfile?{experimental_runtime_profile:$.runtimeProfile}:{},...$.ref?{ref:$.ref}:{},...$.completionMode?{completion_mode:$.completionMode}:{},...$.env&&Object.keys($.env).length>0?{env:$.env}:{},...$.clientSessionId?{client_session_id:$.clientSessionId}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),Q=await this.getSession(Z.session_id);if(J){let X=Q.session_policy,Y=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!X||X.version!==1||X.mode!==($.mode??"standard")||X.workspaceOwnership!==($.workspaceOwnership??"managed")||!X.components||Y.some((G)=>X.components[G]!==!0))throw await this.cancelSession(Z.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if($.runtimeProfile&&Q.experimental_runtime_profile!==$.runtimeProfile)throw await this.cancelSession(Z.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return Q}async getEvents($,J=-1,Z={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/events?after_seq=${J}&limit=500${Z.waitMs?`&wait_ms=${Z.waitMs}`:""}`,Z.signal?{signal:Z.signal}:{})}catch(Q){if(!(Q instanceof G0)||Q.status!==403&&Q.status!==404)throw Q;return{session:await this.getSession($),items:[],next_seq:J}}}async getMessages($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages?first=500${J===void 0?"":`&after_seq=${J}`}`)}async getAttachments($){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/attachments`)).items??[]}catch(J){if(J instanceof G0&&(J.status===403||J.status===404))return[];throw J}}async requireSessionAttachments(){let $=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if($.session_attachments!==!0){let J=typeof $.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test($.reason_version)?`Agent ${$.reason_version}`:null,Z=typeof $.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test($.commit_sha)?`server ${$.commit_sha.slice(0,12)}`:null,Q=[J,Z].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${Q?` (${Q})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage($,J,Z={}){if(Z.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages`,{method:"POST",body:{message:J,...Z.attachments?.length?{attachments:Z.attachments}:{},...Z.model?{model:Z.model}:{},...Z.reasoningEffort?{reasoning_effort:Z.reasoningEffort}:{},...Z.target?{target:Z.target}:{}}})}createSharedLink($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/shared-links`,{method:"POST",body:{url:J.url,...J.label?{label:J.label}:{},...J.expiresInSeconds!==void 0?{expires_in_seconds:J.expiresInSeconds}:{}}})}cancelSession($,J={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/cancel`,{method:"POST",body:J.mode==="hard"?{mode:"hard"}:{}})}}function y1($,J){let Z=b0($,"REASON_API_URL")?.trim();if(!Z)return j4(J);let Q=new URL(Z);if(Q.protocol!=="https:"&&!(Q.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(Q.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return Q.origin}function PZ($){return b0($,"REASON_API_URL")?.trim()?y1($,"production"):void 0}function z4($){return b0($,"REASON_API_KEY")?.trim()||void 0}async function E9($,J){let Z=$.env??process.env,Q=z4(Z);if(!Q)return($.getCredentials??b1)({apiOrigin:PZ(Z),signal:J});let X=y1(Z,$.channel??P0({env:Z})),Y=await($.fetchImpl??fetch)(X+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+Q,accept:"application/json"},signal:J}),G=await Y.json().catch(()=>({})),V=i0(G)?G:{};if(!Y.ok){let N=typeof V.detail==="string"?V.detail:typeof V.message==="string"?V.message:"API key authentication failed ("+Y.status+")";throw new G0(Y.status,typeof V.error==="string"?V.error:"api_key_auth_failed",N)}if(typeof V.org_id!=="string"||!V.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let K=Array.isArray(V.scopes)?V.scopes.filter((N)=>typeof N==="string"):[];return{credentialKind:"api_key",apiOrigin:X,accessToken:Q,orgId:V.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:K}}import{createHash as xZ}from"crypto";import{unlinkSync as EZ}from"fs";import{platform as SZ}from"os";import{join as wZ}from"path";var S9=B.discriminatedUnion("store",[B.strictObject({version:B.literal(1),store:B.literal("keychain")}),B.strictObject({version:B.literal(1),store:B.literal("file"),api_key:B.string().min(1).max(4096)})]),f1=($)=>wZ($,"api-key.json");function z1($){let J=xZ("sha256").update(`reason-connect-api-key
|
|
4
|
+
`,{mode:384,flag:"wx"}),M9(Q,384),_9($,"utf8")!==J)throw Error("credentials_changed");JZ(Q,$)}catch{try{F9(Q)}catch{}}}function D9($=e0()){if(!T9($))return!1;return F9($),!0}var j9=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var SV=j9.filter(($)=>$!=="network:read"&&$!=="network:write");class x$ extends Error{oauthCode;constructor($,J=null){super($);this.oauthCode=J;this.name="LoginError"}}function A9(){let $=z9(48).toString("base64url"),J=YZ("sha256").update($).digest("base64url");return{verifier:$,challenge:J,state:z9(32).toString("base64url")}}function BZ($,J){let Z=typeof $.error==="string"?$.error:null,Q=typeof $.error_description==="string"?$.error_description:Z?Z:J;return new x$(Q,Z)}async function KZ($,J,Z,Q){let X=await Z(`${$}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:J,signal:Q}),Y=await X.json().catch(()=>({}));if(!X.ok)throw BZ(Y,`OAuth token request failed (${X.status})`);return Y}var VZ=1e4;async function HZ($,J={}){let Z=J.fetchImpl??fetch,Q=await KZ($.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:$.clientId,refresh_token:$.refreshToken}),Z,AbortSignal.timeout(VZ)).catch((Y)=>{if(Y instanceof Error&&Y.name==="TimeoutError")throw new x$("Reason did not answer the login refresh in time. Check the network and retry.");throw Y});if(typeof Q.access_token!=="string"||typeof Q.refresh_token!=="string"||typeof Q.expires_in!=="number")throw new x$("Reason returned an incomplete refreshed login.");let X={...$,accessToken:Q.access_token,refreshToken:Q.refresh_token,expiresAt:new Date(Date.now()+Q.expires_in*1000).toISOString(),scopes:typeof Q.scope==="string"?Q.scope.split(/\s+/).filter(Boolean):$.scopes};return L9(X,J.path??e0()),X}var M2=new Map;function O9($,J){if(!J)return $;if(J.aborted)return Promise.reject(J.reason);return new Promise((Z,Q)=>{let X=()=>Q(J.reason);J.addEventListener("abort",X,{once:!0}),$.then(Z,Q).finally(()=>J.removeEventListener("abort",X))})}async function b1($={}){let J=$.path??e0(),Z=P$(J);if(!Z)return null;let Q=$.apiOrigin??b0(process.env,"REASON_API_URL")?.trim();if(Q&&!z0(Z.apiOrigin,new URL(Q).origin))return null;let X=Date.parse(Z.expiresAt)<=Date.now()+60000;if(!$.forceRefresh&&!X)return Z;let Y=[J,Z.apiOrigin,Z.clientId,Z.refreshToken].join("\x00"),G=M2.get(Y);if(G)return O9(G,$.signal);let V;return V=HZ(Z,{fetchImpl:$.fetchImpl,path:J}).catch(async(K)=>{if(!(K instanceof x$)||K.oauthCode!=="invalid_grant"&&K.oauthCode!=="invalid_client")throw K;let N=P$(J),q=K.oauthCode==="invalid_client"?N?.clientId!==Z.clientId:N?.refreshToken!==Z.refreshToken;if(N&&q)return b1({fetchImpl:$.fetchImpl,path:J});return D9(J),null}).finally(()=>{if(M2.get(Y)===V)M2.delete(Y)}),M2.set(Y,V),O9(V,$.signal)}function R9($,J){return new Promise((Z)=>{let Q=GZ({input:$}),X=!1,Y=(V)=>{if(X)return;X=!0,J.removeEventListener("abort",G),Q.close(),$.pause(),Z(V)},G=()=>Y(null);J.addEventListener("abort",G,{once:!0}),Q.once("line",(V)=>Y(V)),Q.once("close",()=>Y(null))})}var NZ=B.object({label:B.string(),used_percent:B.number().min(0).max(100).nullable(),resets_at:B.string().nullable(),exhausted:B.boolean().nullable()}),UZ=B.object({groups:B.array(B.object({selectable:B.boolean().optional(),accounts:B.array(B.object({source_id:B.string().min(1),model_ids:B.array(B.string().min(1)).optional()}))}))});function qZ($){let J=UZ.safeParse($);if(!J.success)return;return J.data.groups.some((Z)=>Z.selectable!==!1&&Z.accounts.some((Q)=>Q.model_ids===void 0||Q.model_ids.length>0))}class G0 extends Error{status;code;suggestedModel;retryAfterMs;constructor($,J,Z,Q,X){super(Z);this.status=$;this.code=J;this.suggestedModel=Q;this.retryAfterMs=X;this.name="ApiError"}static rateLimitDelayMs($,J){if(!($ instanceof G0)||$.status!==429)return null;return Math.min(60000,Math.max(J,$.retryAfterMs??0))}}var MZ=["minimal","low","medium","high","xhigh","max"],TZ=B.object({id:B.string().min(1),kind:B.string(),name:B.string(),custom_name:B.string().nullish(),status:B.string(),online:B.boolean(),compatible:B.boolean().optional(),compatibility_reason:B.string().nullish(),folder_lane_of:B.string().nullish(),roots:B.array(B.object({id:B.string().min(1),label:B.string()}))}),_Z=B.object({devices:B.array(TZ),end_cursor:B.string().nullish(),has_next_page:B.boolean().optional()}),FZ=B.object({id:B.string().min(1),name:B.string()}),WZ=B.object({items:B.array(FZ)}),LZ=B.object({skill_id:B.string().min(1),name:B.string(),description:B.string().nullish(),activation_keywords:B.array(B.string()).default([]),is_enabled:B.boolean().default(!0)}),DZ=B.object({items:B.array(LZ).default([])}),jZ=B.enum(["linux","macos"]),C9=B.object({id:B.string().min(1),name:B.string().min(1),platform:jZ.nullable(),workers:B.object({total:B.number().int(),online:B.number().int(),busy:B.number().int(),idle:B.number().int()}),sessions:B.object({queued:B.number().int(),running:B.number().int()})}),zZ=B.object({machines:B.array(C9)}),OZ=B.object({machine:C9}),AZ=B.object({deleted:B.literal(!0),revoked_workers:B.number().int(),revoked_tokens:B.number().int()}),RZ=B.object({token:B.object({id:B.string().min(1),machine_id:B.string().min(1),token_prefix:B.string()}),secret:B.string().startsWith("rmt_")}),I9=B.looseObject({machine_id:B.string().min(1),machine_name:B.string().min(1)}),CZ=I9.extend({organization_id:B.string().min(1)}),fV=B.object({id:B.string().min(1),name:B.string().min(1),state:B.enum(["waiting","placed"]),queue_position:B.number().int().nullable()});var hV=B.union([B.object({kind:B.literal("cloud")}),B.object({kind:B.enum(["mac","headless"]),device_id:B.string().min(1),root_id:B.string().min(1)})]);function k1($,J,Z){let Q=$.safeParse(J);if(!Q.success)throw new G0(502,Z,"Reason returned an unexpected response.");return Q.data}var IZ=B.object({error:B.object({type:B.string(),message:B.string()})});function P9($,J,Z){let Q=IZ.safeParse(J),X=typeof J.error==="string"?J.error:Q.success?Q.data.error.type:`http_${$}`,Y=typeof J.detail==="string"?J.detail:typeof J.message==="string"?J.message:Q.success?Q.data.error.message:`Reason request failed (${$}${typeof J.error==="string"?` ${J.error}`:""})`,G=X==="github_connection_required"&&typeof J.connect_url==="string"&&/^https?:\/\//.test(J.connect_url)?` Connect it at ${J.connect_url}`:"",V=Z===null||Z.trim()===""?NaN:Number(Z);return new G0($,X,`${Y}${G}`,typeof J.suggested_model==="string"?J.suggested_model:void 0,Number.isFinite(V)&&V>=0?V*1000:void 0)}async function x9($){let J=await($.fetchImpl??fetch)(`${$.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${$.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify($.body),signal:AbortSignal.timeout(30000),redirect:"error"}),Z=await J.json().catch(()=>({}));if(!J.ok)throw P9(J.status,Z,J.headers.get("retry-after"));return k1(CZ,Z,"invalid_machine_ticket")}class N1{options;credentials;constructor($,J={}){this.options=J;this.credentials=$}trackEvent($,J={}){}async request($,J={},Z=!1){let Q=this.options.fetchImpl??fetch,X=await Q(`${this.credentials.apiOrigin}/v3${$}`,{method:J.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":"reason-cli","x-reason-agent":"Reason CLI",...J.body===void 0?{}:{"content-type":"application/json"},...J.headers},body:J.body===void 0?void 0:JSON.stringify(J.body),signal:J.signal,redirect:"error"}),Y=await X.json().catch(()=>({}));if(X.status===401&&!Z&&J.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let G=await b1({fetchImpl:Q,path:this.options.credentialsPath,forceRefresh:!0,signal:J.signal});if(G)return this.credentials=G,this.request($,J,!0)}if(!X.ok)throw P9(X.status,Y,X.headers.get("retry-after"));return Y}createHeadlessDeviceEnrollmentTicket($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:$,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice($){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:$,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(J){if(J instanceof G0&&(J.status===404||J.status===405||J.status===403&&J.code==="endpoint_not_available"))return null;throw J}}addDeviceRoot($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent($)}/roots`,{method:"POST",body:J,signal:AbortSignal.timeout(30000)})}removeDeviceRoot($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent($)}/roots/${encodeURIComponent(J)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath($,J=""){let Z=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return $===void 0?Z:`${Z}/${encodeURIComponent($)}${J}`}async listMachines(){return k1(zZ,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine($){let J=await this.request(this.machinePath(),{method:"POST",body:{name:$.name,...$.platform?{platform:$.platform}:{}}});return k1(OZ,J,"invalid_machine").machine}async deleteMachine($){let J=await this.request(this.machinePath($),{method:"DELETE"});return k1(AZ,J,"invalid_machine_deletion")}async createMachineToken($){let J=await this.request(this.machinePath($,"/tokens"),{method:"POST",body:{}});return k1(RZ,J,"invalid_machine_token")}async createMachineEnrollmentTicket($,J){let Z=await this.request(this.machinePath($,"/enrollment-tickets"),{method:"POST",body:J,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return k1(I9,Z,"invalid_machine_ticket")}self($){return this.request("/self",{signal:$})}claimExistingCliPairing($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:$}})}connectAnthropicProvider($,J,Z={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:Z.retryUnauthorized,signal:Z.signal,body:{access_token:$.access,refresh_token:$.refresh,expires_at:new Date($.expires).toISOString(),...J?{account_key:J}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((J)=>{let Z=typeof J.full_name==="string"?J.full_name:typeof J.repo_full_name==="string"?J.repo_full_name:null;if(!Z)return[];return[{repo_id:typeof J.repo_id==="string"?J.repo_id:void 0,full_name:Z,provider:J.provider==="gitlab"?"gitlab":"github",default_branch:typeof J.default_branch==="string"?J.default_branch:null,private:typeof J.private==="boolean"?J.private:void 0}]})}async listProjects(){let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),J=WZ.safeParse($);if(!J.success)throw new G0(502,"invalid_project_list","Reason returned an unexpected project list.");return J.data.items}async listSkills(){try{let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return k1(DZ,$,"invalid_skill_list").items}catch($){if($ instanceof G0&&($.status===403||$.status===404))return[];throw $}}async listDevices(){let $=[],J=null;for(let Z=0;Z<50;Z+=1){let Q=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${J?`?after=${encodeURIComponent(J)}`:""}`),X=_Z.safeParse(Q);if(!X.success)throw new G0(502,"invalid_device_list","Reason returned an unexpected machine list.");if($.push(...X.data.devices),J=X.data.has_next_page?X.data.end_cursor??null:null,!J)break}return $}async listModels(){try{let J=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((Q)=>Q.hidden!==!0&&Q.available!==!1).map(({reasoning_efforts:Q,hidden:X,available:Y,...G})=>({...G,...Array.isArray(Q)?{reasoning_efforts:MZ.filter((V)=>Q.includes(V))}:{}})),Z=new Set(J.map((Q)=>Q.detail));return J.length>1&&Z.size===1?J.map(({detail:Q,...X})=>X):J}catch($){if($ instanceof G0&&($.status===403||$.status===404))return[];throw $}}async getAgentVersion($){try{let J=await this.request("/deployment",{signal:$,retryUnauthorized:!1});return U9(J.reason_version)?J.reason_version:null}catch{return null}}async getUsageQuota(){try{let $=NZ.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!$.success)return null;let J;try{J=qZ(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...$.data,own_inference:J}}catch($){if($ instanceof G0&&($.status===403||$.status===404))return null;throw $}}async listSessions($=50,J,Z={}){let Q=new URLSearchParams({first:String(Math.min(Math.max($,1),200)),status:Z.status??"active"});if(J)Q.set("project_id",J);if(Z.origin)Q.set("origin",Z.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${Q.toString()}`)).items??[]}getSession($,J){let Z=J?.fields.length?`?fields=${encodeURIComponent(J.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}${Z}`)}async prestartSession($){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:$}});return J?.status==="starting"||J?.status==="ready"}async createSession($){let J=$.mode==="ephemeral"||$.workspaceOwnership==="externally-managed";if($.attachments?.length)await this.requireSessionAttachments();if(J||$.runtimeProfile){let X=await this.request("/deployment");if(J&&(!Array.isArray(X.session_modes)||!X.session_modes.includes($.mode??"standard")||!Array.isArray(X.workspace_ownerships)||!X.workspace_ownerships.includes($.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if($.runtimeProfile&&(!Array.isArray(X.experimental_runtime_profiles)||!X.experimental_runtime_profiles.includes($.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let Z=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:$.prompt,...$.attachments?.length?{attachments:$.attachments}:{},...$.mode?{mode:$.mode}:{},...$.workspaceOwnership?{workspace_ownership:$.workspaceOwnership}:{},...$.target?{target:$.target}:{},...$.repo?{repo:$.repo}:{},...$.provider?{provider:$.provider}:{},...$.model?{model:$.model}:{},...$.reasoningEffort?{reasoning_effort:$.reasoningEffort}:{},...$.runtimeProfile?{experimental_runtime_profile:$.runtimeProfile}:{},...$.ref?{ref:$.ref}:{},...$.completionMode?{completion_mode:$.completionMode}:{},...$.env&&Object.keys($.env).length>0?{env:$.env}:{},...$.clientSessionId?{client_session_id:$.clientSessionId}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),Q=await this.getSession(Z.session_id);if(J){let X=Q.session_policy,Y=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!X||X.version!==1||X.mode!==($.mode??"standard")||X.workspaceOwnership!==($.workspaceOwnership??"managed")||!X.components||Y.some((G)=>X.components[G]!==!0))throw await this.cancelSession(Z.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if($.runtimeProfile&&Q.experimental_runtime_profile!==$.runtimeProfile)throw await this.cancelSession(Z.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return Q}async getEvents($,J=-1,Z={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/events?after_seq=${J}&limit=500${Z.waitMs?`&wait_ms=${Z.waitMs}`:""}`,Z.signal?{signal:Z.signal}:{})}catch(Q){if(!(Q instanceof G0)||Q.status!==403&&Q.status!==404)throw Q;return{session:await this.getSession($),items:[],next_seq:J}}}async getMessages($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages?first=500${J===void 0?"":`&after_seq=${J}`}`)}async getAttachments($){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/attachments`)).items??[]}catch(J){if(J instanceof G0&&(J.status===403||J.status===404))return[];throw J}}async requireSessionAttachments(){let $=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if($.session_attachments!==!0){let J=typeof $.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test($.reason_version)?`Agent ${$.reason_version}`:null,Z=typeof $.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test($.commit_sha)?`server ${$.commit_sha.slice(0,12)}`:null,Q=[J,Z].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${Q?` (${Q})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage($,J,Z={}){if(Z.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages`,{method:"POST",body:{message:J,...Z.attachments?.length?{attachments:Z.attachments}:{},...Z.model?{model:Z.model}:{},...Z.reasoningEffort?{reasoning_effort:Z.reasoningEffort}:{},...Z.target?{target:Z.target}:{}}})}createSharedLink($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/shared-links`,{method:"POST",body:{url:J.url,...J.label?{label:J.label}:{},...J.expiresInSeconds!==void 0?{expires_in_seconds:J.expiresInSeconds}:{}}})}cancelSession($,J={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/cancel`,{method:"POST",body:J.mode==="hard"?{mode:"hard"}:{}})}}function y1($,J){let Z=b0($,"REASON_API_URL")?.trim();if(!Z)return j4(J);let Q=new URL(Z);if(Q.protocol!=="https:"&&!(Q.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(Q.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return Q.origin}function PZ($){return b0($,"REASON_API_URL")?.trim()?y1($,"production"):void 0}function z4($){return b0($,"REASON_API_KEY")?.trim()||void 0}async function E9($,J){let Z=$.env??process.env,Q=z4(Z);if(!Q)return($.getCredentials??b1)({apiOrigin:PZ(Z),signal:J});let X=y1(Z,$.channel??P0({env:Z})),Y=await($.fetchImpl??fetch)(X+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+Q,accept:"application/json"},signal:J}),G=await Y.json().catch(()=>({})),V=i0(G)?G:{};if(!Y.ok){let N=typeof V.detail==="string"?V.detail:typeof V.message==="string"?V.message:"API key authentication failed ("+Y.status+")";throw new G0(Y.status,typeof V.error==="string"?V.error:"api_key_auth_failed",N)}if(typeof V.org_id!=="string"||!V.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let K=Array.isArray(V.scopes)?V.scopes.filter((N)=>typeof N==="string"):[];return{credentialKind:"api_key",apiOrigin:X,accessToken:Q,orgId:V.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:K}}import{createHash as xZ}from"crypto";import{unlinkSync as EZ}from"fs";import{platform as SZ}from"os";import{join as wZ}from"path";var S9=B.discriminatedUnion("store",[B.strictObject({version:B.literal(1),store:B.literal("keychain")}),B.strictObject({version:B.literal(1),store:B.literal("file"),api_key:B.string().min(1).max(4096)})]),f1=($)=>wZ($,"api-key.json");function z1($){let J=xZ("sha256").update(`reason-connect-api-key
|
|
5
5
|
${$}`).digest("hex");return new e1(T2(),SZ(),J)}function O4($,J,Z=z1($)){try{Z.deleteBinding(),Z.createBinding(new TextEncoder().encode(J)),c(f1($),{version:1,store:"keychain"});return}catch(Q){if(!(Q instanceof Y0))throw Q}c(f1($),{version:1,store:"file",api_key:J})}function l0($,J=z1($)){if(!u(f1($)))return null;let Z=S9.parse(JSON.parse(s(f1($))));if(Z.store==="file")return Z.api_key;try{let Q=J.loadBinding();return Q?new TextDecoder().decode(Q):null}catch(Q){if(!(Q instanceof Y0))throw Q;throw Error("worker_api_key_unreadable")}}function w9($,J=z1($)){if(!u(f1($)))return;if(S9.parse(JSON.parse(s(f1($)))).store==="keychain")try{J.deleteBinding()}catch(Z){if(!(Z instanceof Y0))throw Z}EZ(f1($))}async function A4($,J){let Z;try{Z=await E9({env:{REASON_API_KEY:J,REASON_API_URL:$.apiOrigin},fetchImpl:k0($.proxy)})}catch(Q){if(Q instanceof G0&&(Q.status===401||Q.status===403))throw Error("worker_api_key_rejected");throw Q}if(!Z)throw Error("worker_api_key_rejected");if(!Z.scopes.includes("devices:write"))throw Error("worker_api_key_devices_write_required");return Z}import{readdirSync as tZ,renameSync as oZ,rmSync as v1}from"fs";import{join as M0}from"path";import{createHash as bZ}from"crypto";import{realpathSync as kZ,statSync as yZ,unlinkSync as _2}from"fs";import{platform as fZ}from"os";import{join as y0}from"path";function d($){return{state:y0(g($),"device.json"),control:y0(g($),"control.json"),lock:y0(g($),"lifecycle.lock"),socket:y0(g($),"control.sock"),daemon:y0(g($),"daemon.json"),releaseCheck:y0(g($),"release-check.json"),updateDeferral:y0(g($),"update-deferral.json"),firstHeartbeat:y0(g($),"first-heartbeat.json")}}var hZ=B.object({version:B.literal(1),device_id:B.string().min(1).max(160),offer:B.unknown().optional(),enrollment_ms:B.number().int().nonnegative().max($$).optional()});function k9($,J,Z){e(g($),!0),c(d($).firstHeartbeat,{version:1,device_id:J,...Z.offer?{offer:Z.offer}:{},...Z.enrollmentMs!==void 0?{enrollment_ms:Z.enrollmentMs}:{}})}function C4($,J){let Z=d($).firstHeartbeat;try{if(!u(Z))return null;let Q=hZ.safeParse(JSON.parse(s(Z)));if(_2(Z),!Q.success||Q.data.device_id!==J)return null;let X=F2(Q.data.offer);return{...X?{offer:X}:{},...Q.data.enrollment_ms!==void 0?{enrollmentMs:Q.data.enrollment_ms}:{}}}catch{return null}}function T0($,J=!1){e(g($),J);let Z=["local-device.key","local-device.binding","device.json"].filter((Q)=>{let X=y0(g($),Q);if(!u(X))return!1;return s(X),!0});return $.lifetime==="persistent"&&Z.join()==="device.json"?I4($):new R4(g($))}function W2($,J){T0($,!0),gZ($);let Z=J??I4($),Q=new R4(g($));try{Z.deleteBinding(),Z.deleteKey(),Z.createFreshPublicKey()}catch(X){if(X instanceof Y0)return Q;throw X}return Q.deleteBinding(),Q.deleteKey(),Z}function I4($){return new e1(T2(),fZ(),mZ($))}function mZ($){let J=P4($);return bZ("sha256").update(`reason-worker
|
|
6
6
|
${J?.directory??g($)}`).digest("hex")}function S$($,J){c(y0(g($),w$),{version:1,directory:P4($)?.directory??g($),devicePublicKey:J})}var w$="keychain-scope.json";function y9($){return u(y0(g($),w$))}var vZ=B.strictObject({version:B.literal(1),directory:B.string().min(1),devicePublicKey:B.string().min(1)});function P4($){let J=y0(g($),w$);if(!u(J))return null;let Z=vZ.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 gZ($){let J=y0(g($),w$);if(!u(J))return;if(P4($))try{let Z=I4($);Z.deleteBinding(),Z.deleteKey()}catch(Z){if(!(Z instanceof Y0))throw Z}_2(J)}function U1($){let J=kZ($.workspaceRoot);if(J!==$.workspaceRoot||!yZ(J).isDirectory()||!E$(J,$.stateDirectory))throw Error("worker_workspace_not_canonical_or_overlaps_state")}function t($){if(!u(g($)))return null;let J=h1(d($).state,{proofStore:T0($),repair:!1}),Z=J!==null&&b9($.apiOrigin,J.apiOrigin),Q=Z?[U0($),U0({...$,apiOrigin:J.apiOrigin})]:[U0($)];if(J&&(!Q.includes(J.worker?.configDigest??"")||J.worker.lifetime!==$.lifetime||J.apiOrigin!==$.apiOrigin&&!Z||J.roots.length>32||J.roots[0]?.path!==$.workspaceRoot||J.handsSlots!==$.slots))throw Error("worker_config_binding_mismatch");return J}var f9=B.strictObject({version:B.literal(1),drained:B.boolean(),revoked:B.boolean()});function $0($){let J=d($).control;return u(J)?f9.parse(JSON.parse(s(J))):{version:1,drained:!1,revoked:!1}}function x0($,J){c(d($).control,f9.parse(J))}function f0($){let J=T0($);J.deleteBinding(),J.deleteKey();let Z=y0(g($),w$);if(u(Z))_2(Z);let Q=d($).state;if(u(Q))_2(Q)}var uZ=B.strictObject({read:B.boolean(),write:B.boolean(),execute:B.boolean(),discover_environment:B.boolean(),expose_mcp:B.literal(!1)}),x4=B.strictObject({version:B.literal(1),organization_id:B.string().min(1).max(160),enrollment_ticket:B.string().min(1).max(4096),code_verifier:B.string().regex(/^[A-Za-z0-9._~-]{43,128}$/),root_fingerprint_key:B.string().regex(/^[a-f0-9]{64}$/),root:B.strictObject({path_fingerprint:B.string().regex(/^[a-f0-9]{64}$/),permissions:uZ,execution_mode:B.enum(["confined","host"]).default("confined")}),folders:B.array(B.strictObject({path_fingerprint:B.string().regex(/^[a-f0-9]{64}$/)})).min(1).max(31).optional()}),dZ=B.object({device_id:B.string().min(1).max(160),organization_id:B.string().min(1).max(160),auth_scheme:B.literal("p256"),protocol_version:B.literal(2),roots:B.array(B.object({id:B.string().min(1),label:B.string(),path_fingerprint:B.string()})).min(1).max(32),headless:B.object({lifecycle:B.enum(["persistent","ephemeral"]),expires_at:B.iso.datetime({offset:!0})}),first_heartbeat:B.unknown().optional()}),E4=30000;class $1 extends Error{deviceRemoved;constructor($){super("worker_enrollment_rejected");this.deviceRemoved=$}}async function lZ($,J,Z=fetch){let Q=await Z(`${$}/app/local-runtime/enroll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J),redirect:"error",signal:AbortSignal.timeout(E4)});if(!Q.ok){let X=Q.status===409?await Q.json().catch(()=>null):null;throw new $1(X?.error==="device_revoked")}return Q.json()}async function S4($,J,Z,Q){u0();let X=x4.parse(JSON.parse(s(J)));return J1($,X,Z,Q)}async function J1($,J,Z,Q=(Y,G)=>lZ(Y,G,k0($.proxy)),X=performance.now()){let Y=m9($,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 h9($,J,Z,Q,X=performance.now()){let Y=m9($,J,Z),G=await Q(Y.request,J.code_verifier);return G===null?null:Y.receipt(G,X)}function m9($,J,Z){if(u0(),J.root.execution_mode!==$.executionMode)throw Error("worker_enrollment_mode_mismatch");let Q=m1([$.workspaceRoot],J.root.permissions,Buffer.from(J.root_fingerprint_key,"hex"))[0];if(Q.path!==$.workspaceRoot||Q.pathFingerprint!==J.root.path_fingerprint)throw Error("worker_enrollment_root_mismatch");let X=($.folders??[]).map((K,N)=>{let q=m1([K],J.root.permissions,Buffer.from(J.root_fingerprint_key,"hex"))[0];if(q.path!==K||q.pathFingerprint!==J.folders?.[N]?.path_fingerprint)throw Error("worker_enrollment_root_mismatch");return q});if((J.folders?.length??0)!==X.length)throw Error("worker_enrollment_root_mismatch");let Y=[{...Q,label:"workspace"},...X],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:r,bridge_version:r,protocol_version:2,capabilities:{supported_operations:[]},roots:Y.map((K)=>({label:K.label,path_fingerprint:K.pathFingerprint,permissions:J.root.permissions}))},receipt(K,N){let q=dZ.parse(K);if(q.organization_id!==J.organization_id||q.roots.length!==Y.length||q.roots.some((U,M)=>U.path_fingerprint!==Y[M].pathFingerprint)||q.headless.lifecycle!==$.lifetime||Date.parse(q.headless.expires_at)<=Date.now())throw Error("worker_enrollment_receipt_mismatch");let H=F2(q.first_heartbeat);try{k9($,q.device_id,{...H?{offer:H}:{},enrollmentMs:Math.min($$,Math.max(0,Math.round(performance.now()-N)))})}catch{}return{version:4,apiOrigin:$.apiOrigin,orgId:q.organization_id,deviceId:q.device_id,devicePublicKey:G,displayName:$.name,registeredAt:new Date().toISOString(),handsSlots:$.slots,worker:{configDigest:U0($),lifetime:$.lifetime,expiresAt:q.headless.expires_at},roots:q.roots.map((U,M)=>({id:U.id,label:U.label,path:Y[M].path,pathFingerprint:U.path_fingerprint,permissions:J.root.permissions}))}}}}import{randomBytes as pZ,randomUUID as cZ}from"crypto";import{unlinkSync as sZ}from"fs";import{join as aZ}from"path";var v9=B.strictObject({version:B.literal(1),install_id:B.uuid(),fingerprint_key:B.string().regex(/^[a-f0-9]{64}$/)}),iZ=B.object({enrollment_ticket:B.string().min(1).max(4096),expires_at:B.iso.datetime({offset:!0}),device_kind:B.literal("headless"),lifecycle:B.enum(["persistent","ephemeral"]),device_expires_at:B.iso.datetime({offset:!0})});function w4($){return iZ.parse($)}var nZ=B.object({credentialKind:B.enum(["oauth","api_key"]).optional(),apiOrigin:B.url(),clientId:B.string(),accessToken:B.string().min(1).max(32768),refreshToken:B.string().max(32768),expiresAt:B.iso.datetime({offset:!0}),scopes:B.array(B.string().max(128)).max(128),orgId:B.string().min(1).max(160)});function O1($){return e0(k$("REASON_CLI_CHANNEL",$.channel),V0())}async function A1($,J=O1($)){if(!u(J))return null;let Z=nZ.parse(JSON.parse(s(J)));if(!z0(Z.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(Z.credentialKind==="api_key")return Date.parse(Z.expiresAt)>Date.now()?Z:null;let Q=k0($.proxy),X=Object.assign((G,V)=>Q(G,{...V,redirect:"error",signal:AbortSignal.timeout(30000)}),{preconnect:fetch.preconnect}),Y=await b1({path:J,fetchImpl:X});if(Y&&!z0(Y.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");return Y}async function g9($,J,Z){if(!z0(J.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(!J.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let Q=R1($);return Q.complete(J.orgId,await Z.createHeadlessDeviceEnrollmentTicket(Q.request))}async function u9($,J,Z,Q,X){let Y=performance.now();if(!z0(J.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(!J.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let G=R1($),V=X?void 0:Z.enrollHeadlessDevice?.bind(Z);if(V){let K=await h9($,G.direct(J.orgId),Q,(N,q)=>V({approval:G.request,code_verifier:q,registration:N}).catch((H)=>{throw rZ(H)}),Y);if(K)return K}return J1($,G.complete(J.orgId,await Z.createHeadlessDeviceEnrollmentTicket(G.request)),Q,X,Y)}function rZ($){if(!($ instanceof G0))return $;if($.status===409)return new $1($.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 $1(!1);return $}var b$=($)=>aZ(g($),"enrollment-install.json");function d9($){if(u(b$($)))sZ(b$($))}function R1($,{stored:J=!0}={}){u0();let Z=b$($),Q=J&&u(Z)?v9.parse(JSON.parse(s(Z))):{version:1,install_id:cZ(),fingerprint_key:pZ(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=m1([$.workspaceRoot],X,Y)[0];if(G.path!==$.workspaceRoot)throw Error("worker_workspace_not_canonical_or_overlaps_state");let V=($.folders??[]).map((H)=>{let U=m1([H],X,Y)[0];if(U.path!==H)throw Error("worker_workspace_not_canonical_or_overlaps_state");return{path_fingerprint:U.pathFingerprint}}),K=A9(),N={install_id:Q.install_id,code_challenge:K.challenge,lifecycle:$.lifetime,roots:[G.pathFingerprint,...V.map((H)=>H.path_fingerprint)].map((H)=>({path_fingerprint:H,permissions:X,execution_mode:$.executionMode}))},q=(H)=>({version:1,organization_id:H,code_verifier:K.verifier,root_fingerprint_key:Q.fingerprint_key,root:{path_fingerprint:G.pathFingerprint,permissions:X,execution_mode:$.executionMode},...V.length?{folders:V}:{}});return{request:N,saveInstall(H){e(g(H),!0),c(b$(H),Q)},complete(H,U){let M=w4(U);if(M.lifecycle!==$.lifetime||Date.parse(M.expires_at)<=Date.now()||Date.parse(M.device_expires_at)<=Date.now())throw Error("worker_ticket_receipt_mismatch");return{...q(H),enrollment_ticket:M.enrollment_ticket}},direct:q}}function l9($,J,Z){let Q=b$($);if(!u(Q))throw Error("worker_folders_unavailable");let X=v9.parse(JSON.parse(s(Q)));return m1([J],Z,Buffer.from(X.fingerprint_key,"hex"))[0]}var L2=8,s9=600000,a9=15000,p9=new Set(["device_revoked","invalid_device_credential"]),D2=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,q1=($)=>M0(g($),"workspaces"),i9="account.json",b4=($)=>u(M0($,i9));function h0($){let J;try{J=tZ(q1($))}catch{return[]}return J.filter((Z)=>D2.test(Z)).sort().map((Z)=>{let Q=M0(q1($),Z),X=M0(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:b4(Q)}})}function j2($,J){let Z=J.toLowerCase();if(!D2.test(Z))throw Error("worker_workspace_id_invalid");let Q=J0.parse({...$,stateDirectory:M0(q1($),Z)});return e(Q.stateDirectory,!0),c(M0(Q.stateDirectory,i9),{version:1}),{config:Q,configPath:M0(Q.stateDirectory,"worker.json")}}function z2($,J){try{let{config:Z,configPath:Q}=j2($,J);e(g(Z),!0),x0(Z,{version:1,drained:!0,revoked:!0}),c(Q,Z)}catch{}}function f$($,J){let Z=J.toLowerCase(),Q=null;try{Q=t($)?.orgId.toLowerCase()??null}catch{}return Q===Z||h0($).some((X)=>!X.account&&X.config!==null&&X.organizationId===Z)}var k4=["device.json","local-device.key","local-device.binding","keychain-scope.json","control.json","enrollment-install.json","first-heartbeat.json"];function c9($,J){let Z=t($);if(!Z?.worker)throw Error("worker_identity_missing");S$($,Z.devicePublicKey),e(g(J),!0);for(let Y of k4)v1(M0(g(J),Y),{force:!0});for(let Y of k4){let G=M0(g($),Y);if(u(G))oZ(G,M0(g(J),Y))}let Q=T0(J),X=h1(d(J).state,{proofStore:Q,repair:!1});if(!X?.worker)throw Error("worker_identity_missing");m0({...X,worker:{...X.worker,configDigest:U0(J)}},d(J).state,{proofStore:Q})}function y4($){for(let J of h0($)){if(J.account)continue;try{if(J.config&&u(d(J.config).state))f0(J.config)}catch{}v1(J.directory,{recursive:!0,force:!0})}v1(h4($),{force:!0})}function O2($,{prefer:J,keep:Z,live:Q=!1}){let X=Date.now(),Y=(H)=>Number(Date.parse(H.worker?.expiresAt??"")>X+60000),V=h0($).flatMap((H)=>{if(!H.account||!H.config)return[];try{if($0(H.config).revoked)return[];let U=t(H.config);return U&&U.orgId.toLowerCase()===H.organizationId&&(!Q||Y(U))?[{...H,config:H.config,state:U}]:[]}catch{return[]}}).sort((H,U)=>Number(U.organizationId===J)-Number(H.organizationId===J)||Y(U.state)-Y(H.state))[0];if(!V)return null;let K=null;try{K=$0($).revoked?null:t($)}catch{}let N=K?.orgId.toLowerCase()??"";if(Z&&K&&D2.test(N)&&N!==V.organizationId){let H=j2($,N);c9($,H.config),c(H.configPath,H.config)}else if(u(g($))){try{if(u(d($).state))f0($)}catch{}for(let H of k4)v1(M0(g($),H),{force:!0})}y4($);let q=J0.parse({...V.config,stateDirectory:$.stateDirectory});return c9(V.config,q),c(M0($.stateDirectory,"worker.json"),q),v1(V.directory,{recursive:!0,force:!0}),q}var f4={before($){for(let{config:J}of h0($))try{let Z=J?t(J):null;if(J&&Z)S$(J,Z.devicePublicKey)}catch{}},after($,J){for(let{organizationId:Z,directory:Q,configPath:X,config:Y}of h0(J)){if(Y)continue;try{let G=J0.parse(JSON.parse(s(X)));if(G.stateDirectory!==M0(q1($),Z))continue;let V=J0.parse({...G,stateDirectory:Q}),K=T0(V),N=h1(d(V).state,{proofStore:K,repair:!1});if(N?.worker?.configDigest===U0(G))m0({...N,worker:{...N.worker,configDigest:U0(V)}},d(V).state,{proofStore:K});c(X,V)}catch{}}}},h4=($)=>M0(q1($),"listed.json");function n9($){try{let J=JSON.parse(s(h4($))),Z=J.names&&typeof J.names==="object"&&!Array.isArray(J.names)?Object.fromEntries(Object.entries(J.names).filter((Q)=>typeof Q[1]==="string")):{};return{listed:J.listed===!0,reason:J.reason==="sign_in"?"sign_in":null,blocked:Array.isArray(J.blocked)?J.blocked.filter((Q)=>typeof Q==="string"):[],names:Z}}catch{return null}}function r9($,J){let Z=h0($),Q=Z.filter((K)=>K.account),X=Z.filter((K)=>!K.account),Y=n9($),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:q})=>{let H=!1,U=null,M=!1;try{H=N?$0(N).revoked:!1,U=N&&!H?t(N):null,M=J&&!!U&&y$(d(N).daemon)?.state==="connected"}catch{}return{organization_id:K,device_id:U?.deviceId??null,name:Y?.names?.[K]??null,root:U?.roots[0]?{id:U.roots[0].id,permissions:U.roots[0].permissions}:null,state:H?"removed":M?"connected":"not_running",blocked:!q&&!H&&!M&&(Y?.blocked.includes(K)??!1),...q?{account:!0}:{}}})}}function t9($){let{config:J,state:Z,client:Q,signal:X}=$,Y=$.log??(()=>{return}),G=new Map,V=null,K=!1,N=n9(J)??{listed:!1,reason:null,blocked:[]},q=(W)=>{let{folders:L,...R}=J,x=Z.roots.slice(1).map((C)=>C.path);return J0.parse({...R,...x.length?{folders:x}:{},stateDirectory:M0(q1(J),W)})},H=async(W)=>{let L=G.get(W);if(!L)return;L.controller.abort(),await L.done},U=(W,L=!1)=>{let R=new AbortController,x=()=>R.abort();if(X.addEventListener("abort",x,{once:!0}),X.aborted)R.abort();let C={...W,controller:R,claims:0,done:Promise.resolve(),account:L};C.done=$.serve(W,R.signal,(I)=>{C.claims=I}).then(()=>{return},(I)=>{if(L&&I instanceof _0&&I.status===401&&p9.has(I.code)){try{x0(W.config,{version:1,drained:!0,revoked:!0})}catch{}Y(`Reason worker: workspace ${W.organizationId} (another account's) no longer accepts this computer (${I.code}); run \`reason connect\` signed in as that account to connect it again
|
|
7
7
|
`)}else if(I instanceof _0&&I.status===401&&p9.has(I.code)){try{f0(W.config)}catch{}Y(`Reason worker: workspace ${W.organizationId} no longer accepts this computer
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Bh as $}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Bh as $}from"./vm-hands-entry-lite-x3ytsxjm.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 xh,Z as yh,S as zh,k as Ah};
|
|
@@ -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.295",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 Bh};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ef as Z8}from"./vm-hands-entry-lite-zmf3vn3w.js";import{nf as R0}from"./vm-hands-entry-lite-mysjgrwy.js";import{ig as Kq}from"./vm-hands-entry-lite-
|
|
2
|
+
import{ef as Z8}from"./vm-hands-entry-lite-zmf3vn3w.js";import{nf as R0}from"./vm-hands-entry-lite-mysjgrwy.js";import{ig as Kq}from"./vm-hands-entry-lite-32d3ydnw.js";import{Eg as p,Hg as V0,Kg as F0,Lg as C8,Mg as eq,Og as g8,Rg as q0,Tg as x0}from"./vm-hands-entry-lite-yadv8a82.js";import{Yg as wq}from"./vm-hands-entry-lite-cfjx91rj.js";import{Zg as o,_g as C0}from"./vm-hands-entry-lite-pr65ksfz.js";import{lh as B0}from"./vm-hands-entry-lite-ngvxyjhy.js";import{Ch as A0}from"./vm-hands-entry-lite-d94sv87n.js";import{Jh as Z}from"./vm-hands-entry-lite-sn3vjjgx.js";import{execFile as V1,spawn as w0}from"child_process";import{randomBytes as F1}from"crypto";import{chmodSync as w1,existsSync as K0,lstatSync as K1,mkdirSync as M1,readFileSync as z1,rmSync as Y1,writeFileSync as Xq}from"fs";import{connect as _1}from"net";import{join as H}from"path";var Bq="./desktop-wallpaper-0pjhgyfk.jpg";var Rq="./dock-browser-afp005mt.png";var Cq="./dock-files-rywdm96b.png";var yq="./dock-terminal-s41cj1jp.png";var Sq=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
|
|
3
3
|
# The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
|
|
4
4
|
# python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
|
|
5
5
|
# Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
|