@reason-machines/cli-linux-arm64-musl 0.2.295 → 0.2.296
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-6j1pxtm6.js +2 -0
- package/bin/vm-hands/{custom-endpoint-device-tv4wtdb2.js → custom-endpoint-device-p2bvtf6p.js} +1 -1
- package/bin/vm-hands/desktop-account-axaenf68.js +2 -0
- package/bin/vm-hands/{device-workspace-s5z0zr53.js → device-workspace-ecq3hfd6.js} +1 -1
- package/bin/vm-hands/{hands-worker-source-emf3gv2b.js → hands-worker-source-w477y8ad.js} +1 -1
- package/bin/vm-hands/{index-bwnyk312.js → index-nxzv9qe7.js} +1 -1
- package/bin/vm-hands/local-automation-1b5pgjmh.js +2 -0
- package/bin/vm-hands/local-capabilities-j9aa1shb.js +2 -0
- package/bin/vm-hands/local-desktop-users-4756c92y.js +2 -0
- package/bin/vm-hands/local-display-mac-3zz66vzn.js +2 -0
- package/bin/vm-hands/local-display-session-f033e7en.js +2 -0
- package/bin/vm-hands/{network-contract-y6kbgyhe.js → network-contract-ggqak7gp.js} +1 -1
- package/bin/vm-hands/package-s6y0j1as.js +2 -0
- package/bin/vm-hands/permissions-7fw8kh54.js +2 -0
- package/bin/vm-hands/reason-hands-protocol-as5477xr.js +2 -0
- package/bin/vm-hands/{status-4cjfsvqj.js → status-g3jav4j0.js} +2 -2
- package/bin/vm-hands/version-92d8018j.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-qdwm3ya8.js → vm-hands-entry-lite-0ergg2ky.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-tkpfs08y.js → vm-hands-entry-lite-21qkhpm0.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-tm7mv31d.js → vm-hands-entry-lite-3s3jsrmq.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ggkqyxmp.js → vm-hands-entry-lite-425yvj0s.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-tf9322ea.js → vm-hands-entry-lite-5js1vtfd.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-yadv8a82.js → vm-hands-entry-lite-6j2yaa4n.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-32d3ydnw.js → vm-hands-entry-lite-7gfb36ez.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-cfjx91rj.js → vm-hands-entry-lite-7k65s010.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-qz9mkksp.js → vm-hands-entry-lite-7vscxzd1.js} +23 -23
- package/bin/vm-hands/{vm-hands-entry-lite-5zzey257.js → vm-hands-entry-lite-8st97h7b.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-yvftswfy.js → vm-hands-entry-lite-987hd3pc.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-zeay5yc9.js → vm-hands-entry-lite-9ez4yads.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-x3ytsxjm.js → vm-hands-entry-lite-aswtt2b5.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-250sqsry.js → vm-hands-entry-lite-bswnp5ve.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-pr65ksfz.js → vm-hands-entry-lite-em388nee.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-a3n86qqm.js → vm-hands-entry-lite-hf0mk7vd.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-zmf3vn3w.js → vm-hands-entry-lite-pf1ft65e.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-q2pb31vh.js +4 -0
- package/bin/vm-hands/{vm-hands-entry-lite-h7ndfgwc.js → vm-hands-entry-lite-q6fshf3h.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-5rbj89cs.js → vm-hands-entry-lite-rrk5g62b.js} +67 -22
- package/bin/vm-hands/{vm-hands-entry-lite-d94sv87n.js → vm-hands-entry-lite-wgx7z7gt.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-sn3vjjgx.js → vm-hands-entry-lite-xsq25kmd.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-mk9p22xa.js → vm-hands-entry-lite-ya1a2eep.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-ngvxyjhy.js → vm-hands-entry-lite-yp315y25.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-z7twr5ec.js → vm-hands-entry-lite-z662b8yj.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-w3k6wwx4.js → vm-hands-executor-5vqhd6bn.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-34mh58h8.js → vm-hands-op-runner-1n9sw4m8.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-ws1x5fg0.js → vm-hands-runtime-0jf6d2gd.js} +3 -3
- package/bin/vm-hands/worker-sandbox-snmfpfax.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/connect-cli-pwvhzdn1.js +0 -2
- package/bin/vm-hands/desktop-account-vr5beh82.js +0 -2
- package/bin/vm-hands/local-automation-jg8850x7.js +0 -2
- package/bin/vm-hands/local-capabilities-vr1j2605.js +0 -2
- package/bin/vm-hands/local-desktop-users-vztj8kn8.js +0 -2
- package/bin/vm-hands/local-display-mac-4mtwfgty.js +0 -2
- package/bin/vm-hands/local-display-session-9tbyrsqk.js +0 -2
- package/bin/vm-hands/package-q8gdr1z1.js +0 -2
- package/bin/vm-hands/permissions-5bmhsbwr.js +0 -2
- package/bin/vm-hands/reason-hands-protocol-5wqth9ga.js +0 -2
- package/bin/vm-hands/version-eyf47yc7.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-mysjgrwy.js +0 -4
- package/bin/vm-hands/worker-sandbox-wqxffxa1.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ae as W}from"./vm-hands-entry-lite-
|
|
2
|
+
import{ae as W}from"./vm-hands-entry-lite-q6fshf3h.js";var T=W.string().max(201).regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/).refine((Q)=>Q.split("/").every((Z)=>Z!=="."&&Z!=="..")),G=W.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_./-]*$/).refine((Q)=>!Q.includes("..")&&!Q.includes("//")&&!Q.endsWith("/")&&!Q.endsWith(".lock")),g=W.string().regex(/^[a-f0-9]{40}$/),N=W.number().int().positive(),C=W.string().min(1).max(256),A=W.string().max(60000),q={version:W.literal(1),repoFullName:T},c=W.discriminatedUnion("action",[W.strictObject({action:W.literal("edit"),title:C.optional(),body:A.optional(),base:G.optional()}),W.strictObject({action:W.enum(["ready","draft","close"])}),W.strictObject({action:W.literal("metadata"),field:W.enum(["reviewer","assignee","label"]),change:W.enum(["add","remove"]),value:W.string().min(1).max(100).refine((Q)=>!/[\r\n\0]/.test(Q))})]),l=W.discriminatedUnion("kind",[W.strictObject({...q,kind:W.literal("read"),path:W.string().min(1).max(2048),accept:W.enum(["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"]).optional()}),W.strictObject({...q,kind:W.literal("pr_review_context"),number:N,after:W.string().min(1).max(1024).optional()}),W.strictObject({...q,kind:W.literal("prepare"),branch:G,baseSha:g,defaultBranch:G}),W.strictObject({...q,kind:W.literal("publish"),branch:G,defaultBranch:G,baseSha:g,remoteHeadSha:g.nullable()}),W.strictObject({...q,kind:W.literal("pr_create"),head:G,base:G,title:C,body:A,draft:W.boolean()}),W.strictObject({...q,kind:W.literal("pr_mutation"),number:N,mutation:c}),W.strictObject({...q,kind:W.literal("pr_merge"),number:N,expectedHeadSha:g,expectedBaseRef:G,method:W.enum(["merge","squash","rebase"])})]),I=245760,u=W.discriminatedUnion("kind",[W.strictObject({kind:W.literal("pr_review_context"),body:W.string().max(I)}),W.strictObject({kind:W.literal("prepare"),headSha:g}),W.strictObject({kind:W.literal("read"),status:W.number().int().min(200).max(599),headers:W.record(W.string(),W.string().max(8192)).refine((Q)=>Object.keys(Q).every((Z)=>Z==="link"||Z==="content-type")),body:W.string().max(I)}),W.strictObject({kind:W.literal("publish"),headSha:g,scannedObjectCount:W.number().int().min(0).max(5000)}),W.strictObject({kind:W.literal("pr_create"),url:W.string().max(1024).regex(/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/)}),W.strictObject({kind:W.literal("pr_mutation"),number:N,applied:W.literal(!0)}),W.strictObject({kind:W.literal("pr_merge"),number:N,merged:W.literal(!0)})]).refine((Q)=>new TextEncoder().encode(JSON.stringify(Q)).byteLength<=I,"local_device_gh_result_too_large"),y=W.strictObject({source:W.enum(["agent","human"]),operationId:W.uuid()}),j=W.strictObject({version:W.literal(1),userId:W.guid(),deviceId:W.guid(),rootId:W.guid(),runId:W.guid(),merge:y.optional(),repoFullName:T.nullable(),rootRevision:W.string().regex(/^[1-9][0-9]*$/),readOnly:W.boolean(),generation:W.number().int().positive().nullable(),fenceId:W.guid().nullable()}).refine((Q)=>Q.generation===null===(Q.fenceId===null));function P(Q){return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(Q)&&Q.split("/").every((Z)=>Z!=="."&&Z!=="..")}function a(Q,Z,$={},H="read"){if(P(Q)&&(Z==="/search/issues"||Z.startsWith("/search/issues?")))return d(Q,Z,$);if(!P(Q)||!Z.startsWith(`/repos/${Q}/`)&&Z!==`/repos/${Q}`)throw Error("local_device_gh_repository_mismatch");if(/[\\#\u0000-\u001f]/.test(Z)||/%(?:2e|5c|00)/i.test(Z))throw Error("local_device_gh_path_denied");let V=new URL(Z,"https://api.github.com");if(V.pathname!==Z.split("?")[0]||V.username||V.password)throw Error("local_device_gh_path_denied");let Y;try{Y=decodeURIComponent(V.pathname.slice(`/repos/${Q}`.length))}catch{throw Error("local_device_gh_path_denied")}if(Y.includes("%")||Y.split("/").some((K)=>K==="."||K===".."))throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");if(![/^$/,/^\/commits$/,/^\/pulls$/,/^\/pulls\/[1-9][0-9]*(?:\/(?:commits|files|reviews|comments))?$/,/^\/issues\/[1-9][0-9]*(?:\/comments)?$/,/^\/issues\/comments\/[1-9][0-9]*\/reactions$/,/^\/commits\/[A-Za-z0-9_./-]+(?:\/(?:check-runs|status))?$/,/^\/check-runs\/[1-9][0-9]*(?:\/annotations)?$/,/^\/branches\/[A-Za-z0-9_./-]+$/,/^\/git\/ref\/heads\/[A-Za-z0-9_./-]+$/,/^\/compare\/[A-Za-z0-9_./-]+\.\.\.[A-Za-z0-9_./-]+$/].some((K)=>K.test(Y)))throw Error("local_device_gh_path_denied");if(V.searchParams.forEach((K,B)=>{if(B==="per_page"&&/^[1-9][0-9]*$/.test(K)&&Number(K)<=100)return;if(B==="page"&&/^[1-9][0-9]*$/.test(K)&&Number(K)<=100)return;if(Y==="/pulls"&&B==="state"&&["open","closed","all"].includes(K))return;if(Y==="/pulls"&&B==="sort"&&K==="updated")return;if(Y==="/pulls"&&B==="direction"&&K==="desc")return;if(Y==="/pulls"&&["head","base"].includes(B)&&/^[A-Za-z0-9_./:-]{1,255}$/.test(K))return;throw Error("local_device_gh_query_denied")}),$.headers)new Headers($.headers).forEach((B,b)=>{if(b!=="accept"||!["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"].includes(B))throw Error("local_device_gh_header_denied")})}function d(Q,Z,$){if(/[\\#\u0000-\u001f]/.test(Z))throw Error("local_device_gh_path_denied");let H=new URL(Z,"https://api.github.com");if(H.pathname!=="/search/issues"||H.username||H.password)throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");let V=null;H.searchParams.forEach((X,K)=>{if(K==="q"&&V===null){V=X;return}if(K==="per_page"&&/^[1-9][0-9]*$/.test(X)&&Number(X)<=100)return;if(K==="page"&&/^[1-9][0-9]*$/.test(X)&&Number(X)<=100)return;throw Error("local_device_gh_query_denied")});let Y=`repo:${Q.toLowerCase()} `,U=V?.toLowerCase()??"";if(U.length>512||!(U+" ").startsWith(Y)||/(?:^|\s)(?:repo|org|user):/.test(U.slice(Y.length)))throw Error("local_device_gh_query_denied");if($.headers)new Headers($.headers).forEach((X,K)=>{if(K!=="accept"||X!=="application/vnd.github+json")throw Error("local_device_gh_header_denied")})}var e=`query PullRequestReviewContext($owner: String!, $repo: String!, $number: Int!, $after: String) {
|
|
3
3
|
repository(owner: $owner, name: $repo) {
|
|
4
4
|
nameWithOwner
|
|
5
5
|
pullRequest(number: $number) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ef as Z8}from"./vm-hands-entry-lite-
|
|
2
|
+
import{ef as Z8}from"./vm-hands-entry-lite-pf1ft65e.js";import{nf as R0}from"./vm-hands-entry-lite-q2pb31vh.js";import{jg as Kq}from"./vm-hands-entry-lite-7gfb36ez.js";import{Fg as p,Ig as V0,Lg as F0,Mg as C8,Ng as eq,Pg as g8,Sg as q0,Ug as x0}from"./vm-hands-entry-lite-6j2yaa4n.js";import{Zg as wq}from"./vm-hands-entry-lite-7k65s010.js";import{$g as C0,_g as o}from"./vm-hands-entry-lite-em388nee.js";import{mh as B0}from"./vm-hands-entry-lite-yp315y25.js";import{Dh as A0}from"./vm-hands-entry-lite-wgx7z7gt.js";import{Kh as Z}from"./vm-hands-entry-lite-xsq25kmd.js";import{execFile as V1,spawn as w0}from"child_process";import{randomBytes as F1}from"crypto";import{chmodSync as w1,existsSync as K0,lstatSync as K1,mkdirSync as M1,readFileSync as z1,rmSync as Y1,writeFileSync as Xq}from"fs";import{connect as _1}from"net";import{join as H}from"path";var Bq="./desktop-wallpaper-0pjhgyfk.jpg";var Rq="./dock-browser-afp005mt.png";var Cq="./dock-files-rywdm96b.png";var yq="./dock-terminal-s41cj1jp.png";var Sq=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
|
|
3
3
|
# The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
|
|
4
4
|
# python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
|
|
5
5
|
# Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$a as n6,Ea as u6,Ga as w4,Ha as O4,Ma as l6,Na as s6,Xa as I4,ab as r6,bb as S4,cb as k4,eb as a6,ga as U4,gb as B8,hb as y0,ia as W2,ib as m0,ja as X4,jb as c1,ka as W4,la as Y4,ma as S6,mb as i6,na as f6,oa as M4,pa as b6,pb as V8,qa as A3,qb as A4,ra as x6,sa as y6,sb as o6,ta as h6,ua as m6,va as L4,wa as v6,xa as p6}from"./vm-hands-entry-lite-qz9mkksp.js";import{Ab as n0,Bb as r0,Ib as P0,tb as i3,ub as q6,vb as E6}from"./vm-hands-entry-lite-5rbj89cs.js";import{Jb as t6,Mb as e6,Ob as $7,Pb as J7}from"./vm-hands-entry-lite-mk9p22xa.js";import{Ub as d6}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Vb as _6,Wb as R6,Xb as P6,Yb as z6,Zb as L0}from"./vm-hands-entry-lite-n07kxrd1.js";import{$b as o1,ac as t1,bc as S3,dc as k3,fc as f3,gc as b3,kc as x3}from"./vm-hands-entry-lite-qdwm3ya8.js";import{Bc as r1,Ec as H7,Nc as D7}from"./vm-hands-entry-lite-ggkqyxmp.js";import{$c as d,$d as g8,Ad as w6,Cd as O6,Dd as j6,Ed as I6,Fd as A6,Gd as T6,Ld as D8,Md as M8,Nd as L8,Oc as L1,Od as w8,Pc as Q2,Pd as O8,Qc as e5,Qd as j8,Rc as I3,Sc as r3,Sd as I8,Tc as a3,Td as A8,Uc as M0,Ud as T8,Vd as _8,Wd as R8,Xd as P8,Yc as N0,Yd as z8,Zd as q8,_d as E8,ad as E1,dd as H8,fd as g1,hd as $6,id as J6,jd as Z6,kd as Q6,ld as K6,md as B6,nd as V6,od as G6,pd as U6,qd as X6,rd as W6,sd as Y6,td as F6,ud as N6,vd as C6,wd as H6,xd as D6,yd as M6,zd as L6}from"./vm-hands-entry-lite-5zzey257.js";import{ae as V}from"./vm-hands-entry-lite-h7ndfgwc.js";import{Ae as l1,be as W7,ce as Y7,de as F7,ee as N7,fe as C7,le as p5,pe as Q5,qe as T5,we as M7,ze as K5}from"./vm-hands-entry-lite-yvftswfy.js";import{Ze as j4,ef as c6}from"./vm-hands-entry-lite-zmf3vn3w.js";import{jf as M3,wf as g6}from"./vm-hands-entry-lite-mysjgrwy.js";import{Ag as Z7,Bg as Q7,Cg as K7,Dg as B7,Fg as V7,Gg as G7,Ig as U7,Jg as X7}from"./vm-hands-entry-lite-yadv8a82.js";import{Xg as n1}from"./vm-hands-entry-lite-cfjx91rj.js";import{$g as H4,Zg as j1,_g as k6,ah as D4}from"./vm-hands-entry-lite-pr65ksfz.js";import{ch as D3,eh as $1,kh as K8,lh as J4}from"./vm-hands-entry-lite-ngvxyjhy.js";import{Jh as H}from"./vm-hands-entry-lite-sn3vjjgx.js";import{Nh as a4}from"./vm-hands-entry-lite-a3n86qqm.js";import{request as m7}from"http";import{request as v7}from"https";async function p7($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?v7:m7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:k3},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Error("custom_endpoint_timeout"))),K.end($.body)})}function u7($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function d7($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=K[U-1];if(Z[G]===Z[U])U++;K[G]=U}let B=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+B),Y=0;for(let X of G){while(B&&Z[B]!==X){let F=K[B-1];Y+=Z.copy(W,Y,0,B-F),B=F}if(Z[B]===X){if(B++,B===Z.length)Y+=Q.copy(W,Y),B=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,B),B=0;return W.subarray(0,Y)}}async function y3($){$.signal.throwIfAborted();let J=b3.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=x3.parse(await $.credential($.signal));if(!f3(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new H("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let K,B,G=0,U=0,W=0,Y=u7(Q.apiKey),X=d7(Q.apiKey,Y),F=async(N,D)=>{$.signal.throwIfAborted(),await new Promise((w,M)=>{let I=()=>{$.signal.removeEventListener("abort",I),M($.signal.reason)};if($.signal.addEventListener("abort",I,{once:!0}),$.signal.aborted){I();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,D)}).then(()=>{$.signal.removeEventListener("abort",I),w()},(O)=>{$.signal.removeEventListener("abort",I),M(O)})})},C=async(N)=>{if(G+=N.length,G>t1)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<N.length;D+=o1){if(W>=S3)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await F(`custom_endpoint.chunk.${W++}`,{eof:!1,data:N.subarray(D,D+o1).toString("base64")})}};try{let N=await p7({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=N.response,B=N.close;let D=K.statusCode??500;if(D>=300&&D<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let w={};for(let M of["content-type","retry-after","x-request-id","request-id"]){let I=K.headers[M];if(typeof I==="string")w[M]=I.replaceAll(Q.apiKey,Y).slice(0,4096)}await F("custom_endpoint.headers",{status:D,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:w});for await(let M of K){$.signal.throwIfAborted();let I=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=I.length,U>t1)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await C(X(I))}return await C(X(Buffer.alloc(0),!0)),await F(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(N){if($.signal.throwIfAborted(),N instanceof H)throw N;throw new H("custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as h3}from"path";function l7($,J){return $===h3(J,".ara","workspace")||$===h3(J,".reason","workspace")}function m3($,J){let Z=$.filter((Q)=>l7(Q.path,J));return Z.length===1?Z[0].path:null}var s7=/^[a-f0-9]{64}$/;var e1=32,c7=/^\/[^\x00-\x1f\x7f\\]*$/;function H1($){if(typeof $!=="string"||$.length>4096||!c7.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function D1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!H1(J.home)||!Array.isArray(J.roots)||J.roots.length>e1)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:K,path:B}=Q;if(typeof K!=="string"||!s7.test(K)||!H1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}import{spawn as r7}from"child_process";import*as z from"fs";import*as s from"path";import{homedir as a7}from"os";function $2($,J,Z,Q="gh"){if(!["gh","git"].includes(Q))throw Error("local_device_gh_unavailable");let K=$.realpathSync(Z),B=Q==="git"&&process.platform==="darwin"?"/Library/Developer/CommandLineTools/usr/bin/git":"/usr/bin/"+Q;for(let G of["/opt/homebrew/bin/"+Q,"/usr/local/bin/"+Q,B])try{let U=$.realpathSync(G);if(U===K||U.startsWith(K+J.sep)||!["/opt/homebrew/","/usr/local/","/usr/bin/",...Q==="git"?["/Library/Developer/CommandLineTools/"]:[]].some((Y)=>U.startsWith(Y)))continue;let W=$.statSync(U);if(!W.isFile()||(W.mode&18)!==0||![0,process.getuid()].includes(W.uid))continue;return $.accessSync(U,$.constants.X_OK),U}catch{continue}throw Error("local_device_gh_unavailable")}function v3($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var p3=[{name:"private_key",regex:/-----BEGIN\s+(?:[A-Z0-9_-]+\s+)?PRIVATE\s+KEY-----/i},{name:"github_pat",regex:/\bgh[pousr]_[A-Za-z0-9_]{36,}\b/},{name:"github_fine_grained_pat",regex:/\bgithub_pat_[A-Za-z0-9_]{36,}\b/},{name:"gitlab_pat",regex:/\bglpat-[0-9a-zA-Z_-]{20,}\b/},{name:"slack_token",regex:/\bxox[baprs]-[0-9]{10,}-[0-9]{10,}-[0-9a-zA-Z]{24}\b/},{name:"stripe_live_key",regex:/\b[sr]k_live_[0-9a-zA-Z]{24,}\b/},{name:"bearer_jwt",regex:/\bBearer\s+ey[A-Za-z0-9_-]{20,}\.ey[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/}];function J2($){let J=$.trim().replaceAll("\\","/");if(!J)return{valid:!1,reason:"empty_path"};if(J.startsWith("/"))return{valid:!1,reason:"absolute_path_forbidden"};if(J.split("/").includes("..")||J.includes("../")||J.endsWith("/.."))return{valid:!1,reason:"path_traversal_forbidden"};if(J===".git"||J.startsWith(".git/")||J.includes("/.git/"))return{valid:!1,reason:"git_directory_entry_forbidden"};return{valid:!0}}function u3($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function d3($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function M1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=u3(J).filter((G)=>!K.has(G));for(let G of $){let U=J2(G.path);if(!U.valid){Q.push({path:G.path,reason:U.reason??"invalid_path"});continue}let W=G.content??"",Y=B.map((X)=>({secret:X,offset:W.indexOf(X)})).filter((X)=>X.offset>=0).sort((X,F)=>X.offset-F.offset);if(Y.length>0){let X=[...new Set(Y.flatMap((F)=>Z.secretNames?.(F.secret)??[]))];Q.push({path:G.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:v3(W,Y[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of p3){let F=d3(X,W).find((C)=>!K.has(C[0]));if(F){Q.push({path:G.path,reason:`credential_pattern_detected: ${X.name}`,pattern:X.name,ruleId:X.name,line:v3(W,F.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function l3($,J=[]){let Z=u3(J),Q=new Set;for(let{content:K}of $){for(let B of Z)if(K.includes(B))Q.add(B);for(let B of p3)for(let G of d3(B,K))Q.add(G[0])}return[...Q]}function n7($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function s3($,J,Z){let Q=(K,B)=>K.reduce((G,U)=>G+n7(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var T0=4194304,c3=536870912,Z2=/^[a-f0-9]{40}$/,i7=($,J,Z)=>new Promise((Q)=>{if(Z.signal?.aborted){Q({status:null,error:Error("cancelled"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let K;try{K=r7($,J,{cwd:Z.cwd,env:Z.env,detached:!0,stdio:["pipe","pipe","pipe"]})}catch{Q({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let B=Buffer.alloc(0),G=Buffer.alloc(0),U,W=!1,Y=(N)=>{if(U??=Error(N),K.pid)try{process.kill(-K.pid,"SIGKILL")}catch{}},X=()=>Y("cancelled"),F=setTimeout(()=>Y("timeout"),Z.timeout);Z.signal?.addEventListener("abort",X,{once:!0});let C=(N)=>{if(W)return;W=!0,clearTimeout(F),Z.signal?.removeEventListener("abort",X),Q({status:N,stdout:B,stderr:G,...U?{error:U}:{}})};if(K.stdout.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)Y("output_limit");else B=Buffer.concat([B,N])}),K.stderr.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)Y("output_limit");else G=Buffer.concat([G,N])}),K.on("error",()=>{if(Y("spawn_failed"),!K.pid)C(null)}),K.on("close",(N)=>C(N)),K.stdin.on("error",()=>Y("input_failed")),K.stdin.end(Z.input),Z.signal?.aborted)X()}),o7={command:i7,gh:($,J)=>$2(z,s,$,J),home:a7};function A($){throw Error($)}var t7=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),e7=($)=>JSON.stringify($,(J,Z)=>t7.has(J)?void 0:Z);function n3($,J,Z){let Q=[...new Set($.map((B)=>`${J(B.path)}${B.line?`:${B.line}`:""} (${B.reason==="literal_secret_detected"?`value of ${B.secretNames?.length?B.secretNames.slice(0,3).join(", "):"a session variable"}`:`${B.ruleId??"credential"} credential`})`))].slice(0,10),K=$.some((B)=>B.reason==="literal_secret_detected");A(`local_device_gh_secret_scan_failed: the change adds text matching a secret that the base does not already contain: ${Q.join("; ")}. Nothing was sent. ${Z}${K?" If the line is ordinary code, that variable's value is too generic to tell apart from code: tell the person which variable matched so they can change its value.":""}`)}async function o3($,J,Z=o7){let Q=L1.parse($);if(!["darwin","linux"].includes(process.platform))A("local_device_gh_platform_unavailable");J.assertCurrent();let K=z.realpathSync(J.root);if(K==="/")A("local_device_gh_root_unavailable");if(!M0(Q)&&!J.forbiddenSecretValues)A("local_device_gh_secret_scope_unavailable");if(!M0(Q)&&J.readOnly)A("local_device_gh_read_only");if(!M0(Q)){let L=M1([{path:"github-operation",content:e7(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!L.clean)n3(L.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let B=Z.gh(K),G=Z.home(),U=$2(z,s,K,"git"),W=J.privateDirectory?z.realpathSync(J.privateDirectory):z.realpathSync(G);if(!M0(Q)&&(!J.privateDirectory||W===K||W.startsWith(K+s.sep)))A("local_device_gh_private_scope_unavailable");let Y={PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:G,GH_CONFIG_DIR:s.join(G,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:"/bin/cat",GH_HOST:"github.com",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1",...process.platform==="linux"?Object.fromEntries(["DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR"].flatMap((L)=>process.env[L]?[[L,process.env[L]]]:[])):{}},X=async(L,T,P=W,k,x=T0)=>{J.assertCurrent();let y=await Z.command(L,T,{cwd:P,env:Y,input:k,maxBuffer:x,timeout:Math.max(1,Math.min(60000,(J.deadlineMs??Date.now()+60000)-Date.now())),signal:J.signal});if(J.assertCurrent(),y.error||y.status!==0)A("local_device_gh_command_failed");return y.stdout},F=async(L)=>(await X(B,L)).toString("utf8").trim(),C=async(L,T="application/vnd.github+json")=>{r3(Q.repoFullName,L,{headers:{accept:T}}),J.assertCurrent();let P=await Z.command(B,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${T}`,L],{cwd:W,env:Y,maxBuffer:T0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),P.error&&P.status===null)A("local_device_gh_response_unavailable");let k=P.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!k)A("local_device_gh_response_invalid");let x=Number(k[1]);if(x>=200&&x<300&&P.status!==0)A("local_device_gh_response_unavailable");if(Buffer.byteLength(k[3])>Q2)A("local_device_gh_response_too_large");let y={};for(let r of k[2].split(/\r?\n/)){let a=r.indexOf(":"),D0=r.slice(0,a).toLowerCase();if(["link","content-type"].includes(D0))y[D0]=r.slice(a+1).trim().slice(0,8192)}return{kind:"read",status:x,headers:y,body:x>=200&&x<300?k[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return C(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[L,T]=Q.repoFullName.split("/"),P=await F(["api","graphql","--hostname","github.com","-f",`query=${a3}`,"-f",`owner=${L}`,"-f",`repo=${T}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(P)>Q2)A("local_device_gh_response_too_large");let k=JSON.parse(P);if(k.errors||k.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||k.data.repository.pullRequest?.number!==Q.number)A("local_device_gh_response_invalid");return{kind:"pr_review_context",body:P}}if(Q.kind==="pr_merge"){let L=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),T=JSON.parse(L.body),P=(y)=>y.number===Q.number&&y.html_url===`https://github.com/${Q.repoFullName}/pull/${Q.number}`&&y.base?.repo?.full_name?.toLowerCase()===Q.repoFullName.toLowerCase()&&y.base?.ref===Q.expectedBaseRef&&y.head?.sha===Q.expectedHeadSha;if(L.status!==200||!P(T)||T.state!=="open"||T.draft!==!1||T.head?.sha!==Q.expectedHeadSha||T.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())A("local_device_gh_merge_target_changed");await F(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha]);let k=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),x=JSON.parse(k.body);if(k.status!==200||!P(x)||x.merged!==!0)A("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:Q.number,merged:!0}}if(Q.kind==="pr_create"){if(Q.head===Q.base)A("local_device_gh_default_branch");let L=await F(["pr","create","--repo",Q.repoFullName,"--head",Q.head,"--base",Q.base,`--title=${Q.title}`,`--body=${Q.body}`,...Q.draft?["--draft"]:[]]);if(!new RegExp("^https://github\\.com/"+Q.repoFullName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/pull/[1-9][0-9]*$").test(L))A("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:L}}if(Q.kind==="pr_mutation"){let L=Q.mutation,T=L.action==="edit"?["edit",...L.title!==void 0?[`--title=${L.title}`]:[],...L.body!==void 0?[`--body=${L.body}`]:[],...L.base?[`--base=${L.base}`]:[]]:L.action==="metadata"?["edit",`--${L.change}-${L.field}=${L.value}`]:L.action==="ready"?["ready"]:L.action==="draft"?["ready","--undo"]:["close"];return await F(["pr",...T,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)A("local_device_gh_workspace_unavailable");let N=z.realpathSync(J.repoPath);if(N!==K&&!N.startsWith(K+s.sep))A("local_device_gh_workspace_unavailable");let D=`https://github.com/${Q.repoFullName}.git`,w="!'"+B.replace(/'/g,"'\\''")+"' auth git-credential",M=Function("return ("+i3+")")(),I=(L,T,P)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",L,T,...P]]:[T,P],O=async(L,T,P,k=T0)=>{let x=L===W||L.startsWith(W+s.sep),y=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...x?["-c",`credential.https://github.com.helper=${w}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",...T];if(x)return X(U,y,L,P,k);let r=s.join(N,".ara-local-gh-tmp");if(z.mkdirSync(r,{recursive:!0,mode:448}),z.lstatSync(r).isSymbolicLink()||z.realpathSync(r)!==r)A("local_device_gh_workspace_unavailable");J.assertCurrent();let a=await Z.command(...I(M(N,r),U,y),{cwd:L,input:P,maxBuffer:k,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:N,TMPDIR:r,GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1"}});if(J.assertCurrent(),a.error||a.status!==0)A("local_device_gh_collection_failed");return a.stdout},R=async(L,T)=>(await O(L,T)).toString("utf8").trim(),E=async(L,T)=>{let P=s.join(L,".ara-local-gh-tmp");if(z.mkdirSync(P,{recursive:!0,mode:448}),z.lstatSync(P).isSymbolicLink()||z.realpathSync(P)!==P)A("local_device_gh_workspace_unavailable");J.assertCurrent();let k=await Z.command(...I(M(L,P),"/bin/sh",["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",T]),{cwd:L,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:L,TMPDIR:P}});if(J.assertCurrent(),k.error||k.status!==0)A("local_device_gh_materialization_failed")},v=async(L)=>{let T=new Map;if(L.length===0)return T;let P=await O(S,["cat-file","--batch"],[...new Set(L)].join(`
|
|
2
|
+
import{$a as n6,Ea as u6,Ga as w4,Ha as O4,Ma as l6,Na as s6,Xa as I4,ab as r6,bb as S4,cb as k4,eb as a6,ga as U4,gb as B8,hb as y0,ia as W2,ib as m0,ja as X4,jb as c1,ka as W4,la as Y4,ma as S6,mb as i6,na as f6,oa as M4,pa as b6,pb as V8,qa as A3,qb as A4,ra as x6,sa as y6,sb as o6,ta as h6,ua as m6,va as L4,wa as v6,xa as p6}from"./vm-hands-entry-lite-7vscxzd1.js";import{Ab as n0,Bb as r0,Ib as P0,tb as i3,ub as q6,vb as E6}from"./vm-hands-entry-lite-rrk5g62b.js";import{Jb as t6,Mb as e6,Ob as $7,Pb as J7}from"./vm-hands-entry-lite-ya1a2eep.js";import{Ub as d6}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Vb as _6,Wb as R6,Xb as P6,Yb as z6,Zb as L0}from"./vm-hands-entry-lite-n07kxrd1.js";import{$b as o1,ac as t1,bc as S3,dc as k3,fc as f3,gc as b3,kc as x3}from"./vm-hands-entry-lite-0ergg2ky.js";import{Bc as r1,Ec as H7,Nc as D7}from"./vm-hands-entry-lite-425yvj0s.js";import{$c as d,$d as g8,Ad as w6,Cd as O6,Dd as j6,Ed as I6,Fd as A6,Gd as T6,Ld as D8,Md as M8,Nd as L8,Oc as L1,Od as w8,Pc as Q2,Pd as O8,Qc as e5,Qd as j8,Rc as I3,Sc as r3,Sd as I8,Tc as a3,Td as A8,Uc as M0,Ud as T8,Vd as _8,Wd as R8,Xd as P8,Yc as N0,Yd as z8,Zd as q8,_d as E8,ad as E1,dd as H8,fd as g1,hd as $6,id as J6,jd as Z6,kd as Q6,ld as K6,md as B6,nd as V6,od as G6,pd as U6,qd as X6,rd as W6,sd as Y6,td as F6,ud as N6,vd as C6,wd as H6,xd as D6,yd as M6,zd as L6}from"./vm-hands-entry-lite-8st97h7b.js";import{ae as V}from"./vm-hands-entry-lite-q6fshf3h.js";import{Ae as l1,be as W7,ce as Y7,de as F7,ee as N7,fe as C7,le as p5,pe as Q5,qe as T5,we as M7,ze as K5}from"./vm-hands-entry-lite-987hd3pc.js";import{Ze as j4,ef as c6}from"./vm-hands-entry-lite-pf1ft65e.js";import{jf as M3,wf as g6}from"./vm-hands-entry-lite-q2pb31vh.js";import{Bg as Z7,Cg as Q7,Dg as K7,Eg as B7,Gg as V7,Hg as G7,Jg as U7,Kg as X7}from"./vm-hands-entry-lite-6j2yaa4n.js";import{Yg as n1}from"./vm-hands-entry-lite-7k65s010.js";import{$g as k6,_g as j1,ah as H4,bh as D4}from"./vm-hands-entry-lite-em388nee.js";import{dh as D3,fh as $1,lh as K8,mh as J4}from"./vm-hands-entry-lite-yp315y25.js";import{Kh as H}from"./vm-hands-entry-lite-xsq25kmd.js";import{Oh as a4}from"./vm-hands-entry-lite-hf0mk7vd.js";import{request as m7}from"http";import{request as v7}from"https";async function p7($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?v7:m7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:k3},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Error("custom_endpoint_timeout"))),K.end($.body)})}function u7($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function d7($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=K[U-1];if(Z[G]===Z[U])U++;K[G]=U}let B=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+B),Y=0;for(let X of G){while(B&&Z[B]!==X){let F=K[B-1];Y+=Z.copy(W,Y,0,B-F),B=F}if(Z[B]===X){if(B++,B===Z.length)Y+=Q.copy(W,Y),B=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,B),B=0;return W.subarray(0,Y)}}async function y3($){$.signal.throwIfAborted();let J=b3.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=x3.parse(await $.credential($.signal));if(!f3(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new H("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let K,B,G=0,U=0,W=0,Y=u7(Q.apiKey),X=d7(Q.apiKey,Y),F=async(N,D)=>{$.signal.throwIfAborted(),await new Promise((w,M)=>{let I=()=>{$.signal.removeEventListener("abort",I),M($.signal.reason)};if($.signal.addEventListener("abort",I,{once:!0}),$.signal.aborted){I();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,D)}).then(()=>{$.signal.removeEventListener("abort",I),w()},(O)=>{$.signal.removeEventListener("abort",I),M(O)})})},C=async(N)=>{if(G+=N.length,G>t1)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<N.length;D+=o1){if(W>=S3)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await F(`custom_endpoint.chunk.${W++}`,{eof:!1,data:N.subarray(D,D+o1).toString("base64")})}};try{let N=await p7({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=N.response,B=N.close;let D=K.statusCode??500;if(D>=300&&D<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let w={};for(let M of["content-type","retry-after","x-request-id","request-id"]){let I=K.headers[M];if(typeof I==="string")w[M]=I.replaceAll(Q.apiKey,Y).slice(0,4096)}await F("custom_endpoint.headers",{status:D,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:w});for await(let M of K){$.signal.throwIfAborted();let I=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=I.length,U>t1)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await C(X(I))}return await C(X(Buffer.alloc(0),!0)),await F(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(N){if($.signal.throwIfAborted(),N instanceof H)throw N;throw new H("custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as h3}from"path";function l7($,J){return $===h3(J,".ara","workspace")||$===h3(J,".reason","workspace")}function m3($,J){let Z=$.filter((Q)=>l7(Q.path,J));return Z.length===1?Z[0].path:null}var s7=/^[a-f0-9]{64}$/;var e1=32,c7=/^\/[^\x00-\x1f\x7f\\]*$/;function H1($){if(typeof $!=="string"||$.length>4096||!c7.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function D1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!H1(J.home)||!Array.isArray(J.roots)||J.roots.length>e1)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:K,path:B}=Q;if(typeof K!=="string"||!s7.test(K)||!H1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}import{spawn as r7}from"child_process";import*as z from"fs";import*as s from"path";import{homedir as a7}from"os";function $2($,J,Z,Q="gh"){if(!["gh","git"].includes(Q))throw Error("local_device_gh_unavailable");let K=$.realpathSync(Z),B=Q==="git"&&process.platform==="darwin"?"/Library/Developer/CommandLineTools/usr/bin/git":"/usr/bin/"+Q;for(let G of["/opt/homebrew/bin/"+Q,"/usr/local/bin/"+Q,B])try{let U=$.realpathSync(G);if(U===K||U.startsWith(K+J.sep)||!["/opt/homebrew/","/usr/local/","/usr/bin/",...Q==="git"?["/Library/Developer/CommandLineTools/"]:[]].some((Y)=>U.startsWith(Y)))continue;let W=$.statSync(U);if(!W.isFile()||(W.mode&18)!==0||![0,process.getuid()].includes(W.uid))continue;return $.accessSync(U,$.constants.X_OK),U}catch{continue}throw Error("local_device_gh_unavailable")}function v3($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var p3=[{name:"private_key",regex:/-----BEGIN\s+(?:[A-Z0-9_-]+\s+)?PRIVATE\s+KEY-----/i},{name:"github_pat",regex:/\bgh[pousr]_[A-Za-z0-9_]{36,}\b/},{name:"github_fine_grained_pat",regex:/\bgithub_pat_[A-Za-z0-9_]{36,}\b/},{name:"gitlab_pat",regex:/\bglpat-[0-9a-zA-Z_-]{20,}\b/},{name:"slack_token",regex:/\bxox[baprs]-[0-9]{10,}-[0-9]{10,}-[0-9a-zA-Z]{24}\b/},{name:"stripe_live_key",regex:/\b[sr]k_live_[0-9a-zA-Z]{24,}\b/},{name:"bearer_jwt",regex:/\bBearer\s+ey[A-Za-z0-9_-]{20,}\.ey[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/}];function J2($){let J=$.trim().replaceAll("\\","/");if(!J)return{valid:!1,reason:"empty_path"};if(J.startsWith("/"))return{valid:!1,reason:"absolute_path_forbidden"};if(J.split("/").includes("..")||J.includes("../")||J.endsWith("/.."))return{valid:!1,reason:"path_traversal_forbidden"};if(J===".git"||J.startsWith(".git/")||J.includes("/.git/"))return{valid:!1,reason:"git_directory_entry_forbidden"};return{valid:!0}}function u3($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function d3($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function M1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=u3(J).filter((G)=>!K.has(G));for(let G of $){let U=J2(G.path);if(!U.valid){Q.push({path:G.path,reason:U.reason??"invalid_path"});continue}let W=G.content??"",Y=B.map((X)=>({secret:X,offset:W.indexOf(X)})).filter((X)=>X.offset>=0).sort((X,F)=>X.offset-F.offset);if(Y.length>0){let X=[...new Set(Y.flatMap((F)=>Z.secretNames?.(F.secret)??[]))];Q.push({path:G.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:v3(W,Y[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of p3){let F=d3(X,W).find((C)=>!K.has(C[0]));if(F){Q.push({path:G.path,reason:`credential_pattern_detected: ${X.name}`,pattern:X.name,ruleId:X.name,line:v3(W,F.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function l3($,J=[]){let Z=u3(J),Q=new Set;for(let{content:K}of $){for(let B of Z)if(K.includes(B))Q.add(B);for(let B of p3)for(let G of d3(B,K))Q.add(G[0])}return[...Q]}function n7($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function s3($,J,Z){let Q=(K,B)=>K.reduce((G,U)=>G+n7(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var T0=4194304,c3=536870912,Z2=/^[a-f0-9]{40}$/,i7=($,J,Z)=>new Promise((Q)=>{if(Z.signal?.aborted){Q({status:null,error:Error("cancelled"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let K;try{K=r7($,J,{cwd:Z.cwd,env:Z.env,detached:!0,stdio:["pipe","pipe","pipe"]})}catch{Q({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let B=Buffer.alloc(0),G=Buffer.alloc(0),U,W=!1,Y=(N)=>{if(U??=Error(N),K.pid)try{process.kill(-K.pid,"SIGKILL")}catch{}},X=()=>Y("cancelled"),F=setTimeout(()=>Y("timeout"),Z.timeout);Z.signal?.addEventListener("abort",X,{once:!0});let C=(N)=>{if(W)return;W=!0,clearTimeout(F),Z.signal?.removeEventListener("abort",X),Q({status:N,stdout:B,stderr:G,...U?{error:U}:{}})};if(K.stdout.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)Y("output_limit");else B=Buffer.concat([B,N])}),K.stderr.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)Y("output_limit");else G=Buffer.concat([G,N])}),K.on("error",()=>{if(Y("spawn_failed"),!K.pid)C(null)}),K.on("close",(N)=>C(N)),K.stdin.on("error",()=>Y("input_failed")),K.stdin.end(Z.input),Z.signal?.aborted)X()}),o7={command:i7,gh:($,J)=>$2(z,s,$,J),home:a7};function A($){throw Error($)}var t7=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),e7=($)=>JSON.stringify($,(J,Z)=>t7.has(J)?void 0:Z);function n3($,J,Z){let Q=[...new Set($.map((B)=>`${J(B.path)}${B.line?`:${B.line}`:""} (${B.reason==="literal_secret_detected"?`value of ${B.secretNames?.length?B.secretNames.slice(0,3).join(", "):"a session variable"}`:`${B.ruleId??"credential"} credential`})`))].slice(0,10),K=$.some((B)=>B.reason==="literal_secret_detected");A(`local_device_gh_secret_scan_failed: the change adds text matching a secret that the base does not already contain: ${Q.join("; ")}. Nothing was sent. ${Z}${K?" If the line is ordinary code, that variable's value is too generic to tell apart from code: tell the person which variable matched so they can change its value.":""}`)}async function o3($,J,Z=o7){let Q=L1.parse($);if(!["darwin","linux"].includes(process.platform))A("local_device_gh_platform_unavailable");J.assertCurrent();let K=z.realpathSync(J.root);if(K==="/")A("local_device_gh_root_unavailable");if(!M0(Q)&&!J.forbiddenSecretValues)A("local_device_gh_secret_scope_unavailable");if(!M0(Q)&&J.readOnly)A("local_device_gh_read_only");if(!M0(Q)){let L=M1([{path:"github-operation",content:e7(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!L.clean)n3(L.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let B=Z.gh(K),G=Z.home(),U=$2(z,s,K,"git"),W=J.privateDirectory?z.realpathSync(J.privateDirectory):z.realpathSync(G);if(!M0(Q)&&(!J.privateDirectory||W===K||W.startsWith(K+s.sep)))A("local_device_gh_private_scope_unavailable");let Y={PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:G,GH_CONFIG_DIR:s.join(G,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:"/bin/cat",GH_HOST:"github.com",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1",...process.platform==="linux"?Object.fromEntries(["DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR"].flatMap((L)=>process.env[L]?[[L,process.env[L]]]:[])):{}},X=async(L,T,P=W,k,x=T0)=>{J.assertCurrent();let y=await Z.command(L,T,{cwd:P,env:Y,input:k,maxBuffer:x,timeout:Math.max(1,Math.min(60000,(J.deadlineMs??Date.now()+60000)-Date.now())),signal:J.signal});if(J.assertCurrent(),y.error||y.status!==0)A("local_device_gh_command_failed");return y.stdout},F=async(L)=>(await X(B,L)).toString("utf8").trim(),C=async(L,T="application/vnd.github+json")=>{r3(Q.repoFullName,L,{headers:{accept:T}}),J.assertCurrent();let P=await Z.command(B,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${T}`,L],{cwd:W,env:Y,maxBuffer:T0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),P.error&&P.status===null)A("local_device_gh_response_unavailable");let k=P.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!k)A("local_device_gh_response_invalid");let x=Number(k[1]);if(x>=200&&x<300&&P.status!==0)A("local_device_gh_response_unavailable");if(Buffer.byteLength(k[3])>Q2)A("local_device_gh_response_too_large");let y={};for(let r of k[2].split(/\r?\n/)){let a=r.indexOf(":"),D0=r.slice(0,a).toLowerCase();if(["link","content-type"].includes(D0))y[D0]=r.slice(a+1).trim().slice(0,8192)}return{kind:"read",status:x,headers:y,body:x>=200&&x<300?k[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return C(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[L,T]=Q.repoFullName.split("/"),P=await F(["api","graphql","--hostname","github.com","-f",`query=${a3}`,"-f",`owner=${L}`,"-f",`repo=${T}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(P)>Q2)A("local_device_gh_response_too_large");let k=JSON.parse(P);if(k.errors||k.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||k.data.repository.pullRequest?.number!==Q.number)A("local_device_gh_response_invalid");return{kind:"pr_review_context",body:P}}if(Q.kind==="pr_merge"){let L=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),T=JSON.parse(L.body),P=(y)=>y.number===Q.number&&y.html_url===`https://github.com/${Q.repoFullName}/pull/${Q.number}`&&y.base?.repo?.full_name?.toLowerCase()===Q.repoFullName.toLowerCase()&&y.base?.ref===Q.expectedBaseRef&&y.head?.sha===Q.expectedHeadSha;if(L.status!==200||!P(T)||T.state!=="open"||T.draft!==!1||T.head?.sha!==Q.expectedHeadSha||T.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())A("local_device_gh_merge_target_changed");await F(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha]);let k=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),x=JSON.parse(k.body);if(k.status!==200||!P(x)||x.merged!==!0)A("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:Q.number,merged:!0}}if(Q.kind==="pr_create"){if(Q.head===Q.base)A("local_device_gh_default_branch");let L=await F(["pr","create","--repo",Q.repoFullName,"--head",Q.head,"--base",Q.base,`--title=${Q.title}`,`--body=${Q.body}`,...Q.draft?["--draft"]:[]]);if(!new RegExp("^https://github\\.com/"+Q.repoFullName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/pull/[1-9][0-9]*$").test(L))A("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:L}}if(Q.kind==="pr_mutation"){let L=Q.mutation,T=L.action==="edit"?["edit",...L.title!==void 0?[`--title=${L.title}`]:[],...L.body!==void 0?[`--body=${L.body}`]:[],...L.base?[`--base=${L.base}`]:[]]:L.action==="metadata"?["edit",`--${L.change}-${L.field}=${L.value}`]:L.action==="ready"?["ready"]:L.action==="draft"?["ready","--undo"]:["close"];return await F(["pr",...T,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)A("local_device_gh_workspace_unavailable");let N=z.realpathSync(J.repoPath);if(N!==K&&!N.startsWith(K+s.sep))A("local_device_gh_workspace_unavailable");let D=`https://github.com/${Q.repoFullName}.git`,w="!'"+B.replace(/'/g,"'\\''")+"' auth git-credential",M=Function("return ("+i3+")")(),I=(L,T,P)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",L,T,...P]]:[T,P],O=async(L,T,P,k=T0)=>{let x=L===W||L.startsWith(W+s.sep),y=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...x?["-c",`credential.https://github.com.helper=${w}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",...T];if(x)return X(U,y,L,P,k);let r=s.join(N,".ara-local-gh-tmp");if(z.mkdirSync(r,{recursive:!0,mode:448}),z.lstatSync(r).isSymbolicLink()||z.realpathSync(r)!==r)A("local_device_gh_workspace_unavailable");J.assertCurrent();let a=await Z.command(...I(M(N,r),U,y),{cwd:L,input:P,maxBuffer:k,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:N,TMPDIR:r,GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1"}});if(J.assertCurrent(),a.error||a.status!==0)A("local_device_gh_collection_failed");return a.stdout},R=async(L,T)=>(await O(L,T)).toString("utf8").trim(),E=async(L,T)=>{let P=s.join(L,".ara-local-gh-tmp");if(z.mkdirSync(P,{recursive:!0,mode:448}),z.lstatSync(P).isSymbolicLink()||z.realpathSync(P)!==P)A("local_device_gh_workspace_unavailable");J.assertCurrent();let k=await Z.command(...I(M(L,P),"/bin/sh",["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",T]),{cwd:L,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:L,TMPDIR:P}});if(J.assertCurrent(),k.error||k.status!==0)A("local_device_gh_materialization_failed")},v=async(L)=>{let T=new Map;if(L.length===0)return T;let P=await O(S,["cat-file","--batch"],[...new Set(L)].join(`
|
|
3
3
|
`)+`
|
|
4
4
|
`,T0*8);for(let k=0;k<P.length;){let x=P.indexOf(10,k),[y,r,a]=P.subarray(k,x).toString("utf8").split(" ");if(x<0||!y||r!=="blob"||!/^[0-9]+$/.test(a??""))A("local_device_gh_object_invalid");T.set(y,P.subarray(x+1,x+1+Number(a)).toString("utf8")),k=x+1+Number(a)+1}return T},j=async(L,T,P)=>{let k=s.join(N,".ara-local-gh-tmp"),x=M(N,k)+`
|
|
5
5
|
(allow file-read* file-write* (subpath ${JSON.stringify(N)}))
|
|
@@ -23,7 +23,7 @@ Content-Length: 0\r
|
|
|
23
23
|
\r
|
|
24
24
|
`),E4(W,N,Y)})().catch(()=>W.destroy())}),await new Promise((U,W)=>{B.once("error",W),B.listen(0,"127.0.0.1",()=>U())});let{port:G}=B.address();return{url:`http://127.0.0.1:${G}`,close(){B.close();for(let U of Q)U.destroy()}}}import{createHash as O2,randomUUID as f9}from"crypto";import{closeSync as t0,constants as c,fchownSync as b9,fstatSync as z0,fsyncSync as x9,linkSync as y9,mkdirSync as h9,openSync as i4,readSync as o4,unlinkSync as m9,writeSync as v9}from"fs";import{platform as n4}from"os";import{getSystemErrorName as p9}from"util";var x4={type:"string",format:"uuid"},v4=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,A1={type:"string",minLength:1,maxLength:4096,pattern:v4},H2=V.string().min(1).max(4096).regex(new RegExp(v4)),T1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},_1={device_id:x4,root_id:x4,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},fK={read:{schema:V.object({...T1,path:H2,offset:V.number().int().min(0).optional(),max_bytes:V.number().int().min(1).max(131072).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path"],properties:{..._1,path:A1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:V.object({...T1,path:H2,content:V.string().max(131072),mode:V.enum(["overwrite","append"]).optional(),create_parents:V.boolean().optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path","content"],properties:{..._1,path:A1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:V.object({...T1,command:V.string().min(1).max(16000),cwd:H2.optional(),mode:V.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{..._1,command:{type:"string",minLength:1,maxLength:16000},cwd:A1,mode:{type:"string",enum:["confined","host"],description:"Defaults to host: the existing permitted login shell with OS/account access, requiring execute and environment-discovery permission. Request confined explicitly for a scrubbed shell without network."}},additionalProperties:!1}}},W0=1073741824,i0=600000,y4=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,p4=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${y4}(?:/${y4})*(?![\s\S])`,u4=new RegExp(p4);function d4($){return typeof $==="string"&&$.length>0&&$.length<=4096&&u4.test($)}var D2=V.string().min(1).max(4096).regex(u4),M2={...A1,pattern:p4},l4=V.string().regex(/^[a-f0-9]{64}$/),s4=V.object({kind:V.literal("workspace"),path:D2}).strict(),g9=V.discriminatedUnion("kind",[s4,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:l4}).strict()]),R1=1,o0="cloud_workspace_id",L2="cloud_workspace",w2=1,S9=V.discriminatedUnion("kind",[s4,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(W0),sha256:l4}).strict()]),c4=V.object({source_version:V.literal(R1),source:S9,url:V.string().min(1).max(16384),transfer_cloud_scope:V.object({sandboxId:V.string().min(1).max(256),revision:V.number().int().nonnegative(),brainFence:V.string().uuid()}).strict().optional(),[o0]:V.string().min(1).max(160).optional()}).strict(),bK=V.object({ready:V.literal(!0),cloud_source_version:V.literal(R1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var h4=V.object({...T1,timeout_ms:V.number().int().min(1000).max(i0).optional(),source_path:D2,destination_path:D2,idempotency_key:V.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),m4={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{..._1,timeout_ms:{type:"integer",minimum:1000,maximum:i0},source_path:M2,destination_path:M2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},k9={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:M2},additionalProperties:!1},{type:"object",required:["kind","attachment_id","sha256"],properties:{kind:{type:"string",const:"attachment"},attachment_id:{type:"string",minLength:1,maxLength:120},sha256:{type:"string",pattern:"^[a-f0-9]{64}$"}},additionalProperties:!1}]},xK=V.union([h4,h4.omit({source_path:!0}).extend({source:g9}).strict()]),yK={...m4,required:["device_id","root_id","destination_path"],properties:{...m4.properties,source:k9},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var j2=65536;function u($){throw new H($,$)}function z1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function P1($,J,Z){if(J.throwIfAborted(),$ instanceof H||$ instanceof Error&&$.name==="AbortError")throw $;return u(Z)}function u9($,J,Z){let Q;switch(z1($)){case"ENOENT":Q=Z==="export"?"transfer_source_missing":"transfer_path_unavailable";break;case"EACCES":case"EPERM":case"EROFS":Q="transfer_permission_denied";break;case"ELOOP":case"ENOTDIR":Q="transfer_path_unsafe";break;case"EEXIST":Q="transfer_destination_exists";break;default:Q="transfer_path_unavailable"}return P1($,J,Q)}function d9($){if(typeof $!=="string"||$.length>16384)return u("transfer_url_invalid");let J;try{J=new URL($)}catch{return u("transfer_url_invalid")}if(J.protocol!=="https:"||J.username||J.password||J.hash)return u("transfer_url_invalid");return J.href}async function l9(){if(n4()==="linux")return{open:(U,W,Y,X=384)=>i4(`/proc/self/fd/${U}/${W}`,Y,X),mkdir:(U,W)=>h9(`/proc/self/fd/${U}/${W}`,{mode:448}),link:(U,W,Y)=>y9(`/proc/self/fd/${U}/${W}`,`/proc/self/fd/${U}/${Y}`),unlink:(U,W)=>m9(`/proc/self/fd/${U}/${W}`),close:()=>{}};if(n4()!=="darwin")return u("transfer_platform_unsupported");let{dlopen:$,FFIType:J,ptr:Z,read:Q}=await import("bun:ffi"),K=$("/usr/lib/libSystem.B.dylib",{__error:{args:[],returns:J.ptr},openat:{args:[J.i32,J.ptr,J.i32,J.i32,J.i32,J.i32,J.i32,J.i32,J.i32],returns:J.i32},mkdirat:{args:[J.i32,J.ptr,J.i32],returns:J.i32},linkat:{args:[J.i32,J.ptr,J.i32,J.ptr,J.i32],returns:J.i32},unlinkat:{args:[J.i32,J.ptr,J.i32],returns:J.i32}}),B=K.symbols.__error();if(B===null)return K.close(),u("transfer_path_unavailable");let G=(U)=>{if(U<0){let W=p9(-Q.i32(B));throw Object.assign(Error("transfer_path_unavailable"),{code:W})}return U};return{open:(U,W,Y,X=384)=>G(K.symbols.openat(U,Z(Buffer.from(`${W}\x00`)),Y,X,0,0,0,0,X)),mkdir:(U,W)=>{G(K.symbols.mkdirat(U,Z(Buffer.from(`${W}\x00`)),448))},link:(U,W,Y)=>{G(K.symbols.linkat(U,Z(Buffer.from(`${W}\x00`)),U,Z(Buffer.from(`${Y}\x00`)),0))},unlink:(U,W)=>{G(K.symbols.unlinkat(U,Z(Buffer.from(`${W}\x00`)),0))},close:()=>K.close()}}function t4($,J){let Z=z0($),Q=z0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)b9(J,Z.uid,Z.gid)}function s9($,J,Z,Q){if(!d4(Z))return u("transfer_path_invalid");let K=Z.split("/"),B=i4(J,c.O_RDONLY|c.O_DIRECTORY|c.O_NOFOLLOW);try{for(let G of K.slice(0,-1)){let U;try{U=$.open(B,G,c.O_RDONLY|c.O_DIRECTORY|c.O_NOFOLLOW)}catch(W){if(!Q||z1(W)!=="ENOENT")throw W;try{$.mkdir(B,G)}catch(Y){if(z1(Y)!=="EEXIST")throw Y}U=$.open(B,G,c.O_RDONLY|c.O_DIRECTORY|c.O_NOFOLLOW),t4(B,U)}t0(B),B=U}return{fd:B,leaf:K.at(-1)}}catch(G){throw t0(B),G}}function r4($,J){let Z=z0($,{bigint:!0});if(!Z.isFile()||Z.size>W0)return u("transfer_file_invalid");let Q=O2("sha256"),K=Buffer.alloc(j2),B=0;while(!0){J.throwIfAborted();let U=o4($,K,0,K.length,B);if(!U)break;if(B+=U,B>W0)return u("transfer_size_exceeded");Q.update(K.subarray(0,U))}let G=z0($,{bigint:!0});if(BigInt(B)!==Z.size||G.size!==Z.size||G.mtimeNs!==Z.mtimeNs||G.ctimeNs!==Z.ctimeNs)return u("transfer_source_changed");return{size_bytes:B,sha256:Q.digest("hex")}}async function q0($){$.signal.throwIfAborted();try{let J=d9($.payload.url),Z=await l9(),Q,K,B;try{if(Q=s9(Z,$.root,$.path,$.direction==="import"),$.direction==="export"){K=Z.open(Q.fd,Q.leaf,c.O_RDONLY|c.O_NOFOLLOW|c.O_NONBLOCK);let C=z0(K,{bigint:!0});if(!C.isFile()||C.size>W0)return u("transfer_file_invalid");let N=O2("sha256"),D=0,w=K,M,I=new ReadableStream({pull(v){try{$.signal.throwIfAborted();let j=Buffer.alloc(j2),q=o4(w,j,0,j.length,D);if(!q){v.close();return}if(D+=q,D>C.size)return u("transfer_source_changed");N.update(j.subarray(0,q)),v.enqueue(j.subarray(0,q))}catch(j){throw M=j,j}}});try{let v=await($.fetchImpl??fetch)(J,Object.assign({method:"PUT",body:I,redirect:"error",signal:$.signal,headers:{"content-type":"application/octet-stream","content-length":String(C.size)}},{duplex:"half"}));if(M!==void 0)throw M;if(!v.ok)return u("transfer_upload_failed");await v.body?.cancel()}catch(v){if(M!==void 0)throw M;return P1(v,$.signal,"transfer_upload_failed")}let O=z0(K,{bigint:!0});if(BigInt(D)!==C.size||O.size!==C.size||O.mtimeNs!==C.mtimeNs||O.ctimeNs!==C.ctimeNs)return u("transfer_source_changed");let R=N.digest("hex"),E=r4(K,$.signal);if(E.size_bytes!==D||E.sha256!==R)return u("transfer_source_changed");return{size_bytes:D,sha256:R,outcome:"copied"}}let G=$.payload.size_bytes,U=$.payload.sha256;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0||G>W0||typeof U!=="string"||!/^[a-f0-9]{64}$/.test(U))return u("transfer_receipt_invalid");let W;try{W=Z.open(Q.fd,Q.leaf,c.O_RDONLY|c.O_NOFOLLOW|c.O_NONBLOCK)}catch(C){if(z1(C)!=="ENOENT")throw C}if(W!==void 0){try{let C=r4(W,$.signal);if(C.size_bytes===G&&C.sha256===U)return{...C,outcome:"already_present"}}finally{t0(W)}return u("transfer_destination_exists")}B=`.reason-copy-${f9()}`,K=Z.open(Q.fd,B,c.O_CREAT|c.O_EXCL|c.O_WRONLY|c.O_NOFOLLOW,384),t4(Q.fd,K);let Y;try{let C=await($.fetchImpl??fetch)(J,{redirect:"error",signal:$.signal});if(!C.ok||!C.body)return u("transfer_download_failed");Y=C.body.getReader()}catch(C){return P1(C,$.signal,"transfer_download_failed")}let X=O2("sha256"),F=0;try{while(!0){$.signal.throwIfAborted();let C=await Y.read().catch((N)=>P1(N,$.signal,"transfer_download_failed"));if(C.done)break;if(F+=C.value.length,F>G)return u("transfer_size_mismatch");X.update(C.value);for(let N=0;N<C.value.length;)$.signal.throwIfAborted(),N+=v9(K,C.value,N,Math.min(j2,C.value.length-N))}}finally{await Y.cancel().catch(()=>{})}if(F!==G||X.digest("hex")!==U)return u("transfer_hash_mismatch");return x9(K),await $.beforeCommit?.(),$.signal.throwIfAborted(),Z.link(Q.fd,B,Q.leaf),{size_bytes:G,sha256:U,outcome:"copied"}}finally{try{if(K!==void 0)t0(K)}finally{try{if(Q){if(B)try{Z.unlink(Q.fd,B)}catch{}t0(Q.fd)}}finally{Z.close()}}}}catch(J){return u9(J,$.signal,$.direction)}}import{spawn as n9}from"child_process";import{mkdtempSync as r9,rmSync as a9,writeFileSync as i9}from"fs";import{constants as o9,platform as t9,tmpdir as e9}from"os";import{join as Z8}from"path";import{gunzipSync as c9,gzipSync as nK}from"zlib";var $8=900000,aK=$8+60000,e0=49152,e4=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),J8=V.object({version:V.literal(1),script_gzip:e4(163840),stdin_gzip:e4(65536),cwd:V.string().min(1).max(4096).startsWith("/"),env:V.record(V.string().regex(/^[A-Z_][A-Z0-9_]{0,63}$/),V.string().max(4096)).refine(($)=>Object.keys($).length<=16,"too many variables"),timeout_ms:V.number().int().min(1000).max($8)}).strict(),I2=V.string().max(e0+256),iK=V.object({exit_code:V.number().int().min(0).max(255),stdout:I2,stderr:I2,combined:I2.optional()}).strict();function A2($){return c9(Buffer.from($,"base64")).toString("utf8")}var $$="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",J$=["RUSTUP_HOME","TZ","LC_ALL"],Z$=2000,Q$=100;function _2(){return t9()==="linux"&&process.geteuid?.()===0}function T2($){let J=Math.floor($/2),Z=[],Q=0,K=Buffer.alloc(0),B=0;return{push(G){B+=G.length;let U=G;if(Q<J){let W=U.subarray(0,J-Q);Z.push(W),Q+=W.length,U=U.subarray(W.length)}if(U.length)K=Buffer.concat([K,U]).subarray(-J)},text(){let G=B-Q-K.length;return Buffer.concat(Z).toString("utf8")+(G>0?`
|
|
25
25
|
[reason: ${G} bytes of output omitted]
|
|
26
|
-
`:"")+K.toString("utf8")}}}async function Q8($,J){if(!_2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=J8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=A2(Q.script_gzip),B=A2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=r9(Z8(e9(),"reason-workspace-setup-"));try{let U=Z8(G,"setup.sh");i9(U,K,{mode:384});let W={PATH:$$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let E of J$)if(process.env[E])W[E]=process.env[E];Object.assign(W,Q.env);let Y=n9("/bin/bash",[U],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),X=T2(e0),F=T2(e0),C=T2(e0);Y.stdout.on("data",(E)=>{X.push(E),C.push(E)}),Y.stderr.on("data",(E)=>{F.push(E),C.push(E)}),Y.stdin.on("error",()=>{}),Y.stdin.end(B);let N=(E)=>{try{if(Y.pid)process.kill(-Y.pid,E)}catch{}},D=!1,w,M=()=>{N("SIGTERM"),w??=setTimeout(()=>N("SIGKILL"),Z$)},I=setTimeout(()=>{D=!0,M()},Q.timeout_ms);J.addEventListener("abort",M,{once:!0});let O=await new Promise((E,v)=>{Y.once("error",()=>v(new H("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(j,q)=>E({code:j,signal:q}))}).finally(()=>{clearTimeout(I),clearTimeout(w),J.removeEventListener("abort",M)});await new Promise((E)=>{let v=setTimeout(E,Q$);Y.once("close",()=>{clearTimeout(v),E()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let R=D?124:O.signal?128+(o9.signals[O.signal]??0):O.code??1;return{exit_code:Math.min(255,R),stdout:X.text(),stderr:F.text(),...R!==0?{combined:C.text()}:{}}}finally{a9(G,{recursive:!0,force:!0})}}import{chmodSync as K$,mkdtempSync as B$,realpathSync as G8,rmSync as V$}from"fs";import{tmpdir as G$}from"os";import{dirname as U$,join as R2,sep as X$}from"path";function P2($){return V8($,B8($)!==null).repoPath}function U8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[$1,void 0].map((K)=>U$(K8({kind:"managed",workspaceId:J,...K?{layout:K}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let K of Z)try{Q=G8(R2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${X$}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function X8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=P2($.runtimeRoot);if(L0(Q)||L0(R2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return q0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=B$(R2(G$(),`reason-cloud-copy-${process.pid}-`));try{K$(Z,448);let Q=G8(Z);await q0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let K=await q0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(K.size_bytes!==J.size_bytes||K.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return K}finally{V$(Z,{recursive:!0,force:!0})}}import{constants as A0}from"fs";import{closeSync as L7,existsSync as G0,fstatSync as w7,lstatSync as O7,mkdirSync as mZ,mkdtempSync as j7,openSync as I7,readSync as vZ,realpathSync as J0,rmSync as A7,statSync as N1,writeSync as pZ}from"fs";import{homedir as W1,platform as l,tmpdir as T7}from"os";import{dirname as Y1,isAbsolute as uZ,join as T3,relative as L3,resolve as dZ,sep as lZ}from"path";import{spawn as sZ}from"child_process";import{createHash as C$,randomBytes as H$}from"crypto";var z2=30000,W$=1800000,Y$=5000,q1=30000,F$=g1+15000,W8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,N$=[/^\/app\/local-runtime\/operations\/claim$/,W8];class q2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((W)=>Q.pending.set(K,{path:$,resolve:W}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(N$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},F$);else{let W=()=>{if(!Q.pending.has(K))return;let Y=this.now()-Q.lastFrameAt;if(Y>=q1)this.drop(Q);else G=setTimeout(W,q1-Y)};G=setTimeout(W,q1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((W,Y)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>q1)this.drop(Q);Y(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),B.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([B,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(Y$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(W$,z2*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+J/2+this.jitter(J/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let $=this.options.WebSocket??globalThis.WebSocket;if(!$){this.retryAt=Number.POSITIVE_INFINITY;return}let J=new URL(E1,this.options.apiOrigin);J.protocol=J.protocol==="https:"?"wss:":"ws:",J.searchParams.set("device_id",this.options.deviceId);let Z;try{Z=new $(J.toString())}catch{this.failures+=1,this.retryAt=this.now()+z2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(K)=>this.receive(Q,K.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[K,B]of Q.pending){if(!W8.test(B.path))continue;Q.pending.delete(K),this.send(Q,{t:"abort",id:K}),B.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(z2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var g2=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function IB($,J={}){let Z=D$($),Q=J.rootPathsSupported===!0?D1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((K)=>/^[a-f0-9]{64}$/.test(K))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function D$($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[G,U]of Object.entries(K).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[G]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class Y0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}function M$($){return $===408||$===429||$===500||$===502||$===503||$===504}function L$($){if($ instanceof Y0)return!1;if(!($ instanceof Error))return!1;if($.name==="AbortError")return!1;if($ instanceof TypeError&&$.message.toLowerCase().includes("fetch failed"))return!0;for(let J of[$,$.cause])if(J&&typeof J==="object"&&"code"in J){let Z=String(J.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(Z))return!0}return!1}function w$($,J,Z=500){if(J instanceof Y0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function O$($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let K=()=>{clearTimeout(B),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},B=setTimeout(()=>{J?.removeEventListener("abort",K),Z()},$);J?.addEventListener("abort",K,{once:!0})})}function AB($){return $ instanceof Y0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function Y8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function F8($){return C$("sha256").update($??"").digest("hex")}function j$($){return D8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function N8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var I$=20000,A$=1e4,C8=[2000,4000];class E2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class T${fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let K=new URL($);if(K.protocol!=="https:"&&K.hostname!=="127.0.0.1"&&K.hostname!=="localhost"&&K.hostname!=="[::1]"&&K.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=K.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=M8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new Y0($.status,Z,Q,K)}return J}async challenge($,J){let Z=this.proofOptions.challengeAttemptTimeoutsMs??C8;for(let Q of Z)try{return await this.challengeAttempt($,J,Q)}catch(K){if(J?.aborted||!(K instanceof E2))throw K}return await this.challengeAttempt($,J,null)}async challengeAttempt($,J,Z){let Q=JSON.stringify({device_id:$}),K=Z===null?null:new AbortController,B=K&&Z!==null?setTimeout(()=>K.abort(new E2(Z)),Z):null;try{let G=await this.fetchImpl(`${this.apiOrigin}${d.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:Q,signal:K?J?AbortSignal.any([J,K.signal]):K.signal:J});return L8(await this.parseResponse(G))}catch(G){if(!J?.aborted&&K?.signal.aborted)throw K.signal.reason;throw G}finally{if(B)clearTimeout(B)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=I$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,C8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,K=!1,B){let G=B&&Date.parse(B.expires_at)-(this.proofOptions.now??Date.now)()>=A$?B:null,U=!G&&K?await this.takeSpareChallenge(Z.deviceId):null,W=G??U??await this.challenge(Z.deviceId,Q);if(K)this.refillSpareChallenge(Z.deviceId);let Y=F8(J),X=this.signProof("POST",$,W.challenge,Y);return{"x-device-id":Z.deviceId,"x-device-timestamp":X.timestamp,"x-device-nonce":X.nonce,"x-device-challenge":W.challenge,"x-device-body-sha256":Y,"x-device-signature":X.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>H$(24)))();if(B.byteLength<16||B.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(B).toString("base64url"),U=this.proofStore.sign(j$({method:$,route:J,timestamp:K,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:K,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!H8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new q2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",E1,Q,F8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&Y8(J.body)>N0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??O$,W=this.sessionFor($,J.device),Y;for(let X=0;X<G;X+=1)try{let F=await W?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(F)return await this.parseResponse(new Response(F.status===204?null:F.body,{status:F.status,headers:F.retryAfter===null?{}:{"retry-after":F.retryAfter}}));let C=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,J.signal,J.useSpareChallenge===!0&&X===0,X===0?J.issuedChallenge:void 0),N=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...C,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,signal:J.signal});return await this.parseResponse(N)}catch(F){if(Y=F,J.signal?.aborted)throw F;let C=J.device!==void 0&&F instanceof Y0&&F.status===401&&["invalid_device_proof","device_proof_replayed"].includes(F.code),N=F instanceof Y0&&M$(F.status),D=L$(F),w=J.transientRetryOwner!=="caller"&&(N||D);if((C||w)&&X+1<G){let M=C?0:w$(X,F,this.proofOptions.retryBaseDelayMs??500);if(M>0)await U(M,J.signal);continue}if(C&&X+1>=G)throw Error("Reason Device proof retry was exhausted.");throw F}throw Y??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(d.register,{authorization:$,body:J,signal:Z});return w8(Q)}async enroll($,J,Z,Q){let K=await this.request(d.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return O8(K)}async heartbeat($,J,Z,Q){let K=await this.request(d.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return j8(K)}async syncRoots($,J,Z){let Q=await this.request(d.rootsSync,{device:$,body:{roots:J},signal:Z});return I8(Q)}async identity($,J){let Z=await this.request(d.identity,{device:$,signal:J});return A8(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(d.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return T8(K)}async deviceLifecycle($,J,Z){let Q=await this.request(d.lifecycle,{device:$,body:J,signal:Z});R8(Q)}async localSubscription($,J,Z){return _8(await this.request(d.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(d.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(d.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(d.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof Y0&&K.status===404)return null;throw K});if(Q===null)return null;if(!N8(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(d.operationClaim,{device:$,body:Q(30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,g1))},signal:J.signal});if(B===null)return null;return P8(B,g2)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(d.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(G){if(!K||!(G instanceof Y0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return z8(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!N8(K.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(d.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return q8(Q)}async completeOperation($,J,Z,Q){let K={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(Y8(K)>N0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(d.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return g8(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-tv4wtdb2.js");return Q.parse(await this.request(d.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let K=await this.request(d.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return E8(K)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(d.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var _$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),J1=new Set(["jobs.control","environment.install","tunnel.open","tunnel.close","display.stream.v1","automation.call.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"]);function S1($,J){if(_$.has($))return!1;if(J1.has($)&&!J.runtimeDirectory)return!1;if(($==="inference.custom.v1"||$==="preview.serve.v1"||$==="simulator.call.v1"||$==="simulator.stream.v1")&&(J.executionMode!=="unsandboxed"||!J.runtimeDirectory))return!1;if(J.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes($)||J1.has($)))return!1;return!0}import{accessSync as R$,constants as P$,existsSync as z$,statSync as q$}from"fs";import{basename as E$,isAbsolute as g$}from"path";var Z1=["-lic"],S$="/bin/zsh",k$=new Set(["zsh","bash"]),S8=20000,S2=60000,f$=65536,b$=64,x$=8192,y$=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),h$=["DYLD_","LD_"];function m$($){let J=$.toUpperCase();return y$.has(J)||h$.some((Z)=>J.startsWith(Z))}function k8($=process.env){return!0}function v$($){if(!g$($)||$.includes("\x00"))return!1;if(!k$.has(E$($)))return!1;try{if(!q$($).isFile())return!1;return R$($,P$.X_OK),!0}catch{return!1}}function E0($=process.env){let J=$.SHELL?.trim();if(J&&v$(J))return J;return S$}function k2($=process.env){return k8($)&&z$(E0($))}function f2($=process.env){if(!k8($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function b2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>f$)throw new H("invalid_payload","command is missing or too large.");return $}function x2($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>b$)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[K,B]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(K)||typeof B!=="string"||B.includes("\x00")||Buffer.byteLength(B,"utf8")>x$)throw new H("invalid_payload","env entry is invalid or too large.");if(m$(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function f8($){let J=$.processEnv??process.env;if(f2(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=b2($.command),Q=E0(J),{forwarded:K,ignored:B}=x2($.requestEnv),G=await $.spawn(Q,[...Z1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...K}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...Z1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function b8($=process.env){return{transport:"shell",shell:`${E0($)} ${Z1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:S2}}import{readFile as p$,readdir as u$,readlink as d$,realpath as l$}from"fs/promises";import{basename as s$,relative as c$,sep as n$}from"path";var w0="/proc",r$=250,x8=500,a$=50,i$=250,o$=1024,y8=4096,t$=1,e$=3,h8=9,$J="0A",JJ=/^socket:\[(\d+)\]$/,y2={readDirectory:($)=>u$($),readLink:($)=>d$($),readTextFile:($)=>p$($,"utf8"),realPath:($)=>l$($)};function v8($,J){return J===$||J.startsWith(`${$}${n$}`)}function ZJ($,J){return c$($,J)||"."}async function p8($){let J;try{J=await $.readDirectory(w0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function u8($,J){try{let Q=(await J.readTextFile(`${w0}/${$}/comm`)).slice(0,y8).split(`
|
|
26
|
+
`:"")+K.toString("utf8")}}}async function Q8($,J){if(!_2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=J8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=A2(Q.script_gzip),B=A2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=r9(Z8(e9(),"reason-workspace-setup-"));try{let U=Z8(G,"setup.sh");i9(U,K,{mode:384});let W={PATH:$$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let E of J$)if(process.env[E])W[E]=process.env[E];Object.assign(W,Q.env);let Y=n9("/bin/bash",[U],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),X=T2(e0),F=T2(e0),C=T2(e0);Y.stdout.on("data",(E)=>{X.push(E),C.push(E)}),Y.stderr.on("data",(E)=>{F.push(E),C.push(E)}),Y.stdin.on("error",()=>{}),Y.stdin.end(B);let N=(E)=>{try{if(Y.pid)process.kill(-Y.pid,E)}catch{}},D=!1,w,M=()=>{N("SIGTERM"),w??=setTimeout(()=>N("SIGKILL"),Z$)},I=setTimeout(()=>{D=!0,M()},Q.timeout_ms);J.addEventListener("abort",M,{once:!0});let O=await new Promise((E,v)=>{Y.once("error",()=>v(new H("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(j,q)=>E({code:j,signal:q}))}).finally(()=>{clearTimeout(I),clearTimeout(w),J.removeEventListener("abort",M)});await new Promise((E)=>{let v=setTimeout(E,Q$);Y.once("close",()=>{clearTimeout(v),E()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let R=D?124:O.signal?128+(o9.signals[O.signal]??0):O.code??1;return{exit_code:Math.min(255,R),stdout:X.text(),stderr:F.text(),...R!==0?{combined:C.text()}:{}}}finally{a9(G,{recursive:!0,force:!0})}}import{chmodSync as K$,mkdtempSync as B$,realpathSync as G8,rmSync as V$}from"fs";import{tmpdir as G$}from"os";import{dirname as U$,join as R2,sep as X$}from"path";function P2($){return V8($,B8($)!==null).repoPath}function U8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[$1,void 0].map((K)=>U$(K8({kind:"managed",workspaceId:J,...K?{layout:K}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let K of Z)try{Q=G8(R2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${X$}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function X8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=P2($.runtimeRoot);if(L0(Q)||L0(R2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return q0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=B$(R2(G$(),`reason-cloud-copy-${process.pid}-`));try{K$(Z,448);let Q=G8(Z);await q0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let K=await q0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(K.size_bytes!==J.size_bytes||K.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return K}finally{V$(Z,{recursive:!0,force:!0})}}import{constants as A0}from"fs";import{closeSync as L7,existsSync as G0,fstatSync as w7,lstatSync as O7,mkdirSync as mZ,mkdtempSync as j7,openSync as I7,readSync as vZ,realpathSync as J0,rmSync as A7,statSync as N1,writeSync as pZ}from"fs";import{homedir as W1,platform as l,tmpdir as T7}from"os";import{dirname as Y1,isAbsolute as uZ,join as T3,relative as L3,resolve as dZ,sep as lZ}from"path";import{spawn as sZ}from"child_process";import{createHash as C$,randomBytes as H$}from"crypto";var z2=30000,W$=1800000,Y$=5000,q1=30000,F$=g1+15000,W8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,N$=[/^\/app\/local-runtime\/operations\/claim$/,W8];class q2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((W)=>Q.pending.set(K,{path:$,resolve:W}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(N$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},F$);else{let W=()=>{if(!Q.pending.has(K))return;let Y=this.now()-Q.lastFrameAt;if(Y>=q1)this.drop(Q);else G=setTimeout(W,q1-Y)};G=setTimeout(W,q1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((W,Y)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>q1)this.drop(Q);Y(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),B.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([B,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(Y$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(W$,z2*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+J/2+this.jitter(J/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let $=this.options.WebSocket??globalThis.WebSocket;if(!$){this.retryAt=Number.POSITIVE_INFINITY;return}let J=new URL(E1,this.options.apiOrigin);J.protocol=J.protocol==="https:"?"wss:":"ws:",J.searchParams.set("device_id",this.options.deviceId);let Z;try{Z=new $(J.toString())}catch{this.failures+=1,this.retryAt=this.now()+z2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(K)=>this.receive(Q,K.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[K,B]of Q.pending){if(!W8.test(B.path))continue;Q.pending.delete(K),this.send(Q,{t:"abort",id:K}),B.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(z2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var g2=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function IB($,J={}){let Z=D$($),Q=J.rootPathsSupported===!0?D1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((K)=>/^[a-f0-9]{64}$/.test(K))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function D$($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[G,U]of Object.entries(K).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[G]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class Y0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}function M$($){return $===408||$===429||$===500||$===502||$===503||$===504}function L$($){if($ instanceof Y0)return!1;if(!($ instanceof Error))return!1;if($.name==="AbortError")return!1;if($ instanceof TypeError&&$.message.toLowerCase().includes("fetch failed"))return!0;for(let J of[$,$.cause])if(J&&typeof J==="object"&&"code"in J){let Z=String(J.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(Z))return!0}return!1}function w$($,J,Z=500){if(J instanceof Y0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function O$($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let K=()=>{clearTimeout(B),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},B=setTimeout(()=>{J?.removeEventListener("abort",K),Z()},$);J?.addEventListener("abort",K,{once:!0})})}function AB($){return $ instanceof Y0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function Y8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function F8($){return C$("sha256").update($??"").digest("hex")}function j$($){return D8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function N8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var I$=20000,A$=1e4,C8=[2000,4000];class E2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class T${fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let K=new URL($);if(K.protocol!=="https:"&&K.hostname!=="127.0.0.1"&&K.hostname!=="localhost"&&K.hostname!=="[::1]"&&K.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=K.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=M8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new Y0($.status,Z,Q,K)}return J}async challenge($,J){let Z=this.proofOptions.challengeAttemptTimeoutsMs??C8;for(let Q of Z)try{return await this.challengeAttempt($,J,Q)}catch(K){if(J?.aborted||!(K instanceof E2))throw K}return await this.challengeAttempt($,J,null)}async challengeAttempt($,J,Z){let Q=JSON.stringify({device_id:$}),K=Z===null?null:new AbortController,B=K&&Z!==null?setTimeout(()=>K.abort(new E2(Z)),Z):null;try{let G=await this.fetchImpl(`${this.apiOrigin}${d.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:Q,signal:K?J?AbortSignal.any([J,K.signal]):K.signal:J});return L8(await this.parseResponse(G))}catch(G){if(!J?.aborted&&K?.signal.aborted)throw K.signal.reason;throw G}finally{if(B)clearTimeout(B)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=I$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,C8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,K=!1,B){let G=B&&Date.parse(B.expires_at)-(this.proofOptions.now??Date.now)()>=A$?B:null,U=!G&&K?await this.takeSpareChallenge(Z.deviceId):null,W=G??U??await this.challenge(Z.deviceId,Q);if(K)this.refillSpareChallenge(Z.deviceId);let Y=F8(J),X=this.signProof("POST",$,W.challenge,Y);return{"x-device-id":Z.deviceId,"x-device-timestamp":X.timestamp,"x-device-nonce":X.nonce,"x-device-challenge":W.challenge,"x-device-body-sha256":Y,"x-device-signature":X.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>H$(24)))();if(B.byteLength<16||B.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(B).toString("base64url"),U=this.proofStore.sign(j$({method:$,route:J,timestamp:K,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:K,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!H8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new q2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",E1,Q,F8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&Y8(J.body)>N0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??O$,W=this.sessionFor($,J.device),Y;for(let X=0;X<G;X+=1)try{let F=await W?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(F)return await this.parseResponse(new Response(F.status===204?null:F.body,{status:F.status,headers:F.retryAfter===null?{}:{"retry-after":F.retryAfter}}));let C=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,J.signal,J.useSpareChallenge===!0&&X===0,X===0?J.issuedChallenge:void 0),N=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...C,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,signal:J.signal});return await this.parseResponse(N)}catch(F){if(Y=F,J.signal?.aborted)throw F;let C=J.device!==void 0&&F instanceof Y0&&F.status===401&&["invalid_device_proof","device_proof_replayed"].includes(F.code),N=F instanceof Y0&&M$(F.status),D=L$(F),w=J.transientRetryOwner!=="caller"&&(N||D);if((C||w)&&X+1<G){let M=C?0:w$(X,F,this.proofOptions.retryBaseDelayMs??500);if(M>0)await U(M,J.signal);continue}if(C&&X+1>=G)throw Error("Reason Device proof retry was exhausted.");throw F}throw Y??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(d.register,{authorization:$,body:J,signal:Z});return w8(Q)}async enroll($,J,Z,Q){let K=await this.request(d.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return O8(K)}async heartbeat($,J,Z,Q){let K=await this.request(d.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return j8(K)}async syncRoots($,J,Z){let Q=await this.request(d.rootsSync,{device:$,body:{roots:J},signal:Z});return I8(Q)}async identity($,J){let Z=await this.request(d.identity,{device:$,signal:J});return A8(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(d.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return T8(K)}async deviceLifecycle($,J,Z){let Q=await this.request(d.lifecycle,{device:$,body:J,signal:Z});R8(Q)}async localSubscription($,J,Z){return _8(await this.request(d.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(d.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(d.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(d.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof Y0&&K.status===404)return null;throw K});if(Q===null)return null;if(!N8(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(d.operationClaim,{device:$,body:Q(30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,g1))},signal:J.signal});if(B===null)return null;return P8(B,g2)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(d.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(G){if(!K||!(G instanceof Y0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return z8(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!N8(K.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(d.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return q8(Q)}async completeOperation($,J,Z,Q){let K={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(Y8(K)>N0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(d.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return g8(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-p2bvtf6p.js");return Q.parse(await this.request(d.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let K=await this.request(d.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return E8(K)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(d.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var _$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),J1=new Set(["jobs.control","environment.install","tunnel.open","tunnel.close","display.stream.v1","automation.call.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"]);function S1($,J){if(_$.has($))return!1;if(J1.has($)&&!J.runtimeDirectory)return!1;if(($==="inference.custom.v1"||$==="preview.serve.v1"||$==="simulator.call.v1"||$==="simulator.stream.v1")&&(J.executionMode!=="unsandboxed"||!J.runtimeDirectory))return!1;if(J.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes($)||J1.has($)))return!1;return!0}import{accessSync as R$,constants as P$,existsSync as z$,statSync as q$}from"fs";import{basename as E$,isAbsolute as g$}from"path";var Z1=["-lic"],S$="/bin/zsh",k$=new Set(["zsh","bash"]),S8=20000,S2=60000,f$=65536,b$=64,x$=8192,y$=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),h$=["DYLD_","LD_"];function m$($){let J=$.toUpperCase();return y$.has(J)||h$.some((Z)=>J.startsWith(Z))}function k8($=process.env){return!0}function v$($){if(!g$($)||$.includes("\x00"))return!1;if(!k$.has(E$($)))return!1;try{if(!q$($).isFile())return!1;return R$($,P$.X_OK),!0}catch{return!1}}function E0($=process.env){let J=$.SHELL?.trim();if(J&&v$(J))return J;return S$}function k2($=process.env){return k8($)&&z$(E0($))}function f2($=process.env){if(!k8($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function b2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>f$)throw new H("invalid_payload","command is missing or too large.");return $}function x2($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>b$)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[K,B]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(K)||typeof B!=="string"||B.includes("\x00")||Buffer.byteLength(B,"utf8")>x$)throw new H("invalid_payload","env entry is invalid or too large.");if(m$(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function f8($){let J=$.processEnv??process.env;if(f2(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=b2($.command),Q=E0(J),{forwarded:K,ignored:B}=x2($.requestEnv),G=await $.spawn(Q,[...Z1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...K}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...Z1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function b8($=process.env){return{transport:"shell",shell:`${E0($)} ${Z1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:S2}}import{readFile as p$,readdir as u$,readlink as d$,realpath as l$}from"fs/promises";import{basename as s$,relative as c$,sep as n$}from"path";var w0="/proc",r$=250,x8=500,a$=50,i$=250,o$=1024,y8=4096,t$=1,e$=3,h8=9,$J="0A",JJ=/^socket:\[(\d+)\]$/,y2={readDirectory:($)=>u$($),readLink:($)=>d$($),readTextFile:($)=>p$($,"utf8"),realPath:($)=>l$($)};function v8($,J){return J===$||J.startsWith(`${$}${n$}`)}function ZJ($,J){return c$($,J)||"."}async function p8($){let J;try{J=await $.readDirectory(w0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function u8($,J){try{let Q=(await J.readTextFile(`${w0}/${$}/comm`)).slice(0,y8).split(`
|
|
27
27
|
`,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${w0}/${$}/cmdline`)).slice(0,y8).split("\x00",1)[0]?.trim();return Q?s$(Q):null}catch{return null}}async function d8($,J=y2){let Z;try{Z=await J.readLink(`${w0}/${$}/cwd`)}catch{return null}if(!Z)return null;try{return await J.realPath(Z)}catch{return null}}async function l8($,J=y2){let Z=[];for(let Q of await p8(J)){if(Z.length>=r$)break;let K=await d8(Q,J);if(!K||!v8($,K))continue;Z.push({pid:Q,command:await u8(Q,J),cwd:ZJ($,K)})}return{processes:Z}}function m8($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function QJ($){let J=[];for(let W=0;W<16;W+=2)J.push($[W]<<8|$[W+1]);if(J.slice(0,5).every((W)=>W===0)&&J[5]===65535)return`::ffff:${$.slice(12).join(".")}`;let Z=-1,Q=0,K=-1;for(let W=0;W<=J.length;W+=1){if(W<J.length&&J[W]===0){if(K<0)K=W;continue}if(K>=0){let Y=W-K;if(Y>Q)Z=K,Q=Y;K=-1}}let B=J.map((W)=>W.toString(16));if(Q<2)return B.join(":");let G=B.slice(0,Z).join(":"),U=B.slice(Z+Q).join(":");return`${G}::${U}`}function KJ($,J){if(/^[0-9A-Fa-f]{8}$/.test($)){let Z=m8($);if(Z.every((Q)=>Q===0))return`*:${J}`;return`${Z.join(".")}:${J}`}if(/^[0-9A-Fa-f]{32}$/.test($)){let Z=[];for(let Q=0;Q<4;Q+=1)Z.push(...m8($.slice(Q*8,Q*8+8)));if(Z.every((Q)=>Q===0))return`*:${J}`;return`[${QJ(Z)}]:${J}`}return null}function BJ($,J){let Z=[];for(let Q of $.split(`
|
|
28
28
|
`).slice(1)){if(Z.length>=J)break;let K=Q.trim().split(/\s+/);if(K.length<=h8)continue;if(K[e$]?.toUpperCase()!==$J)continue;let B=K[t$]??"",G=B.lastIndexOf(":");if(G<0)continue;let U=Number.parseInt(B.slice(G+1),16);if(!Number.isInteger(U)||U<=0||U>65535)continue;let W=KJ(B.slice(0,G),U),Y=K[h8];if(!W||!Y||!/^[0-9]+$/.test(Y))continue;Z.push({inode:Y,port:U,address:W})}return Z}async function VJ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=x8)break;let Q;try{Q=await $.readTextFile(`${w0}/net/${Z}`)}catch{continue}J.push(...BJ(Q,x8-J.length))}return J}async function GJ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await p8(J)){if(Z.size>=$.size)break;let K;try{K=await J.readDirectory(`${w0}/${Q}/fd`)}catch{continue}for(let B of K.slice(0,o$)){let G;try{G=await J.readLink(`${w0}/${Q}/fd/${B}`)}catch{continue}let U=G.match(JJ)?.[1];if(!U||!$.has(U)||Z.has(U))continue;Z.set(U,Q)}}return Z}async function s8($,J=y2){let Z=await VJ(J),Q=await GJ(new Set(Z.map((X)=>X.inode)),J),K=[];for(let X of Z){let F=Q.get(X.inode);if(F===void 0)continue;K.push({pid:F,port:X.port,address:X.address})}K.sort((X,F)=>X.pid-F.pid||X.port-F.port||(X.address<F.address?-1:X.address>F.address?1:0));let B=[...new Set(K.map((X)=>X.pid))].slice(0,a$),G=await Promise.all(B.map(async(X)=>[X,await d8(X,J)])),U=new Map(G),W=K.filter((X)=>{let F=U.get(X.pid);return Boolean(F&&v8($,F))}),Y=new Map(await Promise.all([...new Set(W.map((X)=>X.pid))].map(async(X)=>[X,await u8(X,J)])));return{ports:W.slice(0,i$).map((X)=>({pid:X.pid,command:Y.get(X.pid)??null,address:X.address}))}}import{posix as m2}from"path";var k1=200,UJ=250,XJ=250;async function f1($,J){let Z=await $(J);if(Z.timedOut||Z.truncated||Z.exitCode!==0&&Z.exitCode!==1)throw new H("process_inspection_failed","Reading this Mac's processes did not complete.");let Q=[],K=null;for(let B of Z.stdout.split(/\r?\n/))if(B.startsWith("p")){let G=Number(B.slice(1));if(K=Number.isInteger(G)&&G>0?{pid:G,command:null,names:[]}:null,K)Q.push(K)}else if(K&&B.startsWith("c"))K.command=B.slice(1)||null;else if(K&&B.startsWith("n"))K.names.push(B.slice(1));return Q}function h2($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var c8="/System/Volumes/Data",WJ=["/tmp","/var","/etc"];function v2($){let J=m2.normalize($);if(J.startsWith(`${c8}/`))J=J.slice(c8.length);return WJ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function n8($){return $&&m2.isAbsolute($)?v2($):null}async function r8($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=k1){let K=J.slice(Q,Q+k1).join(",");for(let B of await f1($,["-a","-p",K,"-d","cwd","-Fpcn"]))Z.set(B.pid,{command:B.command,cwd:n8(B.names[0])})}return Z}async function a8($,J){let Z=v2($),Q=(await f1(J,["-d","cwd","-Fpn"])).filter((B)=>{let G=n8(B.names[0]);return G!==null&&h2(Z,G)}).map((B)=>B.pid).slice(0,UJ),K=await r8(J,Q);return{processes:Q.flatMap((B)=>{let G=K.get(B);return G?.cwd&&h2(Z,G.cwd)?[{pid:B,command:G.command,cwd:m2.relative(Z,G.cwd)||"."}]:[]})}}async function i8($,J){let Z=v2($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],K=await f1(J,Q),B=await r8(J,K.map((Y)=>Y.pid)),G=K.map((Y)=>Y.pid).filter((Y)=>{let X=B.get(Y)?.cwd;return Boolean(X&&h2(Z,X))});if(G.length===0)return{ports:[]};let U=new Set(K.flatMap((Y)=>Y.names.map((X)=>`${Y.pid} ${X}`))),W=[];for(let Y=0;Y<G.length;Y+=k1){let X=G.slice(Y,Y+k1).join(",");for(let F of await f1(J,["-a","-p",X,...Q]))for(let C of F.names)if(U.has(`${F.pid} ${C}`))W.push({pid:F.pid,command:F.command,address:C})}return{ports:W.slice(0,XJ)}}import{join as AJ}from"path";import{spawn as MJ}from"child_process";import{randomUUID as LJ}from"crypto";import{chmodSync as e8,lstatSync as $5,mkdirSync as wJ,readdirSync as OJ,statSync as jJ,unlinkSync as IJ}from"fs";import{join as u2}from"path";function Q1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var p2={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var b1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var O0=()=>{throw Error("proof_visual_contract_invalid")};class o8 extends Error{constructor(){super("proof_visual_contract_invalid")}}function FJ($){if(!Q1($)||$.version!==1)return O0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new o8;if(!Q1($.viewport)||!b1($.viewport.width,1,4096)||!b1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>p2.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return O0();let J=$.targets.map((Q)=>{if(!Q1(Q)||typeof Q.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(Q.id)||typeof Q.selector!=="string"||!Q.selector.trim()||Q.selector.length>256||/[\x00-\x1f\x7f]/.test(Q.selector)||Object.keys(Q).some((K)=>!["id","selector"].includes(K)))return O0();return{id:Q.id,selector:Q.selector}});if(new Set(J.map((Q)=>Q.id)).size!==J.length)return O0();let Z;if($.additionalViewports!==void 0){if(!Array.isArray($.additionalViewports)||$.additionalViewports.length<1||$.additionalViewports.length>3)return O0();Z=$.additionalViewports.map((K)=>{if(!Q1(K)||!b1(K.width,1,4096)||!Number.isInteger(K.width)||!b1(K.height,1,4096)||!Number.isInteger(K.height)||Object.keys(K).some((B)=>!["width","height"].includes(B)))return O0();return{width:K.width,height:K.height}});let Q=[$.viewport,...Z].map((K)=>`${K.width}x${K.height}`);if(new Set(Q).size!==Q.length)return O0()}return{version:1,route:$.route,viewport:{width:$.viewport.width,height:$.viewport.height},targets:J,...Z?{additionalViewports:Z}:{}}}var CJ=["organizationId","userId","sessionId","runId"],HJ=[...CJ,"prUrl","headSha","skillDigest","evidenceKind"],dB=[...HJ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var DJ={"image/png":{kind:"image",directory:"/tmp/ara-public-screenshots",extension:"png",maxBytes:8388608},"video/webm":{kind:"video",directory:"/tmp/ara-public-recordings",extension:"webm",maxBytes:10551296}};function t8($){return DJ[$].directory}var J5=10485760;function Z5($={}){let J=$.directory??t8("video/webm"),Z=null;return{async start(Q){if(Z)throw Error("cloud_browser_recording_active");let K=Q?.seconds;if(!Number.isInteger(K)||Number(K)<1||Number(K)>15||!Q||Object.keys(Q).some((M)=>M!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");wJ(J,{recursive:!0,mode:457});let B=$5(J);if(!B.isDirectory()||B.isSymbolicLink()||B.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");e8(J,457);let G=OJ(J).filter((M)=>/^[a-f0-9-]{36}\.webm$/.test(M)).map((M)=>({name:M,time:jJ(u2(J,M)).mtimeMs})).sort((M,I)=>I.time-M.time);for(let M of G.slice(9))IJ(u2(J,M.name));let U=u2(J,`${LJ()}.webm`),W=["-f","x11grab","-framerate","12","-i",$.display??":99"],Y=($.spawn??MJ)($.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...W,"-t",String(K),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(J5),"-progress","pipe:1",U],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),X,F,C=!1,N=new Promise((M,I)=>{X=M,F=I});Y.stdout.on("data",(M)=>{if(/frame=\s*[1-9]/.test(String(M)))C=!0,X()});let D=new Promise((M,I)=>{Y.once("error",()=>{F(Error("cloud_browser_recording_unavailable")),I(Error("cloud_browser_recording_unavailable"))}),Y.once("exit",(O)=>{try{if(O!==0&&O!==255)throw Error();let R=$5(U);if(!C||!R.isFile()||R.isSymbolicLink()||R.uid!==process.getuid?.()||R.size<128||R.size>J5+65536)throw Error();e8(U,420),X(),M({path:U,mimeType:"video/webm"})}catch{F(Error("cloud_browser_recording_failed")),I(Error("cloud_browser_recording_failed"))}})});D.catch(()=>{});let w=setTimeout(()=>Y.kill("SIGKILL"),(Number(K)+5)*1000);D.finally(()=>clearTimeout(w)).catch(()=>{}),Z={done:D,stop:()=>{return Y.kill("SIGINT"),D}};try{await N}catch(M){throw Z=null,M}return{recording:!0,seconds:Number(K)}},async stop(){if(!Z)throw Error("cloud_browser_recording_not_started");let Q=Z;return Z=null,Q.stop()},async close(){if(Z)await this.stop().catch(()=>{})}}}function B5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??Q5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let K=AJ($.runtimeDirectory,"recordings"),B=null;return{async start(G){let U=await(J.desktop??K5)();return B??=Z5({directory:K,display:U.display,ffmpeg:Q,env:{HOME:j1(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:U.xauthority},...J.spawn?{spawn:J.spawn}:{}}),B.start(G)},async stop(){if(!B)throw Error("cloud_browser_recording_not_started");return B.stop()},async close(){await B?.close()}}}import{spawn as G3}from"child_process";import{createHash as mJ,randomUUID as vJ}from"crypto";import{existsSync as Q0,mkdirSync as Z3,mkdtempSync as U3,readdirSync as d1,readFileSync as X3,renameSync as pJ,rmSync as V1,statSync as m1,writeFileSync as uJ}from"fs";import{homedir as W3,tmpdir as _5}from"os";import{basename as R5,dirname as Q3,join as g,relative as P5,resolve as K3,sep as z5}from"path";var o=V.string().min(1).max(200),Z0=V.number().finite().min(0).max(1e4),x1=V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),V5=V.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),l2=V.object({id:V.string().min(1).max(500).optional(),label:V.string().min(1).max(500).optional()}).strict(),s2=["home","lock","side_button","siri","apple_pay"],TJ=V.enum(["tree","screenshot","both","none"]),_J=V.object({...l2.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),C0={observe:TJ.optional(),wait_for:_J.optional(),timeout:V.number().min(0).max(20).optional()},d2=V.discriminatedUnion("action",[V.object({action:V.literal("tap"),x:Z0.optional(),y:Z0.optional(),...l2.shape,duration:V.number().min(0).max(10).optional()}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional()}).strict(),V.object({action:V.literal("type"),text:V.string().min(1).max(4000)}).strict(),V.object({action:V.literal("button"),name:V.enum(s2)}).strict(),V.object({action:V.literal("sleep"),seconds:V.number().min(0).max(10)}).strict()]),c2=V.discriminatedUnion("action",[V.object({action:V.literal("devices")}).strict(),V.object({action:V.literal("boot"),device:o}).strict(),V.object({action:V.literal("shutdown"),device:o}).strict(),V.object({action:V.literal("build"),path:x1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:o.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("run"),path:x1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:o.optional(),steps:V.array(V.lazy(()=>d2)).max(30).optional(),...C0}).strict(),V.object({action:V.literal("build_status"),build_id:V.string().regex(/^build-[0-9a-z-]{4,64}$/),device:o.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("launch"),device:o.optional(),app_path:x1.optional(),bundle_id:V5.optional(),steps:V.array(V.lazy(()=>d2)).max(30).optional(),...C0}).strict().refine(($)=>Boolean($.app_path)!==Boolean($.bundle_id),"pass exactly one of app_path or bundle_id"),V.object({action:V.literal("terminate"),device:o.optional(),bundle_id:V5}).strict(),V.object({action:V.literal("logs"),device:o.optional(),after:V.number().int().min(0).optional()}).strict(),V.object({action:V.literal("screenshot"),device:o.optional(),scale:V.union([V.literal(1),V.literal(2)]).optional(),save_path:x1.optional()}).strict(),V.object({action:V.literal("chrome"),device:o.optional()}).strict(),V.object({action:V.literal("inspect"),device:o.optional()}).strict(),V.object({action:V.literal("tap"),device:o.optional(),x:Z0.optional(),y:Z0.optional(),...l2.shape,duration:V.number().min(0).max(10).optional(),...C0}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),device:o.optional(),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional(),...C0}).strict(),V.object({action:V.literal("type"),device:o.optional(),text:V.string().min(1).max(4000),...C0}).strict(),V.object({action:V.literal("button"),device:o.optional(),name:V.enum(s2),...C0}).strict(),V.object({action:V.literal("open_url"),device:o.optional(),url:V.string().min(1).max(4000),...C0}).strict(),V.object({action:V.literal("steps"),device:o.optional(),steps:V.array(d2).min(1).max(30),...C0}).strict(),V.object({action:V.literal("appearance"),device:o.optional(),mode:V.enum(["light","dark"])}).strict()]),G5=V.object({udid:V.string(),name:V.string(),runtime:V.string(),state:V.enum(["booted","shutdown","booting","shutting_down"]),kind:V.enum(["iphone","ipad","other"])}).strict(),UV=V.object({text:V.string(),error:V.string().optional(),device:G5.optional(),devices:V.array(G5).optional(),image:V.object({mime:V.literal("image/jpeg"),data:V.string(),width:V.number(),height:V.number()}).strict().optional(),build:V.object({id:V.string(),status:V.enum(["running","succeeded","failed"]),app_path:V.string().optional(),bundle_id:V.string().optional(),errors:V.array(V.string()),log_tail:V.string(),elapsed_ms:V.number()}).strict().optional(),logs:V.object({lines:V.array(V.string()),next:V.number()}).strict().optional(),screen:V.string().optional(),chrome:V.object({identifier:V.string(),screen:V.object({width:V.number(),height:V.number()}).strict(),inset:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),padding:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),screen_mask:V.string().optional(),pieces:V.record(V.enum(["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"]),V.object({image:V.string(),width:V.number(),height:V.number()}).strict()),buttons:V.array(V.object({name:V.string(),image:V.string(),x:V.number(),y:V.number(),width:V.number(),height:V.number()}).strict())}).strict().optional()}).strict();var XV=V.object({device_id:V.uuid().optional(),root_id:V.uuid().optional()}),WV={type:"object",properties:{action:{type:"string",enum:c2.options.map(($)=>$.shape.action.value).filter(($)=>$!=="chrome")},device_id:{type:"string",format:"uuid",description:"Reason machine id from devices.list; omit for the machine this Session runs on."},root_id:{type:"string",format:"uuid"},device:{type:"string",description:"Simulator UDID or exact name; omit for the booted one."},path:{type:"string",description:"build or run: a .xcodeproj, .xcworkspace, or a folder holding one (project.yml is generated with XcodeGen), absolute or relative to the Session's folder. Omit it when the folder holds one app project."},scheme:{type:"string"},configuration:{type:"string"},build_id:{type:"string"},app_path:{type:"string",description:"launch: the built .app from build_status."},bundle_id:{type:"string"},after:{type:"integer",minimum:0,description:"logs: only lines after this sequence number."},x:{type:"number"},y:{type:"number"},x2:{type:"number"},y2:{type:"number"},id:{type:"string",description:"tap: accessibility identifier from inspect."},label:{type:"string",description:"tap: accessibility label from inspect."},duration:{type:"number",description:"tap: seconds held (above 0.5 is a long press); swipe: seconds."},text:{type:"string"},name:{type:"string",enum:[...s2]},url:{type:"string"},mode:{type:"string",enum:["light","dark"]},steps:{type:"array",maxItems:30,description:"steps (or launch): run in order in one call (after launch, once the app is up). Each item is {action:'tap', id|label|x,y} | {action:'swipe', x,y,x2,y2} | {action:'type', text} | {action:'button', name} | {action:'sleep', seconds}. Taps by id or label wait for their element to appear.",items:{type:"object"}},observe:{type:"string",enum:["tree","screenshot","both","none"],description:"After tap, swipe, type, button, open_url, launch or steps: what to return about the settled screen. Default tree (the accessibility tree, so no separate inspect is needed); screenshot or both to see it."},wait_for:{type:"object",description:"After the action, wait until this element is on screen: {id} or {label}; add gone:true to wait for it to disappear.",properties:{id:{type:"string"},label:{type:"string"},gone:{type:"boolean"}},additionalProperties:!1},timeout:{type:"number",description:"Seconds to wait for wait_for (default 5, max 20)."},wait:{type:"boolean",description:"build or build_status: wait for the build to finish (up to ~45 s) instead of returning at once."},save_path:{type:"string",description:"screenshot: also save the full-resolution PNG at this path (absolute or relative to the Session's folder), for example to show the user."}},required:["action"],additionalProperties:!1};import{spawn as i2}from"child_process";import{createHash as PJ}from"crypto";import{existsSync as r2,mkdirSync as y1,mkdtempSync as zJ,readdirSync as U5,readFileSync as X5,renameSync as qJ,rmSync as W5,symlinkSync as a2,writeFileSync as K1}from"fs";import{homedir as EJ}from"os";import{dirname as C5,join as b}from"path";import{createInterface as gJ}from"readline";var n2=`// Reason's simulator host: one warm process per booted iOS Simulator.
|
|
29
29
|
//
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var r={name:"github-native-engineer-device-worker-production",version:"0.2.
|
|
3
|
-
export{r as
|
|
2
|
+
var r={name:"github-native-engineer-device-worker-production",version:"0.2.296",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
|
+
export{r as Ch};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Kb as j,Lb as q}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Kb as j,Lb as q}from"./vm-hands-entry-lite-ya1a2eep.js";function y(v=process.platform){if(j(),v==="linux")q("strict")}
|
|
3
3
|
export{y as t};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
export{Q as
|
|
2
|
+
import{hh as X,jh as Y,lh as Z}from"./vm-hands-entry-lite-yp315y25.js";import{execFileSync as z}from"child_process";import{existsSync as V,realpathSync as M}from"fs";import{userInfo as D}from"os";import{isAbsolute as $,join as C,normalize as F,parse as K}from"path";function Q(){let q=F(D().homedir);if(!$(q)||q===K(q).root)throw Error("Could not resolve the canonical macOS user home.");return q}function O(q,B,J=Q()){let L=Z(B);if(B.kind==="managed"&&B.base){let G=M(J);return{anchor:G,boundary:C(G,B.base),path:C(G,L)}}if(B.kind==="root"&&Y(B.path)){let G=M(J);return{anchor:G,boundary:C(G,X),path:C(G,L)}}return{anchor:q,boundary:q,path:C(q,L)}}function _(q=Q()){return C(q,".config")}function b(){if(process.platform!=="darwin")return null;try{let q=z("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return $(q)?M(q):null}catch{return null}}function g(q=Q()){let B=C(q,"Library","Application Support","Ara"),J=C(q,"Library","Application Support","Reason");return V(B)&&!V(J)?B:J}
|
|
3
|
+
export{Q as _g,O as $g,_ as ah,b as bh,g as ch};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
var j=Object.create;var{getPrototypeOf:k,defineProperty:f,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,s=(a,b,c)=>{var g=a!=null&&typeof a==="object";if(g){var h=b?o??=new WeakMap:p??=new WeakMap,i=h.get(a);if(i)return i}c=a!=null?j(k(a)):{};let d=b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c;for(let e of l(a))if(!m.call(d,e))f(d,e,{get:n.bind(a,e),enumerable:!0});if(g)h.set(a,d);return d};var t=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var q=(a)=>a;function r(a,b){this[a]=q.bind(null,b)}var u=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:r.bind(b,c)})};var v=import.meta.require;
|
|
3
|
-
export{s as
|
|
3
|
+
export{s as Lh,t as Mh,u as Nh,v as Oh};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Zg as c}from"./vm-hands-entry-lite-pr65ksfz.js";var g={REASON_API_KEY:"ARA_API_KEY",REASON_API_URL:"ARA_API_URL",REASON_CLI_CHANNEL:"ARA_CLI_CHANNEL",REASON_CLI_LAUNCHER_PATH:"ARA_CLI_LAUNCHER_PATH",REASON_MANAGED_RUNTIME_ROOT:"ARA_MANAGED_RUNTIME_ROOT",REASON_INSTALL_ALIAS_PATH:"ARA_INSTALL_ALIAS_PATH",REASON_INSTALL_DIR:"ARA_INSTALL_DIR",REASON_INSTALL_METHOD:"ARA_INSTALL_METHOD",REASON_INSTALL_PINNED_VERSION:"ARA_INSTALL_PINNED_VERSION",REASON_INSTALL_UPGRADE:"ARA_INSTALL_UPGRADE"},g0=Object.values(g),jZ=new Set;function MQ(Q,Z){let $=Q[Z];if($?.trim())return $;let X=Q[g[Z]];if(X?.trim())jZ.add(g[Z]);return X}function KZ(Q,Z){return{[Q]:Z,[g[Q]]:Z}}import{basename as BZ}from"path";var i=["production","staging"],OZ="https://api.reasonmachines.com",kZ="https://staging-api.reasonmachines.com";var l={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},AZ=new Set(["ara-staging","reason-staging"]);function KQ(Q={}){let Z=MQ(Q.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(Z){if(i.includes(Z))return Z;throw Error(`Unknown Reason CLI channel: ${Z}`)}let $=BZ(Q.executablePath??process.execPath).toLowerCase();return AZ.has($)?"staging":"production"}function h(Q){return Q==="staging"?kZ:OZ}function y0(Q){return`${h(Q)}/mcp/ara`}var BQ={production:["https://api.ara.so",l.production.api],staging:["https://api-staging.ara.so",l.staging.api]};function jQ(Q){let Z;try{Z=new URL(Q).origin}catch{return Q}let $=i.find((X)=>BQ[X].includes(Z));return $?h($):Z}function p0(Q,Z){return Q===Z||jQ(Q)===jQ(Z)}function OQ(Q,Z){return i.some(($)=>BQ[$].includes(Q)&&Z===h($))}function u0(Q,Z){try{let $=new URL(Z);return!$.username&&!$.password&&($.origin===h(Q)||$.origin===l[Q].api)}catch{return!1}}function d0(Q){try{let Z=new URL(Q).hostname.replace(/^\[|\]$/g,"").toLowerCase();return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}import{randomBytes as xQ}from"crypto";import{chmodSync as LQ,closeSync as FQ,constants as _Z,linkSync as bQ,lstatSync as x,mkdirSync as fQ,openSync as NZ,readdirSync as P,readFileSync as TQ,readlinkSync as D,renameSync as N,rmdirSync as CQ,symlinkSync as _,unlinkSync as B}from"fs";import{createRequire as xZ}from"module";import{constants as LZ}from"os";import{basename as f,join as U,sep as bZ}from"path";import{existsSync as m,lstatSync as AQ,readdirSync as PZ,readFileSync as FZ,readlinkSync as TZ,realpathSync as DZ}from"fs";import{join as K,sep as RZ}from"path";function o(Q,...Z){let $=K(Q,"ara"),X=K(Q,"reason");if(!v($))return K(X,...Z);if(!m(X))return K($,...Z);return m(K($,...Z))&&!m(K(X,...Z))?K($,...Z):K(X,...Z)}function v(Q){try{let Z=AQ(Q);if(!Z.isSymbolicLink())return Z.isDirectory();return TZ(Q)!=="reason"&&m(Q)}catch{return!1}}function PQ(Q,Z=[]){if(!v(Q))return!1;let $;try{$=[Q,...PZ(Q,{withFileTypes:!0}).filter((X)=>X.isDirectory()).map((X)=>K(Q,X.name))]}catch{return!1}return $.some((X)=>["connect","connect-once"].filter((z)=>!Z.includes(K(X,z))).some((z)=>{let W=K(X,z,"worker.json");try{AQ(W)}catch{return!1}try{let q=JSON.parse(FZ(W,"utf8"))?.stateDirectory;if(typeof q!=="string")return!0;let V=(J,w)=>J===w||J.startsWith(w+RZ);return V(q,Q)||V(kQ(q),kQ(Q))}catch{return!0}}))}function kQ(Q){try{return DZ(Q)}catch{return Q}}var u=new Set(["credentials.json","local-device.json","local-device.revoked.json","local-device.auth-migration.json","local-device.json.registration-pending.json","local-daemon.json","local-daemon.json.workspaces.json","local-root-fingerprint-key.json","instances","workspaces"]),n=new Set(["local-device.proxy.json"]),fZ=new Set(["local-device.key","local-device.binding"]),DQ=new Map;function r(Q,Z,$){let X=U(Q,"ara");if(/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(Q))return{state:G(X)?.isDirectory()?"kept":"absent"};return EQ(X,U(Q,"reason"),{linkAlways:!0,kept:(z)=>PQ(z,$??[]),native:Z===void 0?pQ:()=>Z},$!==void 0)}function SQ(Q,...Z){return r(Q),o(Q,...Z)}function z1(Q,Z=process.platform){let $=U(Q,"Library","Logs");if(Z==="darwin")for(let X of[""," Staging"," Development"])EQ(U($,`Ara${X}`),U($,`Reason${X}`),{linkAlways:!1,kept:()=>!1,native:pQ});return U($,"Reason")}var IQ="config_rename_unavailable:busy";function EQ(Q,Z,$,X=!1){let z=X?void 0:DQ.get(Q);if(z)return z;let W;try{W=CZ(Q,Z,$)}catch(q){let V=`config_rename_unavailable:${A(q)??"failed"}`;try{return{state:G(Q)?.isDirectory()?"kept":"absent",problem:V}}catch{return{state:"kept",problem:V}}}if(!(W.state==="absent"&&$.linkAlways)&&W.problem!==IQ&&!(W.state==="kept"&&!W.problem))DQ.set(Q,W);return W}function CZ(Q,Z,$){IZ(Z,$.native);let X=!1;for(let z=0;z<8;z+=1){let W=G(Q);if(W?.isSymbolicLink())return D(Q)===f(Z)?{state:X?"renamed":"linked"}:{state:"kept"};if(!W){if(p(Z))M(()=>B(Z),"ENOENT");if(!(X||$.linkAlways)||!R(Z))return{state:"absent"};let J=b(Z,"link");_(f(Z),J);try{M(()=>N(J,Q),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{M(()=>B(J),"ENOENT")}continue}if(!W.isDirectory())return{state:"absent"};if($.kept(Q))return RQ(Z),{state:"kept"};let q=$.native();if(!q)return RQ(Z),{state:"kept",problem:"config_rename_unavailable:no_native"};let V=EZ(q,Q);if(!V)return{state:"kept",problem:IQ};try{if(x(Q).isSymbolicLink())continue;let J=SZ(q,Q,Z);if(J)return{state:"kept",problem:J};X=!0}finally{V()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function SZ(Q,Z,$){let X=G($);if(!X||p($)){if(!X)_(f($),$);try{Q.exchange(Z,$)}catch(J){if(p($))M(()=>B($),"ENOENT");return`config_rename_unavailable:${A(J)??"exchange_failed"}`}return null}if(!X.isDirectory())return"config_rename_unavailable:ENOTDIR";if(X.dev!==x(Z).dev)return"config_rename_unavailable:EXDEV";let z=[b($,"probe"),b($,"probe")];try{_("a",z[0]),_("b",z[1]),Q.exchange(z[0],z[1])}catch(J){return`config_rename_unavailable:${A(J)??"exchange_failed"}`}finally{for(let J of z)M(()=>B(J),"ENOENT")}let W=yQ($);for(let J of fZ){let w=G(U($,J)),j=G(U(Z,J));if(w&&j&&w.ino!==j.ino)fQ(`${W}-replaced`,{mode:448,recursive:!0}),N(U($,J),U(`${W}-replaced`,J))}let q={linked:new Map,unitsKept:new Set};gQ(Z,$,"",q);let V=b($,"rename");_(f($),V);try{Q.exchange(Z,V)}catch(J){return M(()=>B(V),"ENOENT"),`config_rename_unavailable:${A(J)??"exchange_failed"}`}return hQ(V,$,q,W),null}function t(Q){return Q===""||!Q.includes(bZ)}function gQ(Q,Z,$,X){let z=t($)&&y(U(Z,$),U(Q,$));if(z)X.unitsKept.add($);for(let W of P(U(Q,$))){if(z&&(u.has(W)||n.has(W)))continue;let q=U($,W),V=U(Q,q),J=U(Z,q),w=G(V);if(!w)continue;let j=G(J);if(w.isDirectory()){if(!j)M(()=>fQ(J,{mode:w.mode&4095}),"EEXIST"),LQ(J,w.mode&4095);if(R(J))gQ(Q,Z,q,X)}else if(!j){if(w.isSymbolicLink())M(()=>_(D(V),J),"EEXIST");else if(M(()=>bQ(V,J),"EEXIST","ENOENT"))X.linked.set(q,w.ino)}}}function IZ(Q,Z){let $;try{if(!R(Q))return;$=P(Q)}catch{return}for(let X of $){let z=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(X);if(!z)continue;let W=U(Q,X),q=G(W);if(!q)continue;if(!q.isDirectory()){if(!_Q(Number(z[2])))M(()=>B(W),"ENOENT");continue}let V=Z(),J=null;if(V){try{J=V.lock(W)}catch{continue}if(!J)continue}else if(_Q(Number(z[2])))continue;try{let w=b(Q,"claim");if(M(()=>N(W,w),"ENOENT"))hQ(w,Q,null,yQ(Q))}finally{J?.()}}}function hQ(Q,Z,$,X){for(let[z,W]of $?.linked??[])if(!G(U(Q,z))&&G(U(Z,z))?.ino===W)M(()=>B(U(Z,z)),"ENOENT");if(mQ(Q,Z,"",$),M(()=>CQ(Q),"ENOTEMPTY","EEXIST"))return;N(Q,X),LQ(X,448)}function mQ(Q,Z,$,X){let z=t($)&&(X?X.unitsKept.has($):y(U(Z,$),U(Q,$)));for(let W of P(U(Q,$))){let q=U($,W),V=U(Q,q),J=U(Z,q),w=x(V),j=G(J);if(j&&w.ino===j.ino&&w.dev===j.dev){B(V);continue}if(w.isFile()&&j?.isFile()&&X?.linked.get(q)===j.ino){N(V,J);continue}if(z&&(u.has(W)||n.has(W)))continue;if(!j){if(w.isFile()){if(M(()=>bQ(V,J),"EEXIST"))B(V)}else M(()=>N(V,J),"EEXIST","ENOTEMPTY");continue}if(w.isDirectory()&&j.isDirectory())mQ(Q,Z,q,X),M(()=>CQ(V),"ENOTEMPTY","EEXIST")}}function W1(Q){let Z=U(Q,"ara"),$=U(Q,"reason");if(!R(Z)||!R($))return null;let X=["",...P(Z,{withFileTypes:!0}).filter((z)=>z.isDirectory()&&!z.name.startsWith(".")).map((z)=>z.name)];for(let z of X){let W=U(Z,z),q=U($,z);if(!y(W,q)||!y(q,W))continue;if([...u,...n].some((J)=>a(U(W,J),U(q,J))===!1))return z}return null}function q1(Q){let Z=U(Q,"ara"),$=U(Q,"reason");if(!R(Z)||!R($))return null;let X=(z)=>{for(let W of P(U(Z,z))){let q=U(z,W);if(t(z)&&(W==="connect"||W==="connect-once"))continue;let V=x(U(Z,q)),J=G(U($,q));if(!J||V.ino===J.ino&&V.dev===J.dev)continue;if(V.isDirectory()&&J.isDirectory()&&!J.isSymbolicLink()){let w=X(q);if(w!==null)return w}else if(V.isSymbolicLink()||J.isSymbolicLink()){if(!(V.isSymbolicLink()&&J.isSymbolicLink()&&D(U(Z,q))===D(U($,q))))return q}else if(a(U(Z,q),U($,q))!==!0)return q}return null};return X("")}function a(Q,Z){let $=G(Q),X=G(Z);if(!$&&!X)return null;if(!$||!X||$.isDirectory()!==X.isDirectory())return!1;if($.ino===X.ino&&$.dev===X.dev)return!0;if($.isDirectory())return[...new Set([...P(Q),...P(Z)])].every((W)=>a(U(Q,W),U(Z,W))===!0);try{return TQ(Q).equals(TQ(Z))}catch{return!1}}function y(Q,Z){for(let $ of u)if(vQ(U(Q,$),U(Z,$)))return!0;return!1}function vQ(Q,Z){let $=G(Q);if(!$)return!1;let X=G(Z);if(!X)return!0;if($.isDirectory()){if(!X.isDirectory())return!0;return P(Q).some((z)=>vQ(U(Q,z),U(Z,z)))}if($.isSymbolicLink())return!X.isSymbolicLink()||D(Q)!==D(Z);return $.ino!==X.ino||$.dev!==X.dev}function RQ(Q){if(p(Q))M(()=>B(Q),"ENOENT")}function yQ(Q){return U(Q,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${xQ(3).toString("hex")}`)}function p(Q){try{return x(Q).isSymbolicLink()&&D(Q)===f(Q)}catch{return!1}}function R(Q){let Z=G(Q);return Z!==null&&Z.isDirectory()}function EZ(Q,Z){for(let $=0;$<40;$+=1){let X=Q.lock(Z);if(X)return X;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function b(Q,Z){return U(Q,`.${Z}-${process.pid}-${xQ(6).toString("hex")}`)}function _Q(Q){if(Q===process.pid)return!1;try{return process.kill(Q,0),!0}catch(Z){return A(Z)==="EPERM"}}function G(Q){try{return x(Q)}catch(Z){if(A(Z)==="ENOENT"||A(Z)==="ENOTDIR")return null;throw Z}}function M(Q,...Z){try{return Q(),!0}catch($){if(Z.includes(A($)??""))return!1;throw $}}function A(Q){return Q instanceof Error&&"code"in Q&&typeof Q.code==="string"?Q.code:void 0}var L,gZ=2,hZ=4,mZ=2,vZ=2,NQ=-100;function pQ(){if(L!==void 0)return L;if(L=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let Q;try{Q=xZ(import.meta.url)("bun:ffi")}catch{return null}let Z=process.platform==="darwin",$=Z?"__error":"__errno_location",X=Z?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:z}=Q;for(let W of X)try{let q=Z?"renamex_np":"renameat2",J=Q.dlopen(W,{flock:{args:[z.i32,z.i32],returns:z.i32},[$]:{args:[],returns:z.ptr},[q]:Z?{args:[z.ptr,z.ptr,z.u32],returns:z.i32}:{args:[z.i32,z.ptr,z.i32,z.ptr,z.u32],returns:z.i32}}).symbols,w=J[$]();if(w===null)continue;let j=(T)=>{let k=Q.read.i32(w),O=Object.entries(LZ.errno).find(([,E])=>E===k)?.[0]??`errno_${k}`;return Object.assign(Error(`${T} failed: ${O}`),{code:O})},HQ=(T)=>Buffer.from(`${T}\x00`,"utf8");return L={exchange(T,k){let O=HQ(T),E=HQ(k);if((Z?J[q](Q.ptr(O),Q.ptr(E),mZ):J[q](NQ,Q.ptr(O),NQ,Q.ptr(E),vZ))!==0)throw j("exchange")},lock(T){let k=NZ(T,_Z.O_RDONLY);if(J.flock(k,gZ|hZ)===0)return()=>FQ(k);let O=j("lock");if(FQ(k),O.code==="EWOULDBLOCK"||O.code==="EAGAIN")return null;throw O}},L}catch{}return null}import{createHmac as V0,createPublicKey as w0,randomBytes as G0,randomUUID as zZ,verify as H0}from"crypto";import{chmodSync as qQ,existsSync as WZ,mkdirSync as M0,readFileSync as j0,realpathSync as K0,renameSync as B0,statSync as O0,unlinkSync as k0,writeFileSync as A0}from"fs";import{basename as P0,dirname as YQ,isAbsolute as qZ,join as s,resolve as F0}from"path";var Y1=[Object.freeze({family:"ara",channel:"stable",applicationId:"so.ara.desktop"}),Object.freeze({family:"ara",channel:"staging",applicationId:"so.ara.desktop.staging"}),Object.freeze({family:"reason",channel:"stable",applicationId:"com.reasonmachines.desktop"}),Object.freeze({family:"reason",channel:"staging",applicationId:"com.reasonmachines.desktop.staging"})];var yZ="REASON_DESKTOP_RUNTIME",pZ="REASON_DESKTOP_RUNTIME_CHANNEL",uZ="REASON_DESKTOP_RUNTIME_INSTANCE_ID",dZ="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",M1={[yZ]:"ARA_DESKTOP_RUNTIME",[pZ]:"ARA_DESKTOP_RUNTIME_CHANNEL",[uZ]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[dZ]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function uQ(Q){if(Q===void 0)return;if(!/^[a-f0-9]{64}$/.test(Q))throw Error("Invalid desktop workspace scope.");return Q}import{chmodSync as QQ,existsSync as F,mkdirSync as ZQ,readFileSync as lQ,realpathSync as lZ,renameSync as iZ,unlinkSync as $Q,writeFileSync as XQ}from"fs";import{createPrivateKey as oZ,createPublicKey as nZ,generateKeyPairSync as rZ,randomUUID as tZ,sign as aZ}from"crypto";import{createRequire as eZ}from"module";import{homedir as Q0,platform as rQ}from"os";import{dirname as Z0,join as C}from"path";import{existsSync as sZ}from"fs";import{join as cQ}from"path";var e="libara_device_keychain.dylib",dQ="libreason_device_keychain.dylib";class cZ extends Error{code;constructor(Q,Z){super(Z);this.code=Q;this.name="ManagedRuntimeError"}}function sQ(Q){let Z=cQ(Q,dQ);return sZ(Z)?Z:cQ(Q,e)}var iQ=1,$0=16384,S=65536,X0=128,z0=128,tQ=65536;class Y extends Error{code;nativeStatus;constructor(Q,Z){super(`Reason Device proof boundary failed (${Q}).${Z===void 0?"":` Native status: ${Z}.`}`);this.code=Q;this.nativeStatus=Z;this.name="LocalCredentialBoundaryError"}}function aQ(Q){if(Q.code==="proof_key_read_failed"&&Q.nativeStatus===-25300)return"proof_key_missing";switch(Q.nativeStatus){case-25308:return"keychain_interaction_required";case-25293:return"keychain_access_denied";case-25291:return"keychain_unavailable";default:return Q.code}}var zQ=null;function eQ(){if(!zQ)try{zQ=eZ(import.meta.url)("bun:ffi")}catch{throw new Y("native_boundary_unavailable")}return zQ}function W0(Q){if(typeof Q!=="string")return null;try{let Z=new URL(Q);if(Z.protocol!=="https:"&&Z.hostname!=="127.0.0.1"&&Z.hostname!=="localhost"&&Z.hostname!=="[::1]"&&Z.hostname!=="::1")return null;return Z.origin}catch{return null}}function q0(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))throw new Y("invalid_credential_record");let Z=Q,$=W0(Z.apiOrigin);if(Z.version!==iQ||!$||typeof Z.orgId!=="string"||Z.orgId.length<1||Z.orgId.length>160||typeof Z.deviceId!=="string"||Z.deviceId.length<1||Z.deviceId.length>160||typeof Z.credential!=="string"||!/^(?:reason|ara)_dev_/.test(Z.credential)||Z.credential.length>4096)throw new Y("invalid_credential_record");return{version:iQ,apiOrigin:$,orgId:Z.orgId,deviceId:Z.deviceId,credential:Z.credential}}function J0(Q=process.execPath){let Z=Q;try{Z=lZ(Q)}catch{}return sQ(Z0(Z))}function H(Q){return eQ().ptr(Q)}function Y0(Q){if(!F(Q))throw new Y("native_boundary_unavailable");let{dlopen:Z,FFIType:$}=eQ();try{return Z(Q,{ara_device_configure_scope:{args:[$.ptr,$.u64],returns:$.i32},ara_device_key_load_public:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_create_fresh_public:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_sign:{args:[$.ptr,$.u64,$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_is_non_extractable:{args:[$.ptr],returns:$.i32},ara_device_key_delete:{args:[$.ptr],returns:$.i32},ara_device_binding_read:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_binding_create:{args:[$.ptr,$.u64],returns:$.i32},ara_device_binding_update:{args:[$.ptr,$.u64],returns:$.i32},ara_device_binding_delete:{args:[$.ptr],returns:$.i32},ara_device_keychain_read:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_keychain_delete:{args:[$.ptr],returns:$.i32}})}catch(X){if(X instanceof Y)throw X;throw new Y("native_boundary_unavailable")}}function oQ(Q){return Buffer.from(Q).toString("base64url")}function I(Q){if(typeof Q!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(Q))return!1;try{let Z=Buffer.from(Q,"base64url");return Z.byteLength===65&&Z[0]===4}catch{return!1}}function QZ(Q){if(Q.byteLength<8||Q.byteLength>72||Q[0]!==48)return!1;let Z=Q[1];return Z!==void 0&&Z<128&&Z+2===Q.byteLength}class ZZ{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(Q=J0(),Z=rQ(),$){this.libraryPath=Q;this.runtimePlatform=Z;this.workspaceScope=$;uQ($)}symbols(){if(this.runtimePlatform!=="darwin")throw new Y("unsupported_platform");this.library??=Y0(this.libraryPath);let Q=new TextEncoder().encode(this.workspaceScope??""),Z=this.library.symbols.ara_device_configure_scope(H(Q.length?Q:new Uint8Array(1)),BigInt(Q.length));if(Z!==0)throw new Y("native_boundary_unavailable",Z);return this.library.symbols}publicKey(Q){let Z=new Uint8Array(X0),$=new BigUint64Array(1),X=Q==="load"?this.symbols().ara_device_key_load_public(H(Z),BigInt(Z.byteLength),H($)):this.symbols().ara_device_key_create_fresh_public(H(Z),BigInt(Z.byteLength),H($));if(X!==0)throw new Y(Q==="load"?"proof_key_read_failed":"proof_key_generation_failed",X);let z=Number($[0]);if(!Number.isSafeInteger(z)||z!==65)throw new Y("invalid_public_key");let W=oQ(Z.subarray(0,z));if(!I(W))throw new Y("invalid_public_key");return W}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(Q){if(Q.byteLength<1||Q.byteLength>tQ)throw new Y("proof_sign_failed");let Z=new Uint8Array(z0),$=new BigUint64Array(1),X=this.symbols().ara_device_key_sign(H(Q),BigInt(Q.byteLength),H(Z),BigInt(Z.byteLength),H($));if(X!==0)throw new Y("proof_sign_failed",X);let z=Number($[0]);if(!Number.isSafeInteger(z)||z<1||z>Z.byteLength)throw new Y("invalid_signature");let W=Z.subarray(0,z);if(!QZ(W))throw new Y("invalid_signature");return oQ(W)}privateKeyIsNonExtractable(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_is_non_extractable(H(Q));if(Z!==0||Q[0]!==1)throw new Y("proof_key_read_failed",Z);return!0}deleteKey(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_delete(H(Q));if(Z!==0)throw new Y("proof_key_delete_failed",Z);return Q[0]===1}loadBinding(){let Q=new Uint8Array(S),Z=new BigUint64Array(1),$=this.symbols().ara_device_binding_read(H(Q),BigInt(Q.byteLength),H(Z));if($===1)return null;if($!==0)throw new Y("binding_read_failed",$);let X=Number(Z[0]);if(!Number.isSafeInteger(X)||X<1||X>Q.byteLength)throw new Y("invalid_binding");return Q.slice(0,X)}createBinding(Q){if(Q.byteLength<1||Q.byteLength>S)throw new Y("invalid_binding");let Z=this.symbols().ara_device_binding_create(H(Q),BigInt(Q.byteLength));if(Z!==0)throw new Y("binding_create_failed",Z)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>S)throw new Y("invalid_binding");let Z=this.symbols().ara_device_binding_update(H(Q),BigInt(Q.byteLength));if(Z!==0)throw new Y("binding_update_failed",Z)}deleteBinding(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_binding_delete(H(Q));if(Z!==0)throw new Y("binding_delete_failed",Z);return Q[0]===1}loadLegacyCredential(){let Q=new Uint8Array($0),Z=new BigUint64Array(1),$=this.symbols().ara_device_keychain_read(H(Q),BigInt(Q.byteLength),H(Z));if($===1)return null;if($!==0)throw new Y("legacy_credential_read_failed",$);let X=Number(Z[0]);if(!Number.isSafeInteger(X)||X<1||X>Q.byteLength)throw new Y("invalid_credential_record");try{let z=new TextDecoder("utf-8",{fatal:!0}).decode(Q.subarray(0,X));return q0(JSON.parse(z))}catch(z){if(z instanceof Y)throw z;throw new Y("invalid_credential_record")}}deleteLegacyCredential(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_keychain_delete(H(Q));if(Z!==0)throw new Y("legacy_credential_delete_failed",Z);return Q[0]===1}}function nQ(Q){let Z=Q.export({format:"jwk"});if(Z.crv!=="P-256"||typeof Z.x!=="string"||typeof Z.y!=="string")throw new Y("invalid_public_key");let $=Buffer.from(Z.x,"base64url"),X=Buffer.from(Z.y,"base64url");if($.byteLength!==32||X.byteLength!==32)throw new Y("invalid_public_key");let z=Buffer.concat([Buffer.of(4),$,X]).toString("base64url");if(!I(z))throw new Y("invalid_public_key");return z}function U0(){let Q=process.env.XDG_CONFIG_HOME?.trim()||C(Q0(),".config");r(Q);let Z=C(Q,"ara");return v(Z)?Z:C(Q,"reason")}class $Z{directory;constructor(Q=U0()){this.directory=Q}keyPath(){return C(this.directory,"local-device.key")}bindingPath(){return C(this.directory,"local-device.binding")}loadPrivateKeyObject(){let Q=this.keyPath();if(!F(Q))throw new Y("proof_key_read_failed");try{let Z=lQ(Q,"utf8");return oZ({key:Z,format:"pem"})}catch{throw new Y("proof_key_read_failed")}}loadPublicKey(){let Q=this.loadPrivateKeyObject(),Z=nZ(Q);return nQ(Z)}createFreshPublicKey(){ZQ(this.directory,{recursive:!0,mode:448});let{privateKey:Q,publicKey:Z}=rZ("ec",{namedCurve:"P-256"}),$=Q.export({type:"pkcs8",format:"pem"}),X=this.keyPath();return XQ(X,$,{mode:384}),QQ(X,384),nQ(Z)}sign(Q){if(Q.byteLength<1||Q.byteLength>tQ)throw new Y("proof_sign_failed");let Z=this.loadPrivateKeyObject(),$;try{$=aZ("sha256",Q,Z)}catch{throw new Y("proof_sign_failed")}if(!QZ($))throw new Y("invalid_signature");return $.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let Q=this.keyPath();if(!F(Q))return!1;return $Q(Q),!0}loadBinding(){let Q=this.bindingPath();if(!F(Q))return null;try{return new Uint8Array(lQ(Q))}catch{return null}}createBinding(Q){if(Q.byteLength<1||Q.byteLength>S)throw new Y("invalid_binding");ZQ(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(F(Z))throw new Y("binding_create_failed");XQ(Z,Q,{mode:384}),QQ(Z,384)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>S)throw new Y("invalid_binding");ZQ(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(!F(Z))throw new Y("binding_update_failed");let $=`${Z}.${tZ()}`;try{XQ($,Q,{mode:384,flag:"wx"}),QQ($,384),iZ($,Z)}finally{if(F($))$Q($)}}deleteBinding(){let Q=this.bindingPath();if(!F(Q))return!1;return $Q(Q),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function WQ(){return rQ()==="darwin"?new ZZ:new $Z}var UQ=4;var d="macos-keychain-p256-v1",JZ=1,T0=`ARA-DEVICE-BINDING-V1
|
|
2
|
+
import{_g as c}from"./vm-hands-entry-lite-em388nee.js";var g={REASON_API_KEY:"ARA_API_KEY",REASON_API_URL:"ARA_API_URL",REASON_CLI_CHANNEL:"ARA_CLI_CHANNEL",REASON_CLI_LAUNCHER_PATH:"ARA_CLI_LAUNCHER_PATH",REASON_MANAGED_RUNTIME_ROOT:"ARA_MANAGED_RUNTIME_ROOT",REASON_INSTALL_ALIAS_PATH:"ARA_INSTALL_ALIAS_PATH",REASON_INSTALL_DIR:"ARA_INSTALL_DIR",REASON_INSTALL_METHOD:"ARA_INSTALL_METHOD",REASON_INSTALL_PINNED_VERSION:"ARA_INSTALL_PINNED_VERSION",REASON_INSTALL_UPGRADE:"ARA_INSTALL_UPGRADE"},g0=Object.values(g),jZ=new Set;function MQ(Q,Z){let $=Q[Z];if($?.trim())return $;let X=Q[g[Z]];if(X?.trim())jZ.add(g[Z]);return X}function KZ(Q,Z){return{[Q]:Z,[g[Q]]:Z}}import{basename as BZ}from"path";var i=["production","staging"],OZ="https://api.reasonmachines.com",kZ="https://staging-api.reasonmachines.com";var l={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},AZ=new Set(["ara-staging","reason-staging"]);function KQ(Q={}){let Z=MQ(Q.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(Z){if(i.includes(Z))return Z;throw Error(`Unknown Reason CLI channel: ${Z}`)}let $=BZ(Q.executablePath??process.execPath).toLowerCase();return AZ.has($)?"staging":"production"}function h(Q){return Q==="staging"?kZ:OZ}function y0(Q){return`${h(Q)}/mcp/ara`}var BQ={production:["https://api.ara.so",l.production.api],staging:["https://api-staging.ara.so",l.staging.api]};function jQ(Q){let Z;try{Z=new URL(Q).origin}catch{return Q}let $=i.find((X)=>BQ[X].includes(Z));return $?h($):Z}function p0(Q,Z){return Q===Z||jQ(Q)===jQ(Z)}function OQ(Q,Z){return i.some(($)=>BQ[$].includes(Q)&&Z===h($))}function u0(Q,Z){try{let $=new URL(Z);return!$.username&&!$.password&&($.origin===h(Q)||$.origin===l[Q].api)}catch{return!1}}function d0(Q){try{let Z=new URL(Q).hostname.replace(/^\[|\]$/g,"").toLowerCase();return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}import{randomBytes as xQ}from"crypto";import{chmodSync as LQ,closeSync as FQ,constants as _Z,linkSync as bQ,lstatSync as x,mkdirSync as fQ,openSync as NZ,readdirSync as P,readFileSync as TQ,readlinkSync as D,renameSync as N,rmdirSync as CQ,symlinkSync as _,unlinkSync as B}from"fs";import{createRequire as xZ}from"module";import{constants as LZ}from"os";import{basename as f,join as U,sep as bZ}from"path";import{existsSync as m,lstatSync as AQ,readdirSync as PZ,readFileSync as FZ,readlinkSync as TZ,realpathSync as DZ}from"fs";import{join as K,sep as RZ}from"path";function o(Q,...Z){let $=K(Q,"ara"),X=K(Q,"reason");if(!v($))return K(X,...Z);if(!m(X))return K($,...Z);return m(K($,...Z))&&!m(K(X,...Z))?K($,...Z):K(X,...Z)}function v(Q){try{let Z=AQ(Q);if(!Z.isSymbolicLink())return Z.isDirectory();return TZ(Q)!=="reason"&&m(Q)}catch{return!1}}function PQ(Q,Z=[]){if(!v(Q))return!1;let $;try{$=[Q,...PZ(Q,{withFileTypes:!0}).filter((X)=>X.isDirectory()).map((X)=>K(Q,X.name))]}catch{return!1}return $.some((X)=>["connect","connect-once"].filter((z)=>!Z.includes(K(X,z))).some((z)=>{let W=K(X,z,"worker.json");try{AQ(W)}catch{return!1}try{let q=JSON.parse(FZ(W,"utf8"))?.stateDirectory;if(typeof q!=="string")return!0;let V=(J,w)=>J===w||J.startsWith(w+RZ);return V(q,Q)||V(kQ(q),kQ(Q))}catch{return!0}}))}function kQ(Q){try{return DZ(Q)}catch{return Q}}var u=new Set(["credentials.json","local-device.json","local-device.revoked.json","local-device.auth-migration.json","local-device.json.registration-pending.json","local-daemon.json","local-daemon.json.workspaces.json","local-root-fingerprint-key.json","instances","workspaces"]),n=new Set(["local-device.proxy.json"]),fZ=new Set(["local-device.key","local-device.binding"]),DQ=new Map;function r(Q,Z,$){let X=U(Q,"ara");if(/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(Q))return{state:G(X)?.isDirectory()?"kept":"absent"};return EQ(X,U(Q,"reason"),{linkAlways:!0,kept:(z)=>PQ(z,$??[]),native:Z===void 0?pQ:()=>Z},$!==void 0)}function SQ(Q,...Z){return r(Q),o(Q,...Z)}function z1(Q,Z=process.platform){let $=U(Q,"Library","Logs");if(Z==="darwin")for(let X of[""," Staging"," Development"])EQ(U($,`Ara${X}`),U($,`Reason${X}`),{linkAlways:!1,kept:()=>!1,native:pQ});return U($,"Reason")}var IQ="config_rename_unavailable:busy";function EQ(Q,Z,$,X=!1){let z=X?void 0:DQ.get(Q);if(z)return z;let W;try{W=CZ(Q,Z,$)}catch(q){let V=`config_rename_unavailable:${A(q)??"failed"}`;try{return{state:G(Q)?.isDirectory()?"kept":"absent",problem:V}}catch{return{state:"kept",problem:V}}}if(!(W.state==="absent"&&$.linkAlways)&&W.problem!==IQ&&!(W.state==="kept"&&!W.problem))DQ.set(Q,W);return W}function CZ(Q,Z,$){IZ(Z,$.native);let X=!1;for(let z=0;z<8;z+=1){let W=G(Q);if(W?.isSymbolicLink())return D(Q)===f(Z)?{state:X?"renamed":"linked"}:{state:"kept"};if(!W){if(p(Z))M(()=>B(Z),"ENOENT");if(!(X||$.linkAlways)||!R(Z))return{state:"absent"};let J=b(Z,"link");_(f(Z),J);try{M(()=>N(J,Q),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{M(()=>B(J),"ENOENT")}continue}if(!W.isDirectory())return{state:"absent"};if($.kept(Q))return RQ(Z),{state:"kept"};let q=$.native();if(!q)return RQ(Z),{state:"kept",problem:"config_rename_unavailable:no_native"};let V=EZ(q,Q);if(!V)return{state:"kept",problem:IQ};try{if(x(Q).isSymbolicLink())continue;let J=SZ(q,Q,Z);if(J)return{state:"kept",problem:J};X=!0}finally{V()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function SZ(Q,Z,$){let X=G($);if(!X||p($)){if(!X)_(f($),$);try{Q.exchange(Z,$)}catch(J){if(p($))M(()=>B($),"ENOENT");return`config_rename_unavailable:${A(J)??"exchange_failed"}`}return null}if(!X.isDirectory())return"config_rename_unavailable:ENOTDIR";if(X.dev!==x(Z).dev)return"config_rename_unavailable:EXDEV";let z=[b($,"probe"),b($,"probe")];try{_("a",z[0]),_("b",z[1]),Q.exchange(z[0],z[1])}catch(J){return`config_rename_unavailable:${A(J)??"exchange_failed"}`}finally{for(let J of z)M(()=>B(J),"ENOENT")}let W=yQ($);for(let J of fZ){let w=G(U($,J)),j=G(U(Z,J));if(w&&j&&w.ino!==j.ino)fQ(`${W}-replaced`,{mode:448,recursive:!0}),N(U($,J),U(`${W}-replaced`,J))}let q={linked:new Map,unitsKept:new Set};gQ(Z,$,"",q);let V=b($,"rename");_(f($),V);try{Q.exchange(Z,V)}catch(J){return M(()=>B(V),"ENOENT"),`config_rename_unavailable:${A(J)??"exchange_failed"}`}return hQ(V,$,q,W),null}function t(Q){return Q===""||!Q.includes(bZ)}function gQ(Q,Z,$,X){let z=t($)&&y(U(Z,$),U(Q,$));if(z)X.unitsKept.add($);for(let W of P(U(Q,$))){if(z&&(u.has(W)||n.has(W)))continue;let q=U($,W),V=U(Q,q),J=U(Z,q),w=G(V);if(!w)continue;let j=G(J);if(w.isDirectory()){if(!j)M(()=>fQ(J,{mode:w.mode&4095}),"EEXIST"),LQ(J,w.mode&4095);if(R(J))gQ(Q,Z,q,X)}else if(!j){if(w.isSymbolicLink())M(()=>_(D(V),J),"EEXIST");else if(M(()=>bQ(V,J),"EEXIST","ENOENT"))X.linked.set(q,w.ino)}}}function IZ(Q,Z){let $;try{if(!R(Q))return;$=P(Q)}catch{return}for(let X of $){let z=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(X);if(!z)continue;let W=U(Q,X),q=G(W);if(!q)continue;if(!q.isDirectory()){if(!_Q(Number(z[2])))M(()=>B(W),"ENOENT");continue}let V=Z(),J=null;if(V){try{J=V.lock(W)}catch{continue}if(!J)continue}else if(_Q(Number(z[2])))continue;try{let w=b(Q,"claim");if(M(()=>N(W,w),"ENOENT"))hQ(w,Q,null,yQ(Q))}finally{J?.()}}}function hQ(Q,Z,$,X){for(let[z,W]of $?.linked??[])if(!G(U(Q,z))&&G(U(Z,z))?.ino===W)M(()=>B(U(Z,z)),"ENOENT");if(mQ(Q,Z,"",$),M(()=>CQ(Q),"ENOTEMPTY","EEXIST"))return;N(Q,X),LQ(X,448)}function mQ(Q,Z,$,X){let z=t($)&&(X?X.unitsKept.has($):y(U(Z,$),U(Q,$)));for(let W of P(U(Q,$))){let q=U($,W),V=U(Q,q),J=U(Z,q),w=x(V),j=G(J);if(j&&w.ino===j.ino&&w.dev===j.dev){B(V);continue}if(w.isFile()&&j?.isFile()&&X?.linked.get(q)===j.ino){N(V,J);continue}if(z&&(u.has(W)||n.has(W)))continue;if(!j){if(w.isFile()){if(M(()=>bQ(V,J),"EEXIST"))B(V)}else M(()=>N(V,J),"EEXIST","ENOTEMPTY");continue}if(w.isDirectory()&&j.isDirectory())mQ(Q,Z,q,X),M(()=>CQ(V),"ENOTEMPTY","EEXIST")}}function W1(Q){let Z=U(Q,"ara"),$=U(Q,"reason");if(!R(Z)||!R($))return null;let X=["",...P(Z,{withFileTypes:!0}).filter((z)=>z.isDirectory()&&!z.name.startsWith(".")).map((z)=>z.name)];for(let z of X){let W=U(Z,z),q=U($,z);if(!y(W,q)||!y(q,W))continue;if([...u,...n].some((J)=>a(U(W,J),U(q,J))===!1))return z}return null}function q1(Q){let Z=U(Q,"ara"),$=U(Q,"reason");if(!R(Z)||!R($))return null;let X=(z)=>{for(let W of P(U(Z,z))){let q=U(z,W);if(t(z)&&(W==="connect"||W==="connect-once"))continue;let V=x(U(Z,q)),J=G(U($,q));if(!J||V.ino===J.ino&&V.dev===J.dev)continue;if(V.isDirectory()&&J.isDirectory()&&!J.isSymbolicLink()){let w=X(q);if(w!==null)return w}else if(V.isSymbolicLink()||J.isSymbolicLink()){if(!(V.isSymbolicLink()&&J.isSymbolicLink()&&D(U(Z,q))===D(U($,q))))return q}else if(a(U(Z,q),U($,q))!==!0)return q}return null};return X("")}function a(Q,Z){let $=G(Q),X=G(Z);if(!$&&!X)return null;if(!$||!X||$.isDirectory()!==X.isDirectory())return!1;if($.ino===X.ino&&$.dev===X.dev)return!0;if($.isDirectory())return[...new Set([...P(Q),...P(Z)])].every((W)=>a(U(Q,W),U(Z,W))===!0);try{return TQ(Q).equals(TQ(Z))}catch{return!1}}function y(Q,Z){for(let $ of u)if(vQ(U(Q,$),U(Z,$)))return!0;return!1}function vQ(Q,Z){let $=G(Q);if(!$)return!1;let X=G(Z);if(!X)return!0;if($.isDirectory()){if(!X.isDirectory())return!0;return P(Q).some((z)=>vQ(U(Q,z),U(Z,z)))}if($.isSymbolicLink())return!X.isSymbolicLink()||D(Q)!==D(Z);return $.ino!==X.ino||$.dev!==X.dev}function RQ(Q){if(p(Q))M(()=>B(Q),"ENOENT")}function yQ(Q){return U(Q,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${xQ(3).toString("hex")}`)}function p(Q){try{return x(Q).isSymbolicLink()&&D(Q)===f(Q)}catch{return!1}}function R(Q){let Z=G(Q);return Z!==null&&Z.isDirectory()}function EZ(Q,Z){for(let $=0;$<40;$+=1){let X=Q.lock(Z);if(X)return X;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function b(Q,Z){return U(Q,`.${Z}-${process.pid}-${xQ(6).toString("hex")}`)}function _Q(Q){if(Q===process.pid)return!1;try{return process.kill(Q,0),!0}catch(Z){return A(Z)==="EPERM"}}function G(Q){try{return x(Q)}catch(Z){if(A(Z)==="ENOENT"||A(Z)==="ENOTDIR")return null;throw Z}}function M(Q,...Z){try{return Q(),!0}catch($){if(Z.includes(A($)??""))return!1;throw $}}function A(Q){return Q instanceof Error&&"code"in Q&&typeof Q.code==="string"?Q.code:void 0}var L,gZ=2,hZ=4,mZ=2,vZ=2,NQ=-100;function pQ(){if(L!==void 0)return L;if(L=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let Q;try{Q=xZ(import.meta.url)("bun:ffi")}catch{return null}let Z=process.platform==="darwin",$=Z?"__error":"__errno_location",X=Z?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:z}=Q;for(let W of X)try{let q=Z?"renamex_np":"renameat2",J=Q.dlopen(W,{flock:{args:[z.i32,z.i32],returns:z.i32},[$]:{args:[],returns:z.ptr},[q]:Z?{args:[z.ptr,z.ptr,z.u32],returns:z.i32}:{args:[z.i32,z.ptr,z.i32,z.ptr,z.u32],returns:z.i32}}).symbols,w=J[$]();if(w===null)continue;let j=(T)=>{let k=Q.read.i32(w),O=Object.entries(LZ.errno).find(([,E])=>E===k)?.[0]??`errno_${k}`;return Object.assign(Error(`${T} failed: ${O}`),{code:O})},HQ=(T)=>Buffer.from(`${T}\x00`,"utf8");return L={exchange(T,k){let O=HQ(T),E=HQ(k);if((Z?J[q](Q.ptr(O),Q.ptr(E),mZ):J[q](NQ,Q.ptr(O),NQ,Q.ptr(E),vZ))!==0)throw j("exchange")},lock(T){let k=NZ(T,_Z.O_RDONLY);if(J.flock(k,gZ|hZ)===0)return()=>FQ(k);let O=j("lock");if(FQ(k),O.code==="EWOULDBLOCK"||O.code==="EAGAIN")return null;throw O}},L}catch{}return null}import{createHmac as V0,createPublicKey as w0,randomBytes as G0,randomUUID as zZ,verify as H0}from"crypto";import{chmodSync as qQ,existsSync as WZ,mkdirSync as M0,readFileSync as j0,realpathSync as K0,renameSync as B0,statSync as O0,unlinkSync as k0,writeFileSync as A0}from"fs";import{basename as P0,dirname as YQ,isAbsolute as qZ,join as s,resolve as F0}from"path";var Y1=[Object.freeze({family:"ara",channel:"stable",applicationId:"so.ara.desktop"}),Object.freeze({family:"ara",channel:"staging",applicationId:"so.ara.desktop.staging"}),Object.freeze({family:"reason",channel:"stable",applicationId:"com.reasonmachines.desktop"}),Object.freeze({family:"reason",channel:"staging",applicationId:"com.reasonmachines.desktop.staging"})];var yZ="REASON_DESKTOP_RUNTIME",pZ="REASON_DESKTOP_RUNTIME_CHANNEL",uZ="REASON_DESKTOP_RUNTIME_INSTANCE_ID",dZ="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",M1={[yZ]:"ARA_DESKTOP_RUNTIME",[pZ]:"ARA_DESKTOP_RUNTIME_CHANNEL",[uZ]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[dZ]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function uQ(Q){if(Q===void 0)return;if(!/^[a-f0-9]{64}$/.test(Q))throw Error("Invalid desktop workspace scope.");return Q}import{chmodSync as QQ,existsSync as F,mkdirSync as ZQ,readFileSync as lQ,realpathSync as lZ,renameSync as iZ,unlinkSync as $Q,writeFileSync as XQ}from"fs";import{createPrivateKey as oZ,createPublicKey as nZ,generateKeyPairSync as rZ,randomUUID as tZ,sign as aZ}from"crypto";import{createRequire as eZ}from"module";import{homedir as Q0,platform as rQ}from"os";import{dirname as Z0,join as C}from"path";import{existsSync as sZ}from"fs";import{join as cQ}from"path";var e="libara_device_keychain.dylib",dQ="libreason_device_keychain.dylib";class cZ extends Error{code;constructor(Q,Z){super(Z);this.code=Q;this.name="ManagedRuntimeError"}}function sQ(Q){let Z=cQ(Q,dQ);return sZ(Z)?Z:cQ(Q,e)}var iQ=1,$0=16384,S=65536,X0=128,z0=128,tQ=65536;class Y extends Error{code;nativeStatus;constructor(Q,Z){super(`Reason Device proof boundary failed (${Q}).${Z===void 0?"":` Native status: ${Z}.`}`);this.code=Q;this.nativeStatus=Z;this.name="LocalCredentialBoundaryError"}}function aQ(Q){if(Q.code==="proof_key_read_failed"&&Q.nativeStatus===-25300)return"proof_key_missing";switch(Q.nativeStatus){case-25308:return"keychain_interaction_required";case-25293:return"keychain_access_denied";case-25291:return"keychain_unavailable";default:return Q.code}}var zQ=null;function eQ(){if(!zQ)try{zQ=eZ(import.meta.url)("bun:ffi")}catch{throw new Y("native_boundary_unavailable")}return zQ}function W0(Q){if(typeof Q!=="string")return null;try{let Z=new URL(Q);if(Z.protocol!=="https:"&&Z.hostname!=="127.0.0.1"&&Z.hostname!=="localhost"&&Z.hostname!=="[::1]"&&Z.hostname!=="::1")return null;return Z.origin}catch{return null}}function q0(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))throw new Y("invalid_credential_record");let Z=Q,$=W0(Z.apiOrigin);if(Z.version!==iQ||!$||typeof Z.orgId!=="string"||Z.orgId.length<1||Z.orgId.length>160||typeof Z.deviceId!=="string"||Z.deviceId.length<1||Z.deviceId.length>160||typeof Z.credential!=="string"||!/^(?:reason|ara)_dev_/.test(Z.credential)||Z.credential.length>4096)throw new Y("invalid_credential_record");return{version:iQ,apiOrigin:$,orgId:Z.orgId,deviceId:Z.deviceId,credential:Z.credential}}function J0(Q=process.execPath){let Z=Q;try{Z=lZ(Q)}catch{}return sQ(Z0(Z))}function H(Q){return eQ().ptr(Q)}function Y0(Q){if(!F(Q))throw new Y("native_boundary_unavailable");let{dlopen:Z,FFIType:$}=eQ();try{return Z(Q,{ara_device_configure_scope:{args:[$.ptr,$.u64],returns:$.i32},ara_device_key_load_public:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_create_fresh_public:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_sign:{args:[$.ptr,$.u64,$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_is_non_extractable:{args:[$.ptr],returns:$.i32},ara_device_key_delete:{args:[$.ptr],returns:$.i32},ara_device_binding_read:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_binding_create:{args:[$.ptr,$.u64],returns:$.i32},ara_device_binding_update:{args:[$.ptr,$.u64],returns:$.i32},ara_device_binding_delete:{args:[$.ptr],returns:$.i32},ara_device_keychain_read:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_keychain_delete:{args:[$.ptr],returns:$.i32}})}catch(X){if(X instanceof Y)throw X;throw new Y("native_boundary_unavailable")}}function oQ(Q){return Buffer.from(Q).toString("base64url")}function I(Q){if(typeof Q!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(Q))return!1;try{let Z=Buffer.from(Q,"base64url");return Z.byteLength===65&&Z[0]===4}catch{return!1}}function QZ(Q){if(Q.byteLength<8||Q.byteLength>72||Q[0]!==48)return!1;let Z=Q[1];return Z!==void 0&&Z<128&&Z+2===Q.byteLength}class ZZ{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(Q=J0(),Z=rQ(),$){this.libraryPath=Q;this.runtimePlatform=Z;this.workspaceScope=$;uQ($)}symbols(){if(this.runtimePlatform!=="darwin")throw new Y("unsupported_platform");this.library??=Y0(this.libraryPath);let Q=new TextEncoder().encode(this.workspaceScope??""),Z=this.library.symbols.ara_device_configure_scope(H(Q.length?Q:new Uint8Array(1)),BigInt(Q.length));if(Z!==0)throw new Y("native_boundary_unavailable",Z);return this.library.symbols}publicKey(Q){let Z=new Uint8Array(X0),$=new BigUint64Array(1),X=Q==="load"?this.symbols().ara_device_key_load_public(H(Z),BigInt(Z.byteLength),H($)):this.symbols().ara_device_key_create_fresh_public(H(Z),BigInt(Z.byteLength),H($));if(X!==0)throw new Y(Q==="load"?"proof_key_read_failed":"proof_key_generation_failed",X);let z=Number($[0]);if(!Number.isSafeInteger(z)||z!==65)throw new Y("invalid_public_key");let W=oQ(Z.subarray(0,z));if(!I(W))throw new Y("invalid_public_key");return W}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(Q){if(Q.byteLength<1||Q.byteLength>tQ)throw new Y("proof_sign_failed");let Z=new Uint8Array(z0),$=new BigUint64Array(1),X=this.symbols().ara_device_key_sign(H(Q),BigInt(Q.byteLength),H(Z),BigInt(Z.byteLength),H($));if(X!==0)throw new Y("proof_sign_failed",X);let z=Number($[0]);if(!Number.isSafeInteger(z)||z<1||z>Z.byteLength)throw new Y("invalid_signature");let W=Z.subarray(0,z);if(!QZ(W))throw new Y("invalid_signature");return oQ(W)}privateKeyIsNonExtractable(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_is_non_extractable(H(Q));if(Z!==0||Q[0]!==1)throw new Y("proof_key_read_failed",Z);return!0}deleteKey(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_delete(H(Q));if(Z!==0)throw new Y("proof_key_delete_failed",Z);return Q[0]===1}loadBinding(){let Q=new Uint8Array(S),Z=new BigUint64Array(1),$=this.symbols().ara_device_binding_read(H(Q),BigInt(Q.byteLength),H(Z));if($===1)return null;if($!==0)throw new Y("binding_read_failed",$);let X=Number(Z[0]);if(!Number.isSafeInteger(X)||X<1||X>Q.byteLength)throw new Y("invalid_binding");return Q.slice(0,X)}createBinding(Q){if(Q.byteLength<1||Q.byteLength>S)throw new Y("invalid_binding");let Z=this.symbols().ara_device_binding_create(H(Q),BigInt(Q.byteLength));if(Z!==0)throw new Y("binding_create_failed",Z)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>S)throw new Y("invalid_binding");let Z=this.symbols().ara_device_binding_update(H(Q),BigInt(Q.byteLength));if(Z!==0)throw new Y("binding_update_failed",Z)}deleteBinding(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_binding_delete(H(Q));if(Z!==0)throw new Y("binding_delete_failed",Z);return Q[0]===1}loadLegacyCredential(){let Q=new Uint8Array($0),Z=new BigUint64Array(1),$=this.symbols().ara_device_keychain_read(H(Q),BigInt(Q.byteLength),H(Z));if($===1)return null;if($!==0)throw new Y("legacy_credential_read_failed",$);let X=Number(Z[0]);if(!Number.isSafeInteger(X)||X<1||X>Q.byteLength)throw new Y("invalid_credential_record");try{let z=new TextDecoder("utf-8",{fatal:!0}).decode(Q.subarray(0,X));return q0(JSON.parse(z))}catch(z){if(z instanceof Y)throw z;throw new Y("invalid_credential_record")}}deleteLegacyCredential(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_keychain_delete(H(Q));if(Z!==0)throw new Y("legacy_credential_delete_failed",Z);return Q[0]===1}}function nQ(Q){let Z=Q.export({format:"jwk"});if(Z.crv!=="P-256"||typeof Z.x!=="string"||typeof Z.y!=="string")throw new Y("invalid_public_key");let $=Buffer.from(Z.x,"base64url"),X=Buffer.from(Z.y,"base64url");if($.byteLength!==32||X.byteLength!==32)throw new Y("invalid_public_key");let z=Buffer.concat([Buffer.of(4),$,X]).toString("base64url");if(!I(z))throw new Y("invalid_public_key");return z}function U0(){let Q=process.env.XDG_CONFIG_HOME?.trim()||C(Q0(),".config");r(Q);let Z=C(Q,"ara");return v(Z)?Z:C(Q,"reason")}class $Z{directory;constructor(Q=U0()){this.directory=Q}keyPath(){return C(this.directory,"local-device.key")}bindingPath(){return C(this.directory,"local-device.binding")}loadPrivateKeyObject(){let Q=this.keyPath();if(!F(Q))throw new Y("proof_key_read_failed");try{let Z=lQ(Q,"utf8");return oZ({key:Z,format:"pem"})}catch{throw new Y("proof_key_read_failed")}}loadPublicKey(){let Q=this.loadPrivateKeyObject(),Z=nZ(Q);return nQ(Z)}createFreshPublicKey(){ZQ(this.directory,{recursive:!0,mode:448});let{privateKey:Q,publicKey:Z}=rZ("ec",{namedCurve:"P-256"}),$=Q.export({type:"pkcs8",format:"pem"}),X=this.keyPath();return XQ(X,$,{mode:384}),QQ(X,384),nQ(Z)}sign(Q){if(Q.byteLength<1||Q.byteLength>tQ)throw new Y("proof_sign_failed");let Z=this.loadPrivateKeyObject(),$;try{$=aZ("sha256",Q,Z)}catch{throw new Y("proof_sign_failed")}if(!QZ($))throw new Y("invalid_signature");return $.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let Q=this.keyPath();if(!F(Q))return!1;return $Q(Q),!0}loadBinding(){let Q=this.bindingPath();if(!F(Q))return null;try{return new Uint8Array(lQ(Q))}catch{return null}}createBinding(Q){if(Q.byteLength<1||Q.byteLength>S)throw new Y("invalid_binding");ZQ(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(F(Z))throw new Y("binding_create_failed");XQ(Z,Q,{mode:384}),QQ(Z,384)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>S)throw new Y("invalid_binding");ZQ(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(!F(Z))throw new Y("binding_update_failed");let $=`${Z}.${tZ()}`;try{XQ($,Q,{mode:384,flag:"wx"}),QQ($,384),iZ($,Z)}finally{if(F($))$Q($)}}deleteBinding(){let Q=this.bindingPath();if(!F(Q))return!1;return $Q(Q),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function WQ(){return rQ()==="darwin"?new ZZ:new $Z}var UQ=4;var d="macos-keychain-p256-v1",JZ=1,T0=`ARA-DEVICE-BINDING-V1
|
|
3
3
|
`;function D0(Q){return Q===void 0||typeof Q==="number"&&Number.isInteger(Q)&&Q>=1&&Q<=4}function YZ(Q={},Z=c()){let $=KQ({env:{...process.env,...Q}}),X=Q.XDG_CONFIG_HOME?.trim()||s(Z,".config");return SQ(X,...$==="staging"?["staging"]:[])}function VQ(Q={},Z=c()){return s(YZ(Q,Z),"local-device.json")}function UZ(Q={},Z=c()){return s(YZ(Q,Z),"local-daemon.json")}function wQ(Q,Z){M0(YQ(Q),{recursive:!0,mode:448}),qQ(YQ(Q),448);let $=`${Q}.${process.pid}.${zZ()}.tmp`;try{A0($,`${JSON.stringify(Z,null,2)}
|
|
4
4
|
`,{mode:384,flag:"wx"}),qQ($,384),B0($,Q),qQ(Q,384)}finally{if(WZ($))k0($)}return Q}function GQ(Q){if(!WZ(Q))return null;try{return JSON.parse(j0(Q,"utf8"))}catch{return null}}function JQ(Q,Z,$){try{Q.onCredentialLifecycle?.({event:Z,...$?{reasonCode:$}:{}})}catch{}}function R0(Q){if(!Array.isArray(Q))return null;let Z=[];for(let $ of Q){if(!$||typeof $!=="object")return null;let X=$;if(typeof X.id!=="string"||typeof X.label!=="string"||typeof X.path!=="string"||typeof X.pathFingerprint!=="string"||!X.permissions||typeof X.permissions.read!=="boolean"||typeof X.permissions.write!=="boolean"||typeof X.permissions.execute!=="boolean"||typeof X.permissions.discover_environment!=="boolean"||typeof X.permissions.expose_mcp!=="boolean")return null;Z.push({id:X.id,label:X.label,path:X.path,pathFingerprint:X.pathFingerprint,permissions:X.permissions})}return Z}function VZ(Q,Z,$=[]){let X=Object.keys(Q);return Z.every((z)=>Object.hasOwn(Q,z))&&X.every((z)=>Z.includes(z)||$.includes(z))}function _0(Q){if(typeof Q!=="string")return null;try{let Z=new URL(Q);if(Z.protocol!=="https:"&&Z.hostname!=="127.0.0.1"&&Z.hostname!=="localhost")return null;return Z.origin}catch{return null}}function wZ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let Z=Q,$=R0(Z.roots),X=_0(Z.apiOrigin);if(!X||typeof Z.orgId!=="string"||typeof Z.deviceId!=="string"||typeof Z.displayName!=="string"||typeof Z.registeredAt!=="string"||!D0(Z.handsSlots)||Z.worker!==void 0&&(!Z.worker||!/^[a-f0-9]{64}$/.test(Z.worker.configDigest)||!["persistent","ephemeral"].includes(Z.worker.lifetime)||!Number.isFinite(Date.parse(Z.worker.expiresAt)))||!$)return null;return{apiOrigin:X,orgId:Z.orgId,deviceId:Z.deviceId,displayName:Z.displayName,registeredAt:Z.registeredAt,...Z.handsSlots!==void 0?{handsSlots:Z.handsSlots}:{},...Z.worker!==void 0?{worker:Z.worker}:{},roots:$}}function N0(Q){return{...Q,credentialStorage:d}}function x0(Q){return{version:UQ,apiOrigin:Q.apiOrigin,orgId:Q.orgId,deviceId:Q.deviceId,devicePublicKey:Q.devicePublicKey,displayName:Q.displayName,registeredAt:Q.registeredAt,...Q.handsSlots!==void 0?{handsSlots:Q.handsSlots}:{},...Q.worker!==void 0?{worker:Q.worker}:{},roots:Q.roots.map((Z)=>({id:Z.id,label:Z.label,path:Z.path,pathFingerprint:Z.pathFingerprint,permissions:{read:Z.permissions.read,write:Z.permissions.write,execute:Z.permissions.execute,discover_environment:Z.permissions.discover_environment,expose_mcp:Z.permissions.expose_mcp}})),credentialStorage:d}}function GZ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let Z=Q;if(!VZ(Z,["version","apiOrigin","orgId","deviceId","devicePublicKey","displayName","registeredAt","roots","credentialStorage"],["handsSlots","worker"]))return null;let $=wZ(Z);if(!$||Z.version!==UQ||Z.credentialStorage!==d||!I(Z.devicePublicKey))return null;return{version:UQ,...$,devicePublicKey:Z.devicePublicKey,credentialStorage:d}}function HZ(Q){return new TextEncoder().encode(`${T0}${JSON.stringify(x0(Q))}`)}function L0(Q){let Z=Buffer.from(Q,"base64url");return w0({format:"jwk",key:{kty:"EC",crv:"P-256",x:Z.subarray(1,33).toString("base64url"),y:Z.subarray(33,65).toString("base64url")}})}function b0(Q,Z){let $={version:JZ,state:Q,signature:Z.sign(HZ(Q))};return new TextEncoder().encode(JSON.stringify($))}function MZ(Q){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Q))}catch{throw new Y("invalid_binding")}if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new Y("invalid_binding");let $=Z;if(!VZ($,["version","state","signature"])||$.version!==JZ||typeof $.signature!=="string"||!/^[A-Za-z0-9_-]{10,128}$/.test($.signature))throw new Y("invalid_binding");let X=GZ($.state);if(!X)throw new Y("invalid_binding");let z=!1;try{z=H0("sha256",HZ(X),L0(X.devicePublicKey),Buffer.from($.signature,"base64url"))}catch{z=!1}if(!z)throw new Y("invalid_binding");return X}function f0(Q){let{credentialStorage:Z,...$}=Q;return $}function C0(Q){return Q instanceof Y?aQ(Q):"credential_boundary_failed"}function v1(Q=VQ(),Z={}){let $=GQ(Q),X=Z.proofStore??Z.credentialStore??WQ(),z=X.loadBinding();if(!z){if($&&typeof $==="object"&&!Array.isArray($)&&S0($))return null;if($!==null)throw new Y("invalid_binding");return null}let W=MZ(z),q=X.loadPublicKey();if(X.privateKeyIsNonExtractable(),q!==W.devicePublicKey)throw new Y("invalid_public_key");let V=GZ($);if(Z.repair!==!1&&(!V||JSON.stringify(V)!==JSON.stringify(W)))wQ(Q,W);return f0(W)}function S0(Q){let Z=Q,$=wZ(Q);if(!$)return null;if(Z.version===2){if(typeof Z.deviceCredential!=="string"||!/^(?:reason|ara)_dev_/.test(Z.deviceCredential)||Z.deviceCredential.length>4096)return null;return{state:$,credentialSource:"plaintext-v2"}}if(Z.version!==3||Z.credentialStorage!=="macos-keychain-v1"||"deviceCredential"in Z)return null;return{state:$,credentialSource:"keychain-v3"}}function y1(Q,Z=VQ(),$={}){let X=$.proofStore??$.credentialStore??WQ();JQ($,"credential.store_started");try{if(!I(Q.devicePublicKey)||X.loadPublicKey()!==Q.devicePublicKey)throw new Y("invalid_public_key");X.privateKeyIsNonExtractable();let z=N0(Q),W=X.loadBinding();if(W){let V=MZ(W);if(V.devicePublicKey!==Q.devicePublicKey||V.orgId!==Q.orgId||V.deviceId!==Q.deviceId||V.apiOrigin!==Q.apiOrigin&&!OQ(V.apiOrigin,Q.apiOrigin))throw new Y("invalid_binding")}let q=b0(z,X);if(W)X.updateBinding(q);else X.createBinding(q);return wQ(Z,z),JQ($,"credential.store_completed"),Z}catch(z){throw JQ($,"credential.store_failed",C0(z)),z}}function p1(Q=UZ()){let Z=GQ(Q);if(!Z||typeof Z!=="object")return null;let $=Z;if($.version!==1||typeof $.pid!=="number"||!Number.isInteger($.pid)||!["starting","connected","stopped","error"].includes($.state??"")||typeof $.startedAt!=="string"||$.lastHeartbeatAt!==void 0&&typeof $.lastHeartbeatAt!=="string"||$.lastUsedAt!==void 0&&typeof $.lastUsedAt!=="string"||$.organizationId!==void 0&&typeof $.organizationId!=="string"||$.organizationName!==void 0&&typeof $.organizationName!=="string"||$.organizationSlug!==void 0&&typeof $.organizationSlug!=="string"||$.error!==void 0&&typeof $.error!=="string"||$.reconnectingSince!==void 0&&typeof $.reconnectingSince!=="string"||$.workspace!==void 0&&typeof $.workspace!=="string")return null;return $}function u1(Q,Z=UZ()){return wQ(Z,Q)}var XZ=1;function I0(Q=VQ()){return s(YQ(Q),"local-device.proxy.json")}function d1(Q=I0()){let Z=GQ(Q);if(!Z||typeof Z!=="object"||Array.isArray(Z))return null;let $=Z;if($.version!==XZ||typeof $.url!=="string"||$.url.length===0||$.caFile!==void 0&&(typeof $.caFile!=="string"||!qZ($.caFile)))return null;return{version:XZ,url:$.url,...$.caFile?{caFile:$.caFile}:{}}}function c1(Q,Z={read:!0,write:!1,execute:!1,discover_environment:!1,expose_mcp:!1},$=G0(32)){let X=new Set,z=[];for(let W of Q){let q=K0(qZ(W)?W:F0(W));if(!O0(q).isDirectory())throw Error(`Local execution root is not a directory: ${W}`);if(X.has(q))continue;X.add(q),z.push({id:zZ(),label:P0(q)||q,path:q,pathFingerprint:V0("sha256",$).update(q).digest("hex"),permissions:{...Z}})}if(z.length===0)throw Error("At least one explicit local execution root is required.");return z}
|
|
5
5
|
export{MQ as Be,KZ as Ce,i as De,KQ as Ee,h as Fe,y0 as Ge,jQ as He,p0 as Ie,OQ as Je,u0 as Ke,d0 as Le,r as Me,SQ as Ne,z1 as Oe,W1 as Pe,q1 as Qe,pQ as Re,cZ as Se,Y as Te,J0 as Ue,I as Ve,QZ as We,ZZ as Xe,$Z as Ye,VQ as Ze,UZ as _e,v1 as $e,y1 as af,p1 as bf,u1 as cf,XZ as df,d1 as ef,c1 as ff};
|