@reason-machines/cli-linux-arm64-musl 0.2.343 → 0.2.345

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.
Files changed (76) hide show
  1. package/bin/ara +1 -1
  2. package/bin/vm-hands/api-credentials-d34gw13p.js +2 -0
  3. package/bin/vm-hands/api-t5zxz49k.js +2 -0
  4. package/bin/vm-hands/{ask-relay-d96qx4ez.js → ask-relay-bczg32b2.js} +2 -2
  5. package/bin/vm-hands/connect-cli-789rv77k.js +2 -0
  6. package/bin/vm-hands/{custom-endpoint-device-whc0qjdv.js → custom-endpoint-device-syw4d5k4.js} +1 -1
  7. package/bin/vm-hands/desktop-account-pm3zxjjt.js +2 -0
  8. package/bin/vm-hands/{device-workspace-1abchg0z.js → device-workspace-s49yhsk7.js} +1 -1
  9. package/bin/vm-hands/{hands-worker-source-9mq68whc.js → hands-worker-source-0ca76sbd.js} +1 -1
  10. package/bin/vm-hands/{index-5a4yhzf8.js → index-t1h1wd8g.js} +1 -1
  11. package/bin/vm-hands/local-automation-ms5cgtgc.js +2 -0
  12. package/bin/vm-hands/local-capabilities-jfmzy2qt.js +2 -0
  13. package/bin/vm-hands/local-desktop-users-zxw8xxw9.js +2 -0
  14. package/bin/vm-hands/local-display-mac-jdgx19jw.js +2 -0
  15. package/bin/vm-hands/local-display-session-v8g6x39d.js +2 -0
  16. package/bin/vm-hands/local-pty-session-frp7k8fz.js +2 -0
  17. package/bin/vm-hands/{network-contract-7y9z06qs.js → network-contract-8d4bpy3e.js} +1 -1
  18. package/bin/vm-hands/package-vj1s3sye.js +2 -0
  19. package/bin/vm-hands/permissions-9vwmb8cz.js +2 -0
  20. package/bin/vm-hands/{reason-hands-protocol-mm6kwqk8.js → reason-hands-protocol-k12eme4q.js} +1 -1
  21. package/bin/vm-hands/{status-2mbhthe2.js → status-jfa65qn3.js} +2 -2
  22. package/bin/vm-hands/version-mzcyw4fg.js +2 -0
  23. package/bin/vm-hands/{vm-hands-entry-lite-0zr461f9.js → vm-hands-entry-lite-0jar357h.js} +2 -2
  24. package/bin/vm-hands/{vm-hands-entry-lite-pn6vyghh.js → vm-hands-entry-lite-0wyjnvjz.js} +1 -1
  25. package/bin/vm-hands/{vm-hands-entry-lite-va7g1e1f.js → vm-hands-entry-lite-1jhry648.js} +1 -1
  26. package/bin/vm-hands/{vm-hands-entry-lite-ckehp0dy.js → vm-hands-entry-lite-1w8tvrpq.js} +3 -3
  27. package/bin/vm-hands/{vm-hands-entry-lite-70d6f5r9.js → vm-hands-entry-lite-1xjtcxpn.js} +1 -1
  28. package/bin/vm-hands/{vm-hands-entry-lite-3s5fdvat.js → vm-hands-entry-lite-289bc9v7.js} +1 -1
  29. package/bin/vm-hands/{vm-hands-entry-lite-3c4qwk4d.js → vm-hands-entry-lite-2e50z7hj.js} +1 -1
  30. package/bin/vm-hands/{vm-hands-entry-lite-6z2g0td2.js → vm-hands-entry-lite-2xh7sjs0.js} +2 -2
  31. package/bin/vm-hands/vm-hands-entry-lite-36xzwsxn.js +42 -0
  32. package/bin/vm-hands/{vm-hands-entry-lite-p7x3vnz5.js → vm-hands-entry-lite-7ba3nhgv.js} +1 -1
  33. package/bin/vm-hands/{vm-hands-entry-lite-jjq3xq9z.js → vm-hands-entry-lite-8dvf3de9.js} +2 -2
  34. package/bin/vm-hands/{vm-hands-entry-lite-p9eyqdq7.js → vm-hands-entry-lite-9dx3at21.js} +2 -2
  35. package/bin/vm-hands/{vm-hands-entry-lite-8zencenv.js → vm-hands-entry-lite-ac6zyrj1.js} +1 -1
  36. package/bin/vm-hands/{vm-hands-entry-lite-q1ekx7k0.js → vm-hands-entry-lite-b38m8a8m.js} +2 -2
  37. package/bin/vm-hands/{vm-hands-entry-lite-60t59y3n.js → vm-hands-entry-lite-b8y45rcs.js} +1 -1
  38. package/bin/vm-hands/{vm-hands-entry-lite-ypcqvygf.js → vm-hands-entry-lite-gt5pkv4h.js} +1 -1
  39. package/bin/vm-hands/{vm-hands-entry-lite-dqqjy7kj.js → vm-hands-entry-lite-hywf6580.js} +2 -2
  40. package/bin/vm-hands/{vm-hands-entry-lite-xv868vfm.js → vm-hands-entry-lite-jy102628.js} +2 -2
  41. package/bin/vm-hands/{vm-hands-entry-lite-3gf1yegq.js → vm-hands-entry-lite-k2cvr710.js} +1 -1
  42. package/bin/vm-hands/{vm-hands-entry-lite-bfh3cnh2.js → vm-hands-entry-lite-k2e3q5qj.js} +1 -1
  43. package/bin/vm-hands/{vm-hands-entry-lite-2mhzfg6b.js → vm-hands-entry-lite-knfh7w3j.js} +2 -2
  44. package/bin/vm-hands/{vm-hands-entry-lite-vn0r1e8c.js → vm-hands-entry-lite-kt418g2w.js} +2 -2
  45. package/bin/vm-hands/{vm-hands-entry-lite-tt4zgt64.js → vm-hands-entry-lite-m16qf0yy.js} +1 -1
  46. package/bin/vm-hands/{vm-hands-entry-lite-45cnnd8e.js → vm-hands-entry-lite-mhsv58hw.js} +1 -1
  47. package/bin/vm-hands/{vm-hands-entry-lite-2c8m8m7v.js → vm-hands-entry-lite-pa111vpq.js} +2 -2
  48. package/bin/vm-hands/{vm-hands-entry-lite-5qe562gn.js → vm-hands-entry-lite-pnkfgnqz.js} +1 -1
  49. package/bin/vm-hands/{vm-hands-entry-lite-21sg3fyz.js → vm-hands-entry-lite-tfpebnar.js} +1 -1
  50. package/bin/vm-hands/{vm-hands-entry-lite-qezqtm4g.js → vm-hands-entry-lite-x6jqyxkx.js} +2 -2
  51. package/bin/vm-hands/vm-hands-entry-lite-y16b538h.js +529 -0
  52. package/bin/vm-hands/{vm-hands-entry-lite-xazz63m6.js → vm-hands-entry-lite-y4mtveeb.js} +2 -2
  53. package/bin/vm-hands/{vm-hands-entry-lite-bs1mbk81.js → vm-hands-entry-lite-yeahy7rk.js} +2 -2
  54. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  55. package/bin/vm-hands/{vm-hands-executor-wqn9mnsj.js → vm-hands-executor-tyxvq0j1.js} +1 -1
  56. package/bin/vm-hands/vm-hands-op-runner-k79jadt5.js +2 -0
  57. package/bin/vm-hands/{vm-hands-runtime-bwvpt55d.js → vm-hands-runtime-dq1t8vee.js} +3 -3
  58. package/bin/vm-hands/worker-sandbox-1kpm6af4.js +2 -0
  59. package/package.json +1 -1
  60. package/bin/vm-hands/api-credentials-7wdzy9by.js +0 -2
  61. package/bin/vm-hands/api-jq1fd10n.js +0 -2
  62. package/bin/vm-hands/connect-cli-cp0zh5f8.js +0 -2
  63. package/bin/vm-hands/desktop-account-j9pxgjn0.js +0 -2
  64. package/bin/vm-hands/local-automation-v0r1k6v9.js +0 -2
  65. package/bin/vm-hands/local-capabilities-9y6jj12c.js +0 -2
  66. package/bin/vm-hands/local-desktop-users-gxkmx7rv.js +0 -2
  67. package/bin/vm-hands/local-display-mac-6ktqrbas.js +0 -2
  68. package/bin/vm-hands/local-display-session-ab79qr64.js +0 -2
  69. package/bin/vm-hands/local-pty-session-3592ene9.js +0 -2
  70. package/bin/vm-hands/package-ffnz28tt.js +0 -2
  71. package/bin/vm-hands/permissions-ddm9as7j.js +0 -2
  72. package/bin/vm-hands/version-xdgmrx9d.js +0 -2
  73. package/bin/vm-hands/vm-hands-entry-lite-1sq7jgg0.js +0 -529
  74. package/bin/vm-hands/vm-hands-entry-lite-bbc5r4y1.js +0 -42
  75. package/bin/vm-hands/vm-hands-op-runner-8nw0g7v3.js +0 -2
  76. package/bin/vm-hands/worker-sandbox-4mraqzsg.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Sb as kQ,Tb as fQ,Ub as z4,Vb as K4,Wb as F8}from"./vm-hands-entry-lite-wmxksawm.js";import{$b as G8,_b as MQ,ac as n9,bc as _0,cc as L9,dc as n0,kc as K0}from"./vm-hands-entry-lite-3gf1yegq.js";import{pc as b0}from"./vm-hands-entry-lite-k469tezz.js";import{Td as w9,Ud as o0,Vd as B8,Wd as g0,_d as q0,ld as $Q,od as QQ}from"./vm-hands-entry-lite-bbc5r4y1.js";import{_e as Y4}from"./vm-hands-entry-lite-2c8m8m7v.js";import{yf as UZ}from"./vm-hands-entry-lite-xazz63m6.js";import{kg as hQ,qg as a9,rg as g8}from"./vm-hands-entry-lite-vn0r1e8c.js";import{$g as O0,Fg as ZQ,Gg as XQ,Ig as JQ,Kg as p9,Lg as n$,Mg as i$,Ng as E8,Qg as l9,Zg as R8,_g as S0,ah as u9,hh as b8,ih as YQ,jh as a$,tg as OZ,wg as B9}from"./vm-hands-entry-lite-2mhzfg6b.js";import{Dh as cQ,Eh as h8}from"./vm-hands-entry-lite-70d6f5r9.js";import{Mh as M8,Nh as s9,Qh as J4}from"./vm-hands-entry-lite-p9eyqdq7.js";import{Rh as L8,Sh as i0,Th as N8,Uh as a0,Vh as H9,Wh as Y8,Xh as $$,Yh as s0,Zh as p0,_h as s$,ji as B$}from"./vm-hands-entry-lite-3s5fdvat.js";import{ki as x}from"./vm-hands-entry-lite-6z2g0td2.js";import{qi as G4}from"./vm-hands-entry-lite-0zr461f9.js";import{si as C}from"./vm-hands-entry-lite-ypcqvygf.js";import{ti as P1,yi as VZ}from"./vm-hands-entry-lite-45cnnd8e.js";var v={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000,window:8};function v9($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function P0($,Q,Z=Number.MAX_SAFE_INTEGER){return typeof $==="number"&&Number.isSafeInteger($)&&$>=Q&&$<=Z}function S$($){return typeof $==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test($)}function w$($,Q){let Z=Buffer.from($,"latin1");return Buffer.concat([Buffer.from([Z.length]),Z,Q])}function I0($){if(!v9($)||Object.keys($).length!==12||![$.organizationId,$.userId,$.runId,$.deviceId,$.rootId,$.jobId,$.fenceId].every(S$)||!P0($.attachmentRevision,0)||!P0($.grantRevision,1)||!P0($.generation,1)||!P0($.port,1024,65535)||!P0($.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...$})}function c0($,Q){return Object.keys($).every((Z)=>$[Z]===Q[Z])}function q9($){if($.length>4096||!$.startsWith("/")||$.startsWith("//")||/[\\\x00-\x20\x7f#]/.test($))throw Error("preview_path_invalid");let Q=decodeURIComponent($);if(Q.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(Q))throw Error("preview_path_invalid");return $}function E$($){return Array.isArray($)&&$.length<=64&&$.every((Q)=>Array.isArray(Q)&&Q.length===2&&typeof Q[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(Q[0])&&typeof Q[1]==="string"&&Q[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(Q[1]))}function C9($,Q=v.chunk){if($.length>Math.ceil(Q/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test($))throw Error("preview_data_invalid");let Z=Buffer.from($,"base64");if(Z.length>Q)throw Error("preview_data_too_large");return Z}function b$($){if(Array.isArray($))return Buffer.concat($);if(typeof $==="string")return Buffer.from($,"utf8");if($ instanceof ArrayBuffer)return Buffer.from($);return $}function k$($){if(Buffer.byteLength($)>v.upload*1.4+300000)throw Error("preview_frame_too_large");let Q=JSON.parse($);if(!v9(Q))throw Error("preview_frame_invalid");if(Q.type==="hello")return{type:"hello",binding:I0(Q.binding),...P0(Q.messages,v.chunk,v.upload)?{messages:Q.messages}:{},...P0(Q.window,1,v.window)?{window:Q.window}:{},...Q.bytes===!0?{bytes:!0}:{}};if(Q.type==="refused"&&typeof Q.reason==="string"&&/^[a-z_]{1,32}$/.test(Q.reason))return{type:"refused",binding:I0(Q.binding),reason:Q.reason};if(!S$(Q.id))throw Error("preview_frame_invalid");if(Q.type==="end"||Q.type==="cancel"||Q.type==="credit")return{type:Q.type,id:Q.id};if(Q.type==="ws"&&typeof Q.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(Q.protocol))return{type:"ws",id:Q.id,protocol:Q.protocol};if(Q.type==="data"&&typeof Q.data==="string"&&typeof Q.binary==="boolean")return C9(Q.data,v.upload),{type:"data",id:Q.id,data:Q.data,binary:Q.binary};if(Q.type==="head"&&P0(Q.status,200,599)&&E$(Q.headers))return{type:"head",id:Q.id,status:Q.status,headers:Q.headers};if(Q.type==="request"&&typeof Q.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(Q.method)&&typeof Q.path==="string"&&E$(Q.headers)&&typeof Q.body==="string"&&typeof Q.upgrade==="boolean")return C9(Q.body,v.upload),{type:"request",id:Q.id,method:Q.method,path:q9(Q.path),headers:Q.headers,body:Q.body,upgrade:Q.upgrade};throw Error("preview_frame_invalid")}function _8($){let Q=[...$],Z=new Set(Q.filter(([J])=>J.toLowerCase()==="connection").flatMap(([,J])=>J.toLowerCase().split(",").map((Y)=>Y.trim()))),X=new Set(["authorization","proxy-authorization","cookie","set-cookie","host","origin","referer","connection","upgrade","keep-alive","transfer-encoding","te","trailer","content-length","forwarded","alt-svc","service-worker-allowed","clear-site-data","refresh"]);return Q.filter(([J])=>!X.has(J.toLowerCase())&&!Z.has(J.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(J))}async function A8($){let Q;try{return await Promise.race([Promise.resolve().then($).then((Z)=>Z===!0||(Z===!1?!1:void 0),()=>{return}),new Promise((Z)=>{Q=setTimeout(()=>Z(void 0),v.authorizationMs)})])}finally{clearTimeout(Q)}}async function T9($){return await A8($)===!0}function c9($,Q){let Z=new URL($);if(Z.username||Z.password||Z.search||Z.hash||!(Z.protocol==="wss:"||Z.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(Z.hostname))||!new RegExp(`^/${Q}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(Z.pathname))throw Error("preview_relay_invalid");return Z.href}function f$($){if(!v9($)||Object.keys($).length!==2||typeof $.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:I0($.binding),deviceRelayUrl:c9($.deviceRelayUrl,"device")}}function g$($){if(!v9($)||Object.keys($).length!==1||!("binding"in $))throw Error("preview_close_invalid");return{binding:I0($.binding)}}import{request as D4}from"http";import{pipeline as _4}from"stream";import{constants as x8,createBrotliCompress as A4,createGzip as x4}from"zlib";import{WebSocket as O9}from"ws";import{randomBytes as q4,timingSafeEqual as T4}from"crypto";import{createServer as O4}from"net";var m$="x-preview-connection";async function y$($,Q){if(Q.aborted)throw Error("preview_closed");let Z=q4(32).toString("base64url"),X=new Set,J=!1,Y=O4((G)=>{if(J||Q.aborted||X.size>=v.streams*2)return G.destroy();X.add(G);let F=new AbortController;G.once("close",()=>{X.delete(G),F.abort()}),G.on("error",()=>G.destroy()),G.setTimeout(2000,()=>G.destroy());let B=Buffer.alloc(0),H=(L)=>{B=Buffer.concat([B,L]);let W=B.indexOf(`\r
2
+ import{Sb as kQ,Tb as fQ,Ub as z4,Vb as K4,Wb as F8}from"./vm-hands-entry-lite-wmxksawm.js";import{$b as G8,_b as MQ,ac as n9,bc as _0,cc as L9,dc as n0,kc as K0}from"./vm-hands-entry-lite-k2cvr710.js";import{pc as b0}from"./vm-hands-entry-lite-k469tezz.js";import{Vd as w9,Wd as o0,Xd as B8,Yd as g0,ae as q0,ld as $Q,qd as QQ}from"./vm-hands-entry-lite-36xzwsxn.js";import{af as Y4}from"./vm-hands-entry-lite-pa111vpq.js";import{Af as UZ}from"./vm-hands-entry-lite-y4mtveeb.js";import{mg as hQ,sg as a9,tg as g8}from"./vm-hands-entry-lite-kt418g2w.js";import{$g as R8,Hg as ZQ,Ig as XQ,Kg as JQ,Mg as p9,Ng as n$,Og as i$,Pg as E8,Sg as l9,ah as S0,bh as O0,ch as u9,jh as b8,kh as YQ,lh as a$,vg as OZ,yg as B9}from"./vm-hands-entry-lite-knfh7w3j.js";import{Fh as cQ,Gh as h8}from"./vm-hands-entry-lite-1xjtcxpn.js";import{Oh as M8,Ph as s9,Sh as J4}from"./vm-hands-entry-lite-9dx3at21.js";import{$h as p0,Th as L8,Uh as i0,Vh as N8,Wh as a0,Xh as H9,Yh as Y8,Zh as $$,_h as s0,ai as s$,li as B$}from"./vm-hands-entry-lite-289bc9v7.js";import{mi as x}from"./vm-hands-entry-lite-2xh7sjs0.js";import{si as G4}from"./vm-hands-entry-lite-0jar357h.js";import{ui as C}from"./vm-hands-entry-lite-gt5pkv4h.js";import{Ai as VZ,vi as P1}from"./vm-hands-entry-lite-mhsv58hw.js";var v={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000,window:8};function v9($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function P0($,Q,Z=Number.MAX_SAFE_INTEGER){return typeof $==="number"&&Number.isSafeInteger($)&&$>=Q&&$<=Z}function S$($){return typeof $==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test($)}function w$($,Q){let Z=Buffer.from($,"latin1");return Buffer.concat([Buffer.from([Z.length]),Z,Q])}function I0($){if(!v9($)||Object.keys($).length!==12||![$.organizationId,$.userId,$.runId,$.deviceId,$.rootId,$.jobId,$.fenceId].every(S$)||!P0($.attachmentRevision,0)||!P0($.grantRevision,1)||!P0($.generation,1)||!P0($.port,1024,65535)||!P0($.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...$})}function c0($,Q){return Object.keys($).every((Z)=>$[Z]===Q[Z])}function q9($){if($.length>4096||!$.startsWith("/")||$.startsWith("//")||/[\\\x00-\x20\x7f#]/.test($))throw Error("preview_path_invalid");let Q=decodeURIComponent($);if(Q.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(Q))throw Error("preview_path_invalid");return $}function E$($){return Array.isArray($)&&$.length<=64&&$.every((Q)=>Array.isArray(Q)&&Q.length===2&&typeof Q[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(Q[0])&&typeof Q[1]==="string"&&Q[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(Q[1]))}function C9($,Q=v.chunk){if($.length>Math.ceil(Q/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test($))throw Error("preview_data_invalid");let Z=Buffer.from($,"base64");if(Z.length>Q)throw Error("preview_data_too_large");return Z}function b$($){if(Array.isArray($))return Buffer.concat($);if(typeof $==="string")return Buffer.from($,"utf8");if($ instanceof ArrayBuffer)return Buffer.from($);return $}function k$($){if(Buffer.byteLength($)>v.upload*1.4+300000)throw Error("preview_frame_too_large");let Q=JSON.parse($);if(!v9(Q))throw Error("preview_frame_invalid");if(Q.type==="hello")return{type:"hello",binding:I0(Q.binding),...P0(Q.messages,v.chunk,v.upload)?{messages:Q.messages}:{},...P0(Q.window,1,v.window)?{window:Q.window}:{},...Q.bytes===!0?{bytes:!0}:{}};if(Q.type==="refused"&&typeof Q.reason==="string"&&/^[a-z_]{1,32}$/.test(Q.reason))return{type:"refused",binding:I0(Q.binding),reason:Q.reason};if(!S$(Q.id))throw Error("preview_frame_invalid");if(Q.type==="end"||Q.type==="cancel"||Q.type==="credit")return{type:Q.type,id:Q.id};if(Q.type==="ws"&&typeof Q.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(Q.protocol))return{type:"ws",id:Q.id,protocol:Q.protocol};if(Q.type==="data"&&typeof Q.data==="string"&&typeof Q.binary==="boolean")return C9(Q.data,v.upload),{type:"data",id:Q.id,data:Q.data,binary:Q.binary};if(Q.type==="head"&&P0(Q.status,200,599)&&E$(Q.headers))return{type:"head",id:Q.id,status:Q.status,headers:Q.headers};if(Q.type==="request"&&typeof Q.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(Q.method)&&typeof Q.path==="string"&&E$(Q.headers)&&typeof Q.body==="string"&&typeof Q.upgrade==="boolean")return C9(Q.body,v.upload),{type:"request",id:Q.id,method:Q.method,path:q9(Q.path),headers:Q.headers,body:Q.body,upgrade:Q.upgrade};throw Error("preview_frame_invalid")}function _8($){let Q=[...$],Z=new Set(Q.filter(([J])=>J.toLowerCase()==="connection").flatMap(([,J])=>J.toLowerCase().split(",").map((Y)=>Y.trim()))),X=new Set(["authorization","proxy-authorization","cookie","set-cookie","host","origin","referer","connection","upgrade","keep-alive","transfer-encoding","te","trailer","content-length","forwarded","alt-svc","service-worker-allowed","clear-site-data","refresh"]);return Q.filter(([J])=>!X.has(J.toLowerCase())&&!Z.has(J.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(J))}async function A8($){let Q;try{return await Promise.race([Promise.resolve().then($).then((Z)=>Z===!0||(Z===!1?!1:void 0),()=>{return}),new Promise((Z)=>{Q=setTimeout(()=>Z(void 0),v.authorizationMs)})])}finally{clearTimeout(Q)}}async function T9($){return await A8($)===!0}function c9($,Q){let Z=new URL($);if(Z.username||Z.password||Z.search||Z.hash||!(Z.protocol==="wss:"||Z.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(Z.hostname))||!new RegExp(`^/${Q}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(Z.pathname))throw Error("preview_relay_invalid");return Z.href}function f$($){if(!v9($)||Object.keys($).length!==2||typeof $.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:I0($.binding),deviceRelayUrl:c9($.deviceRelayUrl,"device")}}function g$($){if(!v9($)||Object.keys($).length!==1||!("binding"in $))throw Error("preview_close_invalid");return{binding:I0($.binding)}}import{request as D4}from"http";import{pipeline as _4}from"stream";import{constants as x8,createBrotliCompress as A4,createGzip as x4}from"zlib";import{WebSocket as O9}from"ws";import{randomBytes as q4,timingSafeEqual as T4}from"crypto";import{createServer as O4}from"net";var m$="x-preview-connection";async function y$($,Q){if(Q.aborted)throw Error("preview_closed");let Z=q4(32).toString("base64url"),X=new Set,J=!1,Y=O4((G)=>{if(J||Q.aborted||X.size>=v.streams*2)return G.destroy();X.add(G);let F=new AbortController;G.once("close",()=>{X.delete(G),F.abort()}),G.on("error",()=>G.destroy()),G.setTimeout(2000,()=>G.destroy());let B=Buffer.alloc(0),H=(L)=>{B=Buffer.concat([B,L]);let W=B.indexOf(`\r
3
3
  \r
4
4
  `);if(W<0){if(B.length>16384)G.destroy();return}if(G.pause(),G.off("data",H),W>16384||B.length>v.upload+16384)return G.destroy();z(B,W).catch(()=>G.destroy())};G.on("data",H);async function z(L,W){let U=L.subarray(0,W).toString("latin1").split(`\r
5
5
  `),j=/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) (\S+) HTTP\/1\.1$/.exec(U.shift()??"");if(!j)throw Error("preview_request_invalid");q9(j[2]);let O=!1,q=0,A=[];for(let T of U){let S=/^([a-zA-Z0-9-]+):[ \t]*([^\x00-\x08\x0a-\x1f\x7f]*)$/.exec(T);if(!S)throw Error("preview_header_invalid");if(S[1].toLowerCase()===m$){q++;let g=Buffer.from(S[2].trim());O=g.length===Z.length&&T4(g,Buffer.from(Z))}else if(S[1].toLowerCase()!=="host")A.push(T)}if(!O||q!==1||J||F.signal.aborted)throw Error("preview_connection_denied");let R=await $.connect(F.signal);if(J||F.signal.aborted)throw R.destroy(),Error("preview_closed");X.add(R),R.on("error",()=>G.destroy()),R.once("close",()=>{X.delete(R),G.destroy()}),G.once("close",()=>R.destroy()),G.setTimeout(0);let P=[`${j[1]} ${j[2]} HTTP/1.1`,`Host: 127.0.0.1:${R.remotePort}`,...A,"",""].join(`\r
@@ -303,7 +303,7 @@ async (input) => {
303
303
  if (!bridge || typeof bridge.evaluate !== "function") throw new Error("Reason Hands browser bridge is not installed");
304
304
  return await bridge.evaluate(typeof input === "string" ? input : input && input.code);
305
305
  }
306
- `.trim();import{Buffer as X9}from"buffer";import{randomUUID as z1}from"crypto";class tQ extends Error{code;constructor($){super($==="hands_repl_private_profile_attribute_denied"?"Private browser attribute read denied.":$);this.code=$;this.name="HandsReplBrowserDispatcherError"}}var eQ=new Set(["__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","__proto__","constructor","prototype"]),aQ=/^hands_[A-Za-z0-9_-]{8,128}$/,K1=2048,$Z=32,QZ=1e4,V1=new Set(["href","src","alt","title","role","aria-label","aria-expanded","aria-checked","aria-selected","aria-disabled","placeholder","type","name","data-testid"]);function F1($){let Q=$.split("+"),Z=(Q.pop()??"").replace(/^Key/,"").toLowerCase();if(Z==="f12")return!0;if(Q.some((X)=>["Control","ControlOrMeta","Meta"].includes(X))&&["l","n","t","j","i","p","s","w","u","o","r","tab","pageup","pagedown"].includes(Z))return!0;if(Q.some((X)=>["Control","ControlOrMeta","Meta"].includes(X))&&Q.includes("Shift")&&Z==="c")return!0;return Q.includes("Alt")&&["d","arrowleft","arrowright","home"].includes(Z)}var H1=($)=>{let Q=$.closest("a[href],area[href]");return{password:$.tagName==="INPUT"&&$.type==="password",executableLink:Boolean(Q&&!/^(https?:|about:blank)/i.test(Q.href))}},ZZ={browser:{close:{returns:"void"},contexts:{returns:"context[]"},isConnected:{returns:"json"},version:{returns:"json"}},context:{addCookies:{returns:"void"},addInitScript:{returns:"void"},browser:{returns:"browser"},clearCookies:{returns:"void"},clearPermissions:{returns:"void"},close:{returns:"void"},cookies:{returns:"json"},grantPermissions:{returns:"void"},newPage:{returns:"page"},pages:{returns:"page[]"},setDefaultNavigationTimeout:{returns:"void"},setDefaultTimeout:{returns:"void"},setExtraHTTPHeaders:{returns:"void"},setGeolocation:{returns:"void"},setHTTPCredentials:{returns:"void"},setOffline:{returns:"void"},setViewportSize:{returns:"void"},storageState:{returns:"json"},viewportSize:{returns:"json",special:"contextViewportSize"}},page:{addInitScript:{returns:"void"},addScriptTag:{returns:"void"},addStyleTag:{returns:"void"},bringToFront:{returns:"void"},close:{returns:"void"},content:{returns:"json"},context:{returns:"context"},emulateMedia:{returns:"void"},evaluate:{returns:"json",requiresStringSource:!0},frame:{returns:"frame"},frameLocator:{returns:"frameLocator"},frames:{returns:"frame[]"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},goBack:{returns:"void"},goForward:{returns:"void"},goto:{returns:"void"},isClosed:{returns:"json"},locator:{returns:"locator"},mainFrame:{returns:"frame"},opener:{returns:"page"},pdf:{returns:"bytes"},reload:{returns:"void"},screenshot:{returns:"bytes"},selectOption:{returns:"json"},setContent:{returns:"void"},setDefaultNavigationTimeout:{returns:"void"},setDefaultTimeout:{returns:"void"},setExtraHTTPHeaders:{returns:"void"},setInputFiles:{returns:"void"},setViewportSize:{returns:"void"},title:{returns:"json"},url:{returns:"json"},viewportSize:{returns:"json"},waitForFunction:{returns:"void",requiresStringSource:!0},waitForLoadState:{returns:"void"},waitForNavigation:{returns:"void"},waitForTimeout:{returns:"void"},waitForURL:{returns:"void"}},locator:{all:{returns:"locator[]"},allInnerTexts:{returns:"json"},allTextContents:{returns:"json"},and:{returns:"locator"},ariaSnapshot:{returns:"json"},blur:{returns:"void"},boundingBox:{returns:"json"},check:{returns:"void"},clear:{returns:"void"},click:{returns:"void"},contentFrame:{returns:"frameLocator"},count:{returns:"json"},dblclick:{returns:"void"},dragTo:{returns:"void"},evaluate:{returns:"json",requiresStringSource:!0},evaluateAll:{returns:"json",requiresStringSource:!0},fill:{returns:"void"},filter:{returns:"locator"},first:{returns:"locator",special:"property"},focus:{returns:"void"},getAttribute:{returns:"json"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},hover:{returns:"void"},innerHTML:{returns:"json"},innerText:{returns:"json"},inputValue:{returns:"json"},isChecked:{returns:"json"},isEditable:{returns:"json"},isEnabled:{returns:"json"},isHidden:{returns:"json"},isVisible:{returns:"json"},last:{returns:"locator",special:"property"},locator:{returns:"locator"},nth:{returns:"locator"},or:{returns:"locator"},page:{returns:"page"},press:{returns:"void"},pressSequentially:{returns:"void"},scrollIntoViewIfNeeded:{returns:"void"},screenshot:{returns:"bytes"},selectOption:{returns:"json"},setInputFiles:{returns:"void"},tap:{returns:"void"},textContent:{returns:"json"},type:{returns:"void"},uncheck:{returns:"void"},waitFor:{returns:"void"}},frame:{addScriptTag:{returns:"void"},addStyleTag:{returns:"void"},childFrames:{returns:"frame[]"},content:{returns:"json"},evaluate:{returns:"json",requiresStringSource:!0},frameLocator:{returns:"frameLocator"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},goto:{returns:"void"},isDetached:{returns:"json"},locator:{returns:"locator"},name:{returns:"json"},page:{returns:"page"},parentFrame:{returns:"frame"},setContent:{returns:"void"},title:{returns:"json"},url:{returns:"json"},waitForFunction:{returns:"void",requiresStringSource:!0},waitForLoadState:{returns:"void"},waitForNavigation:{returns:"void"},waitForTimeout:{returns:"void"},waitForURL:{returns:"void"}},frameLocator:{getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},locator:{returns:"locator"},owner:{returns:"locator"}}};function I($){throw new tQ($)}function z0($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let Q=Object.getPrototypeOf($);return Q===Object.prototype||Q===null}function J9($,Q=0,Z={nodes:0}){if(Q>$Z||++Z.nodes>QZ)I("hands_repl_json_too_complex");if($===null||typeof $==="boolean"||typeof $==="string")return;if(typeof $==="number"){if(!Number.isFinite($))I("hands_repl_invalid_json");return}if(Array.isArray($)){for(let X of $)J9(X,Q+1,Z);return}if(!z0($))I("hands_repl_invalid_json");for(let[X,J]of Object.entries($)){if(eQ.has(X))I("hands_repl_invalid_json");J9(J,Q+1,Z)}}function v8($){return typeof $==="string"&&Object.hasOwn(ZZ,$)}function U1($){if(!$.endsWith("[]"))return null;let Q=$.slice(0,-2);return v8(Q)?Q:null}function oQ($){return z0($)&&Object.keys($).length===2&&$.$handsRepl==="bytes"&&typeof $.base64==="string"}function W1($){return z0($)&&Object.keys($).length===1&&$.$handsRepl==="undefined"}function rQ($){return z0($)&&Object.keys($).length===2&&$.$handsRepl==="routeFulfill"&&"options"in $}function k0($){return!!$&&typeof $==="object"}function t9(){return Object.freeze({$handsRepl:"undefined"})}function B1($){if(!X9.isBuffer($)&&!($ instanceof Uint8Array))I("hands_repl_expected_bytes");return Object.freeze({$handsRepl:"bytes",base64:X9.from($).toString("base64")})}function XZ($){if(!k0($.browser)||!k0($.context)||!k0($.page))I("hands_repl_invalid_roots");if(typeof $.a11y!=="function"||typeof $.view!=="function")I("hands_repl_invalid_callbacks");let Q=$.maxHandles??K1;if(!Number.isInteger(Q)||Q<3||Q>1e5)I("hands_repl_invalid_handle_limit");let Z=new Map,X=new WeakMap,J=$.createOpaqueId??z1,Y=(z,L)=>{if(!k0(L))I("hands_repl_expected_target");let W=X.get(L)?.get(z);if(W)return W;if(Z.size>=Q)I("hands_repl_handle_limit");let U="";for(let q=0;q<16;q+=1){let A=`hands_${J()}`;if(aQ.test(A)&&!Z.has(A)){U=A;break}}if(!U)I("hands_repl_invalid_opaque_id");let j=Object.freeze({$handsRepl:"handle",id:U,kind:z});Z.set(U,{kind:z,target:L});let O=X.get(L);if(!O)O=new Map,X.set(L,O);return O.set(z,j),j},K=Object.freeze({browser:Y("browser",$.browser),context:Y("context",$.context),page:Y("page",$.page)}),V=(z)=>{if(!z0(z)||Object.keys(z).length!==3||z.$handsRepl!=="handle"||typeof z.id!=="string"||!aQ.test(z.id)||!v8(z.kind))I("hands_repl_invalid_handle");let L=Z.get(z.id);if(!L||L.kind!==z.kind)I("hands_repl_unknown_handle");return L},G=(z,L=0,W=new Set)=>{if(L>$Z)I("hands_repl_json_too_complex");if(z===void 0)return t9();if(z===null||typeof z==="boolean"||typeof z==="string")return z;if(typeof z==="number"){if(!Number.isFinite(z))I("hands_repl_non_json_result");return z}if(Array.isArray(z)){if(W.has(z))I("hands_repl_cyclic_result");W.add(z);try{return z.map((U)=>G(U,L+1,W))}finally{W.delete(z)}}if(!z0(z))I("hands_repl_non_json_result");if(W.has(z))I("hands_repl_cyclic_result");W.add(z);try{let U=Object.create(null);for(let j of Object.keys(z)){let O=Object.getOwnPropertyDescriptor(z,j);if(!O||!("value"in O))continue;U[j]=G(O.value,L+1,W)}return U}finally{W.delete(z)}},F=(z,L)=>{if(L==="void")return t9();if(L==="json")return G(z);if(L==="bytes")return B1(z);let W=U1(L);if(W){if(!Array.isArray(z))I("hands_repl_expected_target_list");if(W==="context"&&z.some((U)=>U!==$.context))I("hands_repl_foreign_context");return z.map((U)=>Y(W,U))}if(z===null||z===void 0)return t9();if(!v8(L))I("hands_repl_invalid_return_kind");if(L==="context"&&z!==$.context)I("hands_repl_foreign_context");return Y(L,z)},B=(z)=>{if(z0(z)&&z.$handsRepl==="handle")return V(z).target;if(oQ(z))return X9.from(z.base64,"base64");if(W1(z))return;if(rQ(z))I("hands_repl_route_fulfill_only");if(Array.isArray(z))return z.map(B);if(!z0(z))return z;let L=Object.create(null);for(let[W,U]of Object.entries(z))L[W]=B(U);return L};return Object.freeze({roots:K,dispatch:async(z)=>{if(!z0(z)||typeof z.type!=="string")I("hands_repl_invalid_request");if(z.type==="a11y"){let T=z.target===void 0?Z.get(K.page.id):V(z.target);if(!T||T.kind!=="page"&&T.kind!=="locator")I("hands_repl_invalid_a11y_target");return G(await $.a11y(T.target))}if(z.type==="view"){if(J9(z.source),z.options!==void 0)J9(z.options);let T=oQ(z.source)?X9.from(z.source.base64,"base64"):z.source;if($.privateProfile&&!X9.isBuffer(T))I("hands_repl_profile_requires_image_bytes");return G(await $.view(T,z.options))}if(z.type!=="call")I("hands_repl_invalid_request");if(typeof z.method!=="string"||z.method.length===0||z.method.length>128)I("hands_repl_invalid_method");if(eQ.has(z.method))I("hands_repl_forbidden_method");let L=V(z.target),W=z.args??[];if(!Array.isArray(W))I("hands_repl_invalid_arguments");if(J9(W),L.kind==="page"&&z.method==="captureScreenshot"){if(W.length!==0)I("hands_repl_invalid_arguments");if(!$.screenshotExport)I("hands_repl_screenshot_export_unavailable");return G(await $.screenshotExport(L.target))}if(L.kind==="context"&&["startRecording","stopRecording"].includes(z.method)){if(!$.recording||L.target!==$.context)I("hands_repl_recording_unavailable");if(W.length>(z.method==="startRecording"?1:0))I("hands_repl_invalid_arguments");return G(z.method==="startRecording"?await $.recording.start(W[0]):await $.recording.stop())}if($.privateProfile){let T=z.method;if(["evaluate","evaluateAll","waitForFunction","addInitScript","addScriptTag","addStyleTag","setContent","setInputFiles","route","content","cookies","storageState","addCookies","clearCookies","setExtraHTTPHeaders","setHTTPCredentials","grantPermissions","clearPermissions","innerHTML","textContent","allTextContents"].includes(T)||L.kind==="browser"&&T==="close"||L.kind==="context"&&T==="close")I("hands_repl_private_profile_method_denied");if(L.kind==="browser"&&T==="contexts")return F([$.context],"context[]");if((T==="screenshot"||T==="pdf")&&z0(W[0])&&(("path"in W[0])||("style"in W[0])))I("hands_repl_private_profile_path_denied");if(T==="goto"){if(typeof W[0]!=="string")I("hands_repl_private_profile_url_denied");try{let S=new URL(W[0]);if(!["http:","https:"].includes(S.protocol)&&W[0]!=="about:blank")I("hands_repl_private_profile_url_denied")}catch{I("hands_repl_private_profile_url_denied")}}if(T==="getAttribute"&&(typeof W[0]!=="string"||!V1.has(W[0].toLowerCase())))I("hands_repl_private_profile_attribute_denied");if(L.kind==="locator"&&["innerText","allInnerTexts","getAttribute"].includes(T)){let S=[L.target];if(T==="allInnerTexts"){let g=Reflect.get(L.target,"all");if(typeof g!=="function")I("hands_repl_private_profile_probe_unavailable");let E=await Reflect.apply(g,L.target,[]);if(!Array.isArray(E)||E.length>QZ||!E.every(k0))I("hands_repl_private_profile_probe_unavailable");S=E}for(let g of S){let E=Reflect.get(g,"isVisible");if(typeof E!=="function"||!await Reflect.apply(E,g,[]))I("hands_repl_private_profile_hidden_value_denied")}}if(T==="press"&&typeof W[0]==="string"&&F1(W[0]))I("hands_repl_private_profile_browser_shortcut_denied");if(L.kind==="locator"&&["inputValue","click","dblclick","tap","press"].includes(T)){let S=Reflect.get(L.target,"evaluate");if(typeof S!=="function")I("hands_repl_private_profile_probe_unavailable");let g=await Reflect.apply(S,L.target,[H1]);if(!z0(g)||typeof g.password!=="boolean"||typeof g.executableLink!=="boolean")I("hands_repl_private_profile_probe_unavailable");if(T==="inputValue"&&g.password)I("hands_repl_private_profile_password_denied");if(T!=="inputValue"&&g.executableLink)I("hands_repl_private_profile_url_denied");if(T==="inputValue"){let E=Reflect.get(L.target,"isVisible");if(typeof E!=="function"||!await Reflect.apply(E,L.target,[]))I("hands_repl_private_profile_hidden_value_denied")}}}let U=ZZ[L.kind][z.method];if(!U)I("hands_repl_method_not_allowed");if(U.requiresStringSource&&typeof W[0]!=="string")I("hands_repl_string_source_required");if(L.kind==="browser"&&z.method==="contexts")return[K.context];if(["addInitScript","addScriptTag","addStyleTag","screenshot","pdf","storageState"].includes(z.method)&&W.some((T)=>z0(T)&&("path"in T)))I("hands_repl_file_path_not_allowed");if(z.method==="goto"&&typeof W[0]==="string"){let T;try{T=new URL(W[0]).protocol}catch{I("hands_repl_invalid_url")}if(!["http:","https:","data:","about:","blob:"].includes(T))I("hands_repl_file_path_not_allowed")}if(U.special==="contextViewportSize"){let T=Reflect.get(L.target,"pages");if(typeof T!=="function")I("hands_repl_method_unavailable");let S=await Reflect.apply(T,L.target,[]),g=Array.isArray(S)?S[0]:void 0,E=k0(g)?Reflect.get(g,"viewportSize"):void 0;if(typeof E!=="function")return t9();return F(await Reflect.apply(E,g,[]),U.returns)}if(U.special==="property"){let T=Reflect.get(L.target,z.method);return F(typeof T==="function"?Reflect.apply(T,L.target,[]):T,U.returns)}let j=Reflect.get(L.target,z.method);if(typeof j!=="function")I("hands_repl_method_unavailable");if(U.special==="route"){let T=W[1];if(!rQ(T))I("hands_repl_invalid_route_handler");J9(T.options);let S=B(T.options),g=async(M)=>{if(!k0(M))I("hands_repl_invalid_route");let D=Reflect.get(M,"fulfill");if(typeof D!=="function")I("hands_repl_invalid_route");await Reflect.apply(D,M,[S])},E=[B(W[0]??null),g],N=await Reflect.apply(j,L.target,E);return F(N,U.returns)}let O=W.map(B);if(z.method==="setInputFiles"){let T=L.kind==="locator"?0:1,S=async(E)=>{if(typeof E!=="string"){if(!z0(E)||typeof E.name!=="string"||typeof E.mimeType!=="string"||!X9.isBuffer(E.buffer))I("hands_repl_invalid_file_input");return E}if(!$.readWorkspaceFile)I("hands_repl_workspace_required");return $.readWorkspaceFile(E)},g=O[T];O[T]=Array.isArray(g)?await Promise.all(g.map(S)):await S(g)}if(z.method==="goto")await $.beforeNavigation?.();let q=$.actionRecorder?.(),A=await Reflect.apply(j,L.target,O),P={click:"Click browser element",tap:"Click browser element",dblclick:"Double click browser element",fill:"Type text",type:"Type text",pressSequentially:"Type text",clear:"Clear browser field",press:"Press key",scrollIntoViewIfNeeded:"Scroll browser element into view",dragTo:"Drag on computer",selectOption:"Select browser option",check:"Check browser control",uncheck:"Uncheck browser control",hover:"Hover browser element",focus:"Focus browser element",goto:"Open browser page",reload:"Reload browser page",goBack:"Go back in browser",goForward:"Go forward in browser",screenshot:"Take browser screenshot"}[z.method];if(P){let T=Reflect.get(L.target,"page"),S=L.kind==="page"?L.target:typeof T==="function"?Reflect.apply(T,L.target,[]):void 0;q?.(P,k0(S)?S:void 0)}return F(A,U.returns)}})}import{isIP as KZ}from"net";import{Resolver as L1}from"dns/promises";import{isIP as $8}from"net";var N1=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]];function c8($){if($8($)!==4)return null;let Q=$.split(".");if(Q.length!==4)return null;let Z=0;for(let X of Q){let J=Number(X);if(!Number.isInteger(J)||J<0||J>255)return null;Z=Z*256+J}return Z>>>0}function M1($,Q,Z){let X=c8(Q);if(X===null)return!1;let J=Z===0?0:4294967295<<32-Z>>>0;return($&J)>>>0===(X&J)>>>0}function JZ($){let Q=c8($);if(Q===null)return!0;return N1.some(([Z,X])=>M1(Q,Z,X))}function j1($){if($8($)!==6)return null;let Q=$.toLowerCase(),Z=Q.indexOf("%");if(Z>=0)Q=Q.slice(0,Z);let X=[],J=Q.lastIndexOf(":"),Y=J>=0?Q.slice(J+1):"";if(Y.includes(".")){let z=c8(Y);if(z===null)return null;X=[z>>>16&65535,z&65535],Q=Q.slice(0,J+1)+"0:0"}let K=Q.split("::");if(K.length>2)return null;let V=(z)=>{if(z==="")return[];let L=[];for(let W of z.split(":")){if(W===""||W.length>4||!/^[0-9a-f]+$/.test(W))return null;L.push(Number.parseInt(W,16))}return L},G=V(K[0]??"");if(G===null)return null;if(K.length===1){let z=G;if(z.length!==8)return null;return X.length>0?z.slice(0,6).concat(X):z}let F=V(K[1]??"");if(F===null)return null;let B=8-G.length-F.length;if(B<0)return null;let H=G.concat(Array(B).fill(0),F);if(H.length!==8)return null;return X.length>0?H.slice(0,6).concat(X):H}function C1($,Q){return`${$>>8&255}.${$&255}.${Q>>8&255}.${Q&255}`}function q1($){let Q=j1($);if(Q===null)return!0;let[Z,X,J]=Q;if((Z&57344)!==8192)return!0;if(Z===8193&&(X&65024)===0)return!0;if(Z===8193&&X===3512)return!0;if(Z===16383&&(X&61440)===0)return!0;if(Z===8194)return JZ(C1(X,J));return!1}function YZ($){return $.replace(/^\[|\]$/g,"")}function e9($){let Q=YZ($.trim()),Z=$8(Q);if(Z===4)return JZ(Q);if(Z===6)return q1(Q);return!0}function GZ($){if($ instanceof Error&&$.name==="TimeoutError")return"dns_timeout";switch(typeof $==="object"&&$!==null&&"code"in $?$.code:void 0){case"ENOTFOUND":return"dns_not_found";case"ENODATA":return"dns_empty";case"EAI_AGAIN":case"ESERVFAIL":case"ECONNREFUSED":return"dns_temporary";case"ETIMEOUT":case"ETIMEDOUT":return"dns_timeout";default:return"dns_failed"}}var zZ=5000;function T1($){return async(Q,Z)=>{if(Z?.aborted)throw Error("aborted");let X=new L1({timeout:zZ,tries:1});if($)X.setServers($);let J=()=>X.cancel();Z?.addEventListener("abort",J,{once:!0});try{let[Y,K]=await Promise.allSettled([X.resolve4(Q),X.resolve6(Q)]),V=[...Y.status==="fulfilled"?Y.value:[],...K.status==="fulfilled"?K.value:[]];if(V.length>0)return V;let G=[Y,K].flatMap((B)=>B.status==="rejected"?[B.reason]:[]);throw G.find((B)=>["dns_temporary","dns_timeout"].includes(GZ(B)))??G[0]??Object.assign(Error("DNS returned no addresses"),{code:"ENODATA"})}finally{Z?.removeEventListener("abort",J)}}}var O1=T1();async function D1($,Q,Z,X){if(X?.aborted)throw Error("aborted");let J=new AbortController,Y,K,V=Q($,J.signal);V.catch(()=>{});try{return await Promise.race([V,new Promise((G,F)=>{if(Y=setTimeout(()=>F(new DOMException("DNS lookup timed out","TimeoutError")),Z),X)K=()=>F(Error("aborted")),X.addEventListener("abort",K,{once:!0})})])}finally{if(Y!==void 0)clearTimeout(Y);if(X&&K)X.removeEventListener("abort",K);J.abort()}}async function XX($,Q=O1,Z){let X=YZ($);if($8(X))return e9(X)?{ok:!1,reason:"non_public_ip"}:{ok:!0,addresses:[X]};let J;try{J=await D1(X,Q,zZ,Z)}catch(Y){return{ok:!1,reason:Z?.aborted?Z.reason instanceof Error&&Z.reason.name==="TimeoutError"?"dns_timeout":"aborted":GZ(Y)}}if(J.length===0)return{ok:!1,reason:"dns_empty"};if(J.some(e9))return{ok:!1,reason:"non_public_ip"};return{ok:!0,addresses:J}}var _1=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;function d8($){return $.length<=253&&_1.test($.toLowerCase())}function A1($,Q){let Z=$.trim().toLowerCase();if(!d8(Z))return!1;if(Z.startsWith("*.")){let X=Z.slice(2);return Q===X||Q.endsWith(`.${X}`)}return Z===Q}function x1($){let Q=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec($);if(!Q)return null;let Z=Q.slice(1).map(Number);return Z.some((X)=>X>255)?null:Z}function p8($,Q=[]){let Z=(X)=>{if(X=X.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,""),!X.includes(":"))return X;try{X=new URL(`http://[${X}]/`).hostname.slice(1,-1)}catch{return X}let J=/^::ffff:([\da-f]+):([\da-f]+)$/.exec(X);if(!J)return X;let Y=parseInt(J[1],16),K=parseInt(J[2],16);return`${Y>>8}.${Y&255}.${K>>8}.${K&255}`};return Q.some((X)=>Z(X)===Z($))}function l0($){$=$.toLowerCase().replace(/^\[|\]$/g,"");let Q=x1($);if(Q){let[Y,K,V]=Q;if(Y===127)return"loopback";return Y===0||Y===10||Y>=224||Y===100&&K>=64&&K<=127||Y===169&&K===254||Y===172&&K>=16&&K<=31||Y===192&&(K===168||K===0&&(V===0||V===2)||K===88&&V===99)||Y===198&&(K===18||K===19||K===51&&V===100)||Y===203&&K===0&&V===113?"private":"public"}if(!$.includes(":"))return"hostname";try{$=new URL(`http://[${$}]/`).hostname.slice(1,-1)}catch{return"private"}if($==="::1")return"loopback";let Z=/^::ffff:([\da-f]+):([\da-f]+)$/.exec($);if(Z){let Y=parseInt(Z[1],16),K=parseInt(Z[2],16);return l0(`${Y>>8}.${Y&255}.${K>>8}.${K&255}`)==="public"?"public":"private"}let[X,J=0]=$.split(":").map((Y)=>parseInt(Y||"0",16));return X<8192||X>16383||X===8194||X===8193&&(J<512||J===3512)||X===16383&&J<4096?"private":"public"}function I9($,Q){let Z;try{Z=new URL($)}catch{return{allowed:!1,url:$,host:null,reason:"invalid_url"}}if(["about:","data:","blob:"].includes(Z.protocol))return{allowed:!0,url:$,host:null,reason:"local_document"};if(!["http:","https:","ws:","wss:"].includes(Z.protocol))return{allowed:!1,url:$,host:Z.hostname||null,reason:"unsupported_protocol"};let X=Z.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(Q.mode==="off")return{allowed:!0,url:$,host:X,reason:"policy_off"};let J=(V)=>({allowed:!1,url:$,host:X,reason:V});if(Z.username||Z.password)return J("invalid_url");if(Q.mode==="public_web"){let V=l0(X)!=="public"&&l0(X)!=="hostname"||X==="localhost"||/\.(?:localhost|local|internal|arpa)$/.test(X)||!X.includes(".")&&!KZ(X)||Boolean(KZ(X)&&e9(X));return{allowed:!V,url:$,host:X,reason:V?"private_network":"public_web"}}let Y=Number(Z.port||(["https:","wss:"].includes(Z.protocol)?443:80));if(Q.deniedPorts?.includes(Y)||p8(X,Q.deniedHosts))return J("destination_not_allowed");let K=l0(X);if(K==="private"||["local","internal","arpa"].some((V)=>X===V||X.endsWith(`.${V}`)))return J("private_network");if(K==="loopback"||X==="localhost"||X.endsWith(".localhost"))return Q.allowedLoopbackPorts?.includes(Y)?{allowed:!0,url:$,host:X,reason:"loopback"}:J("destination_not_allowed");if(Q.allowedDomains.some((V)=>A1(V,X)))return{allowed:!0,url:$,host:X,reason:"allowed_domain"};return{allowed:!1,url:$,host:X,reason:"destination_not_allowed"}}import FZ from"child_process";import{accessSync as I1,constants as R1,readFileSync as E1,statSync as WZ}from"fs";import{createRequire as BZ}from"module";import{homedir as HZ}from"os";import{dirname as S1,isAbsolute as l8,join as Y9,resolve as w1}from"path";var Q8=Object.freeze({schemaVersion:1,driver:"playwright-core",driverVersion:UZ.dependencies["playwright-core"],browser:"chromium"}),LZ=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Chromium.app/Contents/MacOS/Chromium"],u8=["/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/google-chrome","/usr/bin/google-chrome-stable"];function R9($){try{return I1($,R1.X_OK),l8($)&&WZ($).isFile()}catch{return!1}}function s8($,Q=process.platform){let Z=Q==="darwin"?LZ:Q==="linux"?u8:null;return Z?($??Z).find(R9)??null:null}function b1(){if(!process.versions.bun)return;let $=Symbol.for("ara.headless-browser.bun-pipe-owners");if(Object.hasOwn(globalThis,$))return;let Q=[];FZ.spawn=new Proxy(FZ.spawn,{apply(Z,X,J){let Y=Reflect.apply(Z,X,J),K=J[1],V=J[2]?.stdio;if(Array.isArray(K)&&K.includes("--remote-debugging-pipe")&&Array.isArray(V)&&V[3]==="pipe"&&V[4]==="pipe")Q.push(Y);return Y}}),Object.defineProperty(globalThis,$,{value:Q})}async function Z8($){if(b1(),$!==void 0){if(!l8($))throw Error("hands_browser_driver_path_must_be_absolute");let X=Y9($,"package.json"),J=JSON.parse(E1(X,"utf8"));if(J.name!==Q8.driver)throw Error("hands_browser_wrong_driver");let Y=BZ(X)($),K=Y.default?.chromium??Y.chromium;if(!K)throw Error("hands_browser_missing_chromium");return{version:J.version,chromium:K}}let[Q,Z]=await Promise.all([import("./index-5a4yhzf8.js"),import("./package-ffnz28tt.js").then((m)=>P1(m.default,1))]);return{version:Z.default.version,chromium:Q.chromium}}var k1=($,Q=Q8.driverVersion)=>({status:"unavailable",reason:$,expectedDriverVersion:Q}),f1=($)=>$.loadDriver?.()??Z8($.driverModuleDirectory),g1={"1.60.0":"1223"};function BX(){let $=process.platform,Q=g1[Q8.driverVersion];if(!Q||$!=="linux"&&$!=="darwin")return!1;let Z=(X)=>process.env[X]??process.env[`npm_config_${X.toLowerCase()}`]??process.env[`npm_package_config_${X.toLowerCase()}`];try{let X=Z("PLAYWRIGHT_BROWSERS_PATH"),J=X==="0"?Y9(S1(BZ(import.meta.url).resolve("playwright-core/package.json")),".local-browsers"):X?w1(Z("INIT_CWD")||process.cwd(),X):Y9($==="darwin"?Y9(HZ(),"Library","Caches"):process.env.XDG_CACHE_HOME||Y9(HZ(),".cache"),"ms-playwright");return WZ(Y9(J,`chromium-${Q}`,"INSTALLATION_COMPLETE")).isFile()}catch{return!1}}async function G9($={}){return NZ($,Q8.driverVersion)}async function n8($,Q={}){if($.driverVersion!=="1.61.1"||!l8($.driverModuleDirectory))throw Error("hands_browser_invalid_managed_compatibility");return NZ({...Q,driverModuleDirectory:$.driverModuleDirectory,allowSystemBrowser:!0},$.driverVersion)}async function NZ($,Q){let Z=(G)=>k1(G,Q),X=$.platform??process.platform;if(X!=="linux"&&X!=="darwin")return Z("unsupported_platform");let J;try{J=await f1($)}catch{return Z("driver_missing")}if(J.version!==Q)return Z("driver_version_mismatch");let Y=(G,F)=>({status:"resolved",executablePath:G,source:F,driverVersion:J.version});if($.executablePath!==void 0)return R9($.executablePath)?Y($.executablePath,"configured"):Z("executable_missing");let K=J.chromium.executablePath();if(R9(K))return Y(K,"managed");let V=$.allowSystemBrowser===!0?s8($.systemCandidates,X):null;return V?Y(V,"system"):Z("executable_missing")}var a1=["/usr/local/bin/chromium",...u8];function o1($,Q=DZ()){return s8($??(Q==="linux"?a1:void 0),Q)}async function r1(){try{return(await Z8()).chromium}catch{return l1(import.meta.url)("playwright-core").chromium}}var t1=1048576,e1=105000,$7=20000,CZ=5000,Q7=2000,Z7=1000,X7=30000,qZ=81920,J7={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif"};async function Y7($,Q){let Z=new URL($.url()),X={...await $.allHeaders(),host:Z.host};for(let J of Object.keys(X))if(/^(?:proxy-|connection$|upgrade$|transfer-encoding$|content-length$)/i.test(J))delete X[J];return new Promise((J,Y)=>{let V=(Z.protocol==="https:"?s1:u1)(Z,{method:$.method(),headers:X,agent:!1,lookup:(F,B,H)=>{let z=u0.isIP(Q);if(B.all)H(null,[{address:Q,family:z}]);else H(null,Q,z)}},(F)=>{let B=[],H=0;F.on("data",(z)=>{if(H+=z.length,H>33554432)V.destroy(Error("hands_browser_response_too_large"));else B.push(z)}),F.on("error",Y),F.on("end",()=>{let z={};for(let[L,W]of Object.entries(F.headers))if(W!==void 0&&!["transfer-encoding","connection","content-length"].includes(L))z[L]=Array.isArray(W)?W.join(`
306
+ `.trim();import{Buffer as X9}from"buffer";import{randomUUID as z1}from"crypto";class tQ extends Error{code;constructor($){super($==="hands_repl_private_profile_attribute_denied"?"Private browser attribute read denied.":$);this.code=$;this.name="HandsReplBrowserDispatcherError"}}var eQ=new Set(["__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","__proto__","constructor","prototype"]),aQ=/^hands_[A-Za-z0-9_-]{8,128}$/,K1=2048,$Z=32,QZ=1e4,V1=new Set(["href","src","alt","title","role","aria-label","aria-expanded","aria-checked","aria-selected","aria-disabled","placeholder","type","name","data-testid"]);function F1($){let Q=$.split("+"),Z=(Q.pop()??"").replace(/^Key/,"").toLowerCase();if(Z==="f12")return!0;if(Q.some((X)=>["Control","ControlOrMeta","Meta"].includes(X))&&["l","n","t","j","i","p","s","w","u","o","r","tab","pageup","pagedown"].includes(Z))return!0;if(Q.some((X)=>["Control","ControlOrMeta","Meta"].includes(X))&&Q.includes("Shift")&&Z==="c")return!0;return Q.includes("Alt")&&["d","arrowleft","arrowright","home"].includes(Z)}var H1=($)=>{let Q=$.closest("a[href],area[href]");return{password:$.tagName==="INPUT"&&$.type==="password",executableLink:Boolean(Q&&!/^(https?:|about:blank)/i.test(Q.href))}},ZZ={browser:{close:{returns:"void"},contexts:{returns:"context[]"},isConnected:{returns:"json"},version:{returns:"json"}},context:{addCookies:{returns:"void"},addInitScript:{returns:"void"},browser:{returns:"browser"},clearCookies:{returns:"void"},clearPermissions:{returns:"void"},close:{returns:"void"},cookies:{returns:"json"},grantPermissions:{returns:"void"},newPage:{returns:"page"},pages:{returns:"page[]"},setDefaultNavigationTimeout:{returns:"void"},setDefaultTimeout:{returns:"void"},setExtraHTTPHeaders:{returns:"void"},setGeolocation:{returns:"void"},setHTTPCredentials:{returns:"void"},setOffline:{returns:"void"},setViewportSize:{returns:"void"},storageState:{returns:"json"},viewportSize:{returns:"json",special:"contextViewportSize"}},page:{addInitScript:{returns:"void"},addScriptTag:{returns:"void"},addStyleTag:{returns:"void"},bringToFront:{returns:"void"},close:{returns:"void"},content:{returns:"json"},context:{returns:"context"},emulateMedia:{returns:"void"},evaluate:{returns:"json",requiresStringSource:!0},frame:{returns:"frame"},frameLocator:{returns:"frameLocator"},frames:{returns:"frame[]"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},goBack:{returns:"void"},goForward:{returns:"void"},goto:{returns:"void"},isClosed:{returns:"json"},locator:{returns:"locator"},mainFrame:{returns:"frame"},opener:{returns:"page"},pdf:{returns:"bytes"},reload:{returns:"void"},screenshot:{returns:"bytes"},selectOption:{returns:"json"},setContent:{returns:"void"},setDefaultNavigationTimeout:{returns:"void"},setDefaultTimeout:{returns:"void"},setExtraHTTPHeaders:{returns:"void"},setInputFiles:{returns:"void"},setViewportSize:{returns:"void"},title:{returns:"json"},url:{returns:"json"},viewportSize:{returns:"json"},waitForFunction:{returns:"void",requiresStringSource:!0},waitForLoadState:{returns:"void"},waitForNavigation:{returns:"void"},waitForTimeout:{returns:"void"},waitForURL:{returns:"void"}},locator:{all:{returns:"locator[]"},allInnerTexts:{returns:"json"},allTextContents:{returns:"json"},and:{returns:"locator"},ariaSnapshot:{returns:"json"},blur:{returns:"void"},boundingBox:{returns:"json"},check:{returns:"void"},clear:{returns:"void"},click:{returns:"void"},contentFrame:{returns:"frameLocator"},count:{returns:"json"},dblclick:{returns:"void"},dragTo:{returns:"void"},evaluate:{returns:"json",requiresStringSource:!0},evaluateAll:{returns:"json",requiresStringSource:!0},fill:{returns:"void"},filter:{returns:"locator"},first:{returns:"locator",special:"property"},focus:{returns:"void"},getAttribute:{returns:"json"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},hover:{returns:"void"},innerHTML:{returns:"json"},innerText:{returns:"json"},inputValue:{returns:"json"},isChecked:{returns:"json"},isEditable:{returns:"json"},isEnabled:{returns:"json"},isHidden:{returns:"json"},isVisible:{returns:"json"},last:{returns:"locator",special:"property"},locator:{returns:"locator"},nth:{returns:"locator"},or:{returns:"locator"},page:{returns:"page"},press:{returns:"void"},pressSequentially:{returns:"void"},scrollIntoViewIfNeeded:{returns:"void"},screenshot:{returns:"bytes"},selectOption:{returns:"json"},setInputFiles:{returns:"void"},tap:{returns:"void"},textContent:{returns:"json"},type:{returns:"void"},uncheck:{returns:"void"},waitFor:{returns:"void"}},frame:{addScriptTag:{returns:"void"},addStyleTag:{returns:"void"},childFrames:{returns:"frame[]"},content:{returns:"json"},evaluate:{returns:"json",requiresStringSource:!0},frameLocator:{returns:"frameLocator"},getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},goto:{returns:"void"},isDetached:{returns:"json"},locator:{returns:"locator"},name:{returns:"json"},page:{returns:"page"},parentFrame:{returns:"frame"},setContent:{returns:"void"},title:{returns:"json"},url:{returns:"json"},waitForFunction:{returns:"void",requiresStringSource:!0},waitForLoadState:{returns:"void"},waitForNavigation:{returns:"void"},waitForTimeout:{returns:"void"},waitForURL:{returns:"void"}},frameLocator:{getByAltText:{returns:"locator"},getByLabel:{returns:"locator"},getByPlaceholder:{returns:"locator"},getByRole:{returns:"locator"},getByTestId:{returns:"locator"},getByText:{returns:"locator"},getByTitle:{returns:"locator"},locator:{returns:"locator"},owner:{returns:"locator"}}};function I($){throw new tQ($)}function z0($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let Q=Object.getPrototypeOf($);return Q===Object.prototype||Q===null}function J9($,Q=0,Z={nodes:0}){if(Q>$Z||++Z.nodes>QZ)I("hands_repl_json_too_complex");if($===null||typeof $==="boolean"||typeof $==="string")return;if(typeof $==="number"){if(!Number.isFinite($))I("hands_repl_invalid_json");return}if(Array.isArray($)){for(let X of $)J9(X,Q+1,Z);return}if(!z0($))I("hands_repl_invalid_json");for(let[X,J]of Object.entries($)){if(eQ.has(X))I("hands_repl_invalid_json");J9(J,Q+1,Z)}}function v8($){return typeof $==="string"&&Object.hasOwn(ZZ,$)}function U1($){if(!$.endsWith("[]"))return null;let Q=$.slice(0,-2);return v8(Q)?Q:null}function oQ($){return z0($)&&Object.keys($).length===2&&$.$handsRepl==="bytes"&&typeof $.base64==="string"}function W1($){return z0($)&&Object.keys($).length===1&&$.$handsRepl==="undefined"}function rQ($){return z0($)&&Object.keys($).length===2&&$.$handsRepl==="routeFulfill"&&"options"in $}function k0($){return!!$&&typeof $==="object"}function t9(){return Object.freeze({$handsRepl:"undefined"})}function B1($){if(!X9.isBuffer($)&&!($ instanceof Uint8Array))I("hands_repl_expected_bytes");return Object.freeze({$handsRepl:"bytes",base64:X9.from($).toString("base64")})}function XZ($){if(!k0($.browser)||!k0($.context)||!k0($.page))I("hands_repl_invalid_roots");if(typeof $.a11y!=="function"||typeof $.view!=="function")I("hands_repl_invalid_callbacks");let Q=$.maxHandles??K1;if(!Number.isInteger(Q)||Q<3||Q>1e5)I("hands_repl_invalid_handle_limit");let Z=new Map,X=new WeakMap,J=$.createOpaqueId??z1,Y=(z,L)=>{if(!k0(L))I("hands_repl_expected_target");let W=X.get(L)?.get(z);if(W)return W;if(Z.size>=Q)I("hands_repl_handle_limit");let U="";for(let q=0;q<16;q+=1){let A=`hands_${J()}`;if(aQ.test(A)&&!Z.has(A)){U=A;break}}if(!U)I("hands_repl_invalid_opaque_id");let j=Object.freeze({$handsRepl:"handle",id:U,kind:z});Z.set(U,{kind:z,target:L});let O=X.get(L);if(!O)O=new Map,X.set(L,O);return O.set(z,j),j},K=Object.freeze({browser:Y("browser",$.browser),context:Y("context",$.context),page:Y("page",$.page)}),V=(z)=>{if(!z0(z)||Object.keys(z).length!==3||z.$handsRepl!=="handle"||typeof z.id!=="string"||!aQ.test(z.id)||!v8(z.kind))I("hands_repl_invalid_handle");let L=Z.get(z.id);if(!L||L.kind!==z.kind)I("hands_repl_unknown_handle");return L},G=(z,L=0,W=new Set)=>{if(L>$Z)I("hands_repl_json_too_complex");if(z===void 0)return t9();if(z===null||typeof z==="boolean"||typeof z==="string")return z;if(typeof z==="number"){if(!Number.isFinite(z))I("hands_repl_non_json_result");return z}if(Array.isArray(z)){if(W.has(z))I("hands_repl_cyclic_result");W.add(z);try{return z.map((U)=>G(U,L+1,W))}finally{W.delete(z)}}if(!z0(z))I("hands_repl_non_json_result");if(W.has(z))I("hands_repl_cyclic_result");W.add(z);try{let U=Object.create(null);for(let j of Object.keys(z)){let O=Object.getOwnPropertyDescriptor(z,j);if(!O||!("value"in O))continue;U[j]=G(O.value,L+1,W)}return U}finally{W.delete(z)}},F=(z,L)=>{if(L==="void")return t9();if(L==="json")return G(z);if(L==="bytes")return B1(z);let W=U1(L);if(W){if(!Array.isArray(z))I("hands_repl_expected_target_list");if(W==="context"&&z.some((U)=>U!==$.context))I("hands_repl_foreign_context");return z.map((U)=>Y(W,U))}if(z===null||z===void 0)return t9();if(!v8(L))I("hands_repl_invalid_return_kind");if(L==="context"&&z!==$.context)I("hands_repl_foreign_context");return Y(L,z)},B=(z)=>{if(z0(z)&&z.$handsRepl==="handle")return V(z).target;if(oQ(z))return X9.from(z.base64,"base64");if(W1(z))return;if(rQ(z))I("hands_repl_route_fulfill_only");if(Array.isArray(z))return z.map(B);if(!z0(z))return z;let L=Object.create(null);for(let[W,U]of Object.entries(z))L[W]=B(U);return L};return Object.freeze({roots:K,dispatch:async(z)=>{if(!z0(z)||typeof z.type!=="string")I("hands_repl_invalid_request");if(z.type==="a11y"){let T=z.target===void 0?Z.get(K.page.id):V(z.target);if(!T||T.kind!=="page"&&T.kind!=="locator")I("hands_repl_invalid_a11y_target");return G(await $.a11y(T.target))}if(z.type==="view"){if(J9(z.source),z.options!==void 0)J9(z.options);let T=oQ(z.source)?X9.from(z.source.base64,"base64"):z.source;if($.privateProfile&&!X9.isBuffer(T))I("hands_repl_profile_requires_image_bytes");return G(await $.view(T,z.options))}if(z.type!=="call")I("hands_repl_invalid_request");if(typeof z.method!=="string"||z.method.length===0||z.method.length>128)I("hands_repl_invalid_method");if(eQ.has(z.method))I("hands_repl_forbidden_method");let L=V(z.target),W=z.args??[];if(!Array.isArray(W))I("hands_repl_invalid_arguments");if(J9(W),L.kind==="page"&&z.method==="captureScreenshot"){if(W.length!==0)I("hands_repl_invalid_arguments");if(!$.screenshotExport)I("hands_repl_screenshot_export_unavailable");return G(await $.screenshotExport(L.target))}if(L.kind==="context"&&["startRecording","stopRecording"].includes(z.method)){if(!$.recording||L.target!==$.context)I("hands_repl_recording_unavailable");if(W.length>(z.method==="startRecording"?1:0))I("hands_repl_invalid_arguments");return G(z.method==="startRecording"?await $.recording.start(W[0]):await $.recording.stop())}if($.privateProfile){let T=z.method;if(["evaluate","evaluateAll","waitForFunction","addInitScript","addScriptTag","addStyleTag","setContent","setInputFiles","route","content","cookies","storageState","addCookies","clearCookies","setExtraHTTPHeaders","setHTTPCredentials","grantPermissions","clearPermissions","innerHTML","textContent","allTextContents"].includes(T)||L.kind==="browser"&&T==="close"||L.kind==="context"&&T==="close")I("hands_repl_private_profile_method_denied");if(L.kind==="browser"&&T==="contexts")return F([$.context],"context[]");if((T==="screenshot"||T==="pdf")&&z0(W[0])&&(("path"in W[0])||("style"in W[0])))I("hands_repl_private_profile_path_denied");if(T==="goto"){if(typeof W[0]!=="string")I("hands_repl_private_profile_url_denied");try{let S=new URL(W[0]);if(!["http:","https:"].includes(S.protocol)&&W[0]!=="about:blank")I("hands_repl_private_profile_url_denied")}catch{I("hands_repl_private_profile_url_denied")}}if(T==="getAttribute"&&(typeof W[0]!=="string"||!V1.has(W[0].toLowerCase())))I("hands_repl_private_profile_attribute_denied");if(L.kind==="locator"&&["innerText","allInnerTexts","getAttribute"].includes(T)){let S=[L.target];if(T==="allInnerTexts"){let g=Reflect.get(L.target,"all");if(typeof g!=="function")I("hands_repl_private_profile_probe_unavailable");let E=await Reflect.apply(g,L.target,[]);if(!Array.isArray(E)||E.length>QZ||!E.every(k0))I("hands_repl_private_profile_probe_unavailable");S=E}for(let g of S){let E=Reflect.get(g,"isVisible");if(typeof E!=="function"||!await Reflect.apply(E,g,[]))I("hands_repl_private_profile_hidden_value_denied")}}if(T==="press"&&typeof W[0]==="string"&&F1(W[0]))I("hands_repl_private_profile_browser_shortcut_denied");if(L.kind==="locator"&&["inputValue","click","dblclick","tap","press"].includes(T)){let S=Reflect.get(L.target,"evaluate");if(typeof S!=="function")I("hands_repl_private_profile_probe_unavailable");let g=await Reflect.apply(S,L.target,[H1]);if(!z0(g)||typeof g.password!=="boolean"||typeof g.executableLink!=="boolean")I("hands_repl_private_profile_probe_unavailable");if(T==="inputValue"&&g.password)I("hands_repl_private_profile_password_denied");if(T!=="inputValue"&&g.executableLink)I("hands_repl_private_profile_url_denied");if(T==="inputValue"){let E=Reflect.get(L.target,"isVisible");if(typeof E!=="function"||!await Reflect.apply(E,L.target,[]))I("hands_repl_private_profile_hidden_value_denied")}}}let U=ZZ[L.kind][z.method];if(!U)I("hands_repl_method_not_allowed");if(U.requiresStringSource&&typeof W[0]!=="string")I("hands_repl_string_source_required");if(L.kind==="browser"&&z.method==="contexts")return[K.context];if(["addInitScript","addScriptTag","addStyleTag","screenshot","pdf","storageState"].includes(z.method)&&W.some((T)=>z0(T)&&("path"in T)))I("hands_repl_file_path_not_allowed");if(z.method==="goto"&&typeof W[0]==="string"){let T;try{T=new URL(W[0]).protocol}catch{I("hands_repl_invalid_url")}if(!["http:","https:","data:","about:","blob:"].includes(T))I("hands_repl_file_path_not_allowed")}if(U.special==="contextViewportSize"){let T=Reflect.get(L.target,"pages");if(typeof T!=="function")I("hands_repl_method_unavailable");let S=await Reflect.apply(T,L.target,[]),g=Array.isArray(S)?S[0]:void 0,E=k0(g)?Reflect.get(g,"viewportSize"):void 0;if(typeof E!=="function")return t9();return F(await Reflect.apply(E,g,[]),U.returns)}if(U.special==="property"){let T=Reflect.get(L.target,z.method);return F(typeof T==="function"?Reflect.apply(T,L.target,[]):T,U.returns)}let j=Reflect.get(L.target,z.method);if(typeof j!=="function")I("hands_repl_method_unavailable");if(U.special==="route"){let T=W[1];if(!rQ(T))I("hands_repl_invalid_route_handler");J9(T.options);let S=B(T.options),g=async(M)=>{if(!k0(M))I("hands_repl_invalid_route");let D=Reflect.get(M,"fulfill");if(typeof D!=="function")I("hands_repl_invalid_route");await Reflect.apply(D,M,[S])},E=[B(W[0]??null),g],N=await Reflect.apply(j,L.target,E);return F(N,U.returns)}let O=W.map(B);if(z.method==="setInputFiles"){let T=L.kind==="locator"?0:1,S=async(E)=>{if(typeof E!=="string"){if(!z0(E)||typeof E.name!=="string"||typeof E.mimeType!=="string"||!X9.isBuffer(E.buffer))I("hands_repl_invalid_file_input");return E}if(!$.readWorkspaceFile)I("hands_repl_workspace_required");return $.readWorkspaceFile(E)},g=O[T];O[T]=Array.isArray(g)?await Promise.all(g.map(S)):await S(g)}if(z.method==="goto")await $.beforeNavigation?.();let q=$.actionRecorder?.(),A=await Reflect.apply(j,L.target,O),P={click:"Click browser element",tap:"Click browser element",dblclick:"Double click browser element",fill:"Type text",type:"Type text",pressSequentially:"Type text",clear:"Clear browser field",press:"Press key",scrollIntoViewIfNeeded:"Scroll browser element into view",dragTo:"Drag on computer",selectOption:"Select browser option",check:"Check browser control",uncheck:"Uncheck browser control",hover:"Hover browser element",focus:"Focus browser element",goto:"Open browser page",reload:"Reload browser page",goBack:"Go back in browser",goForward:"Go forward in browser",screenshot:"Take browser screenshot"}[z.method];if(P){let T=Reflect.get(L.target,"page"),S=L.kind==="page"?L.target:typeof T==="function"?Reflect.apply(T,L.target,[]):void 0;q?.(P,k0(S)?S:void 0)}return F(A,U.returns)}})}import{isIP as KZ}from"net";import{Resolver as L1}from"dns/promises";import{isIP as $8}from"net";var N1=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]];function c8($){if($8($)!==4)return null;let Q=$.split(".");if(Q.length!==4)return null;let Z=0;for(let X of Q){let J=Number(X);if(!Number.isInteger(J)||J<0||J>255)return null;Z=Z*256+J}return Z>>>0}function M1($,Q,Z){let X=c8(Q);if(X===null)return!1;let J=Z===0?0:4294967295<<32-Z>>>0;return($&J)>>>0===(X&J)>>>0}function JZ($){let Q=c8($);if(Q===null)return!0;return N1.some(([Z,X])=>M1(Q,Z,X))}function j1($){if($8($)!==6)return null;let Q=$.toLowerCase(),Z=Q.indexOf("%");if(Z>=0)Q=Q.slice(0,Z);let X=[],J=Q.lastIndexOf(":"),Y=J>=0?Q.slice(J+1):"";if(Y.includes(".")){let z=c8(Y);if(z===null)return null;X=[z>>>16&65535,z&65535],Q=Q.slice(0,J+1)+"0:0"}let K=Q.split("::");if(K.length>2)return null;let V=(z)=>{if(z==="")return[];let L=[];for(let W of z.split(":")){if(W===""||W.length>4||!/^[0-9a-f]+$/.test(W))return null;L.push(Number.parseInt(W,16))}return L},G=V(K[0]??"");if(G===null)return null;if(K.length===1){let z=G;if(z.length!==8)return null;return X.length>0?z.slice(0,6).concat(X):z}let F=V(K[1]??"");if(F===null)return null;let B=8-G.length-F.length;if(B<0)return null;let H=G.concat(Array(B).fill(0),F);if(H.length!==8)return null;return X.length>0?H.slice(0,6).concat(X):H}function C1($,Q){return`${$>>8&255}.${$&255}.${Q>>8&255}.${Q&255}`}function q1($){let Q=j1($);if(Q===null)return!0;let[Z,X,J]=Q;if((Z&57344)!==8192)return!0;if(Z===8193&&(X&65024)===0)return!0;if(Z===8193&&X===3512)return!0;if(Z===16383&&(X&61440)===0)return!0;if(Z===8194)return JZ(C1(X,J));return!1}function YZ($){return $.replace(/^\[|\]$/g,"")}function e9($){let Q=YZ($.trim()),Z=$8(Q);if(Z===4)return JZ(Q);if(Z===6)return q1(Q);return!0}function GZ($){if($ instanceof Error&&$.name==="TimeoutError")return"dns_timeout";switch(typeof $==="object"&&$!==null&&"code"in $?$.code:void 0){case"ENOTFOUND":return"dns_not_found";case"ENODATA":return"dns_empty";case"EAI_AGAIN":case"ESERVFAIL":case"ECONNREFUSED":return"dns_temporary";case"ETIMEOUT":case"ETIMEDOUT":return"dns_timeout";default:return"dns_failed"}}var zZ=5000;function T1($){return async(Q,Z)=>{if(Z?.aborted)throw Error("aborted");let X=new L1({timeout:zZ,tries:1});if($)X.setServers($);let J=()=>X.cancel();Z?.addEventListener("abort",J,{once:!0});try{let[Y,K]=await Promise.allSettled([X.resolve4(Q),X.resolve6(Q)]),V=[...Y.status==="fulfilled"?Y.value:[],...K.status==="fulfilled"?K.value:[]];if(V.length>0)return V;let G=[Y,K].flatMap((B)=>B.status==="rejected"?[B.reason]:[]);throw G.find((B)=>["dns_temporary","dns_timeout"].includes(GZ(B)))??G[0]??Object.assign(Error("DNS returned no addresses"),{code:"ENODATA"})}finally{Z?.removeEventListener("abort",J)}}}var O1=T1();async function D1($,Q,Z,X){if(X?.aborted)throw Error("aborted");let J=new AbortController,Y,K,V=Q($,J.signal);V.catch(()=>{});try{return await Promise.race([V,new Promise((G,F)=>{if(Y=setTimeout(()=>F(new DOMException("DNS lookup timed out","TimeoutError")),Z),X)K=()=>F(Error("aborted")),X.addEventListener("abort",K,{once:!0})})])}finally{if(Y!==void 0)clearTimeout(Y);if(X&&K)X.removeEventListener("abort",K);J.abort()}}async function XX($,Q=O1,Z){let X=YZ($);if($8(X))return e9(X)?{ok:!1,reason:"non_public_ip"}:{ok:!0,addresses:[X]};let J;try{J=await D1(X,Q,zZ,Z)}catch(Y){return{ok:!1,reason:Z?.aborted?Z.reason instanceof Error&&Z.reason.name==="TimeoutError"?"dns_timeout":"aborted":GZ(Y)}}if(J.length===0)return{ok:!1,reason:"dns_empty"};if(J.some(e9))return{ok:!1,reason:"non_public_ip"};return{ok:!0,addresses:J}}var _1=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/;function d8($){return $.length<=253&&_1.test($.toLowerCase())}function A1($,Q){let Z=$.trim().toLowerCase();if(!d8(Z))return!1;if(Z.startsWith("*.")){let X=Z.slice(2);return Q===X||Q.endsWith(`.${X}`)}return Z===Q}function x1($){let Q=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec($);if(!Q)return null;let Z=Q.slice(1).map(Number);return Z.some((X)=>X>255)?null:Z}function p8($,Q=[]){let Z=(X)=>{if(X=X.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,""),!X.includes(":"))return X;try{X=new URL(`http://[${X}]/`).hostname.slice(1,-1)}catch{return X}let J=/^::ffff:([\da-f]+):([\da-f]+)$/.exec(X);if(!J)return X;let Y=parseInt(J[1],16),K=parseInt(J[2],16);return`${Y>>8}.${Y&255}.${K>>8}.${K&255}`};return Q.some((X)=>Z(X)===Z($))}function l0($){$=$.toLowerCase().replace(/^\[|\]$/g,"");let Q=x1($);if(Q){let[Y,K,V]=Q;if(Y===127)return"loopback";return Y===0||Y===10||Y>=224||Y===100&&K>=64&&K<=127||Y===169&&K===254||Y===172&&K>=16&&K<=31||Y===192&&(K===168||K===0&&(V===0||V===2)||K===88&&V===99)||Y===198&&(K===18||K===19||K===51&&V===100)||Y===203&&K===0&&V===113?"private":"public"}if(!$.includes(":"))return"hostname";try{$=new URL(`http://[${$}]/`).hostname.slice(1,-1)}catch{return"private"}if($==="::1")return"loopback";let Z=/^::ffff:([\da-f]+):([\da-f]+)$/.exec($);if(Z){let Y=parseInt(Z[1],16),K=parseInt(Z[2],16);return l0(`${Y>>8}.${Y&255}.${K>>8}.${K&255}`)==="public"?"public":"private"}let[X,J=0]=$.split(":").map((Y)=>parseInt(Y||"0",16));return X<8192||X>16383||X===8194||X===8193&&(J<512||J===3512)||X===16383&&J<4096?"private":"public"}function I9($,Q){let Z;try{Z=new URL($)}catch{return{allowed:!1,url:$,host:null,reason:"invalid_url"}}if(["about:","data:","blob:"].includes(Z.protocol))return{allowed:!0,url:$,host:null,reason:"local_document"};if(!["http:","https:","ws:","wss:"].includes(Z.protocol))return{allowed:!1,url:$,host:Z.hostname||null,reason:"unsupported_protocol"};let X=Z.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(Q.mode==="off")return{allowed:!0,url:$,host:X,reason:"policy_off"};let J=(V)=>({allowed:!1,url:$,host:X,reason:V});if(Z.username||Z.password)return J("invalid_url");if(Q.mode==="public_web"){let V=l0(X)!=="public"&&l0(X)!=="hostname"||X==="localhost"||/\.(?:localhost|local|internal|arpa)$/.test(X)||!X.includes(".")&&!KZ(X)||Boolean(KZ(X)&&e9(X));return{allowed:!V,url:$,host:X,reason:V?"private_network":"public_web"}}let Y=Number(Z.port||(["https:","wss:"].includes(Z.protocol)?443:80));if(Q.deniedPorts?.includes(Y)||p8(X,Q.deniedHosts))return J("destination_not_allowed");let K=l0(X);if(K==="private"||["local","internal","arpa"].some((V)=>X===V||X.endsWith(`.${V}`)))return J("private_network");if(K==="loopback"||X==="localhost"||X.endsWith(".localhost"))return Q.allowedLoopbackPorts?.includes(Y)?{allowed:!0,url:$,host:X,reason:"loopback"}:J("destination_not_allowed");if(Q.allowedDomains.some((V)=>A1(V,X)))return{allowed:!0,url:$,host:X,reason:"allowed_domain"};return{allowed:!1,url:$,host:X,reason:"destination_not_allowed"}}import FZ from"child_process";import{accessSync as I1,constants as R1,readFileSync as E1,statSync as WZ}from"fs";import{createRequire as BZ}from"module";import{homedir as HZ}from"os";import{dirname as S1,isAbsolute as l8,join as Y9,resolve as w1}from"path";var Q8=Object.freeze({schemaVersion:1,driver:"playwright-core",driverVersion:UZ.dependencies["playwright-core"],browser:"chromium"}),LZ=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Chromium.app/Contents/MacOS/Chromium"],u8=["/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/google-chrome","/usr/bin/google-chrome-stable"];function R9($){try{return I1($,R1.X_OK),l8($)&&WZ($).isFile()}catch{return!1}}function s8($,Q=process.platform){let Z=Q==="darwin"?LZ:Q==="linux"?u8:null;return Z?($??Z).find(R9)??null:null}function b1(){if(!process.versions.bun)return;let $=Symbol.for("ara.headless-browser.bun-pipe-owners");if(Object.hasOwn(globalThis,$))return;let Q=[];FZ.spawn=new Proxy(FZ.spawn,{apply(Z,X,J){let Y=Reflect.apply(Z,X,J),K=J[1],V=J[2]?.stdio;if(Array.isArray(K)&&K.includes("--remote-debugging-pipe")&&Array.isArray(V)&&V[3]==="pipe"&&V[4]==="pipe")Q.push(Y);return Y}}),Object.defineProperty(globalThis,$,{value:Q})}async function Z8($){if(b1(),$!==void 0){if(!l8($))throw Error("hands_browser_driver_path_must_be_absolute");let X=Y9($,"package.json"),J=JSON.parse(E1(X,"utf8"));if(J.name!==Q8.driver)throw Error("hands_browser_wrong_driver");let Y=BZ(X)($),K=Y.default?.chromium??Y.chromium;if(!K)throw Error("hands_browser_missing_chromium");return{version:J.version,chromium:K}}let[Q,Z]=await Promise.all([import("./index-t1h1wd8g.js"),import("./package-vj1s3sye.js").then((m)=>P1(m.default,1))]);return{version:Z.default.version,chromium:Q.chromium}}var k1=($,Q=Q8.driverVersion)=>({status:"unavailable",reason:$,expectedDriverVersion:Q}),f1=($)=>$.loadDriver?.()??Z8($.driverModuleDirectory),g1={"1.60.0":"1223"};function BX(){let $=process.platform,Q=g1[Q8.driverVersion];if(!Q||$!=="linux"&&$!=="darwin")return!1;let Z=(X)=>process.env[X]??process.env[`npm_config_${X.toLowerCase()}`]??process.env[`npm_package_config_${X.toLowerCase()}`];try{let X=Z("PLAYWRIGHT_BROWSERS_PATH"),J=X==="0"?Y9(S1(BZ(import.meta.url).resolve("playwright-core/package.json")),".local-browsers"):X?w1(Z("INIT_CWD")||process.cwd(),X):Y9($==="darwin"?Y9(HZ(),"Library","Caches"):process.env.XDG_CACHE_HOME||Y9(HZ(),".cache"),"ms-playwright");return WZ(Y9(J,`chromium-${Q}`,"INSTALLATION_COMPLETE")).isFile()}catch{return!1}}async function G9($={}){return NZ($,Q8.driverVersion)}async function n8($,Q={}){if($.driverVersion!=="1.61.1"||!l8($.driverModuleDirectory))throw Error("hands_browser_invalid_managed_compatibility");return NZ({...Q,driverModuleDirectory:$.driverModuleDirectory,allowSystemBrowser:!0},$.driverVersion)}async function NZ($,Q){let Z=(G)=>k1(G,Q),X=$.platform??process.platform;if(X!=="linux"&&X!=="darwin")return Z("unsupported_platform");let J;try{J=await f1($)}catch{return Z("driver_missing")}if(J.version!==Q)return Z("driver_version_mismatch");let Y=(G,F)=>({status:"resolved",executablePath:G,source:F,driverVersion:J.version});if($.executablePath!==void 0)return R9($.executablePath)?Y($.executablePath,"configured"):Z("executable_missing");let K=J.chromium.executablePath();if(R9(K))return Y(K,"managed");let V=$.allowSystemBrowser===!0?s8($.systemCandidates,X):null;return V?Y(V,"system"):Z("executable_missing")}var a1=["/usr/local/bin/chromium",...u8];function o1($,Q=DZ()){return s8($??(Q==="linux"?a1:void 0),Q)}async function r1(){try{return(await Z8()).chromium}catch{return l1(import.meta.url)("playwright-core").chromium}}var t1=1048576,e1=105000,$7=20000,CZ=5000,Q7=2000,Z7=1000,X7=30000,qZ=81920,J7={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif"};async function Y7($,Q){let Z=new URL($.url()),X={...await $.allHeaders(),host:Z.host};for(let J of Object.keys(X))if(/^(?:proxy-|connection$|upgrade$|transfer-encoding$|content-length$)/i.test(J))delete X[J];return new Promise((J,Y)=>{let V=(Z.protocol==="https:"?s1:u1)(Z,{method:$.method(),headers:X,agent:!1,lookup:(F,B,H)=>{let z=u0.isIP(Q);if(B.all)H(null,[{address:Q,family:z}]);else H(null,Q,z)}},(F)=>{let B=[],H=0;F.on("data",(z)=>{if(H+=z.length,H>33554432)V.destroy(Error("hands_browser_response_too_large"));else B.push(z)}),F.on("error",Y),F.on("end",()=>{let z={};for(let[L,W]of Object.entries(F.headers))if(W!==void 0&&!["transfer-encoding","connection","content-length"].includes(L))z[L]=Array.isArray(W)?W.join(`
307
307
  `):W;J({status:F.statusCode??502,headers:z,body:Buffer.concat(B)})})}),G=setTimeout(()=>V.destroy(Error("hands_browser_fetch_timeout")),X7);V.once("close",()=>clearTimeout(G)),V.on("error",Y),V.end($.postDataBuffer()??void 0)})}async function G7($,Q,Z=()=>{},X={lookup:(J)=>p1(J,{all:!0}),fetch:Y7}){let J=new WeakSet,Y=new WeakMap,K=(V)=>{let G=Y.get(V);if(G)return G;let F=(async()=>{if(!$.newCDPSession)return;let B=await $.newCDPSession(V),H=new Map;B.on("Network.loadingFinished",({requestId:z})=>H.delete(z)),B.on("Network.loadingFailed",({requestId:z})=>H.delete(z)),B.on("Fetch.requestPaused",async(z)=>{let L=z.networkId??z.requestId,W=z.redirectedRequestId?(H.get(L)??0)+1:0;H.set(L,W);let U=I9(z.request.url,Q),j=Q.mode==="enforce"&&Boolean(z.redirectedRequestId)&&U.host!==null&&!u0.isIP(U.host),O=!U.allowed?U:j?{...U,allowed:!1,reason:"destination_not_allowed"}:W>20?{...U,allowed:!1,reason:"redirect_not_supported"}:null;try{if(O)Z(O),await B.send("Fetch.failRequest",{requestId:z.requestId,errorReason:"BlockedByClient"});else await B.send("Fetch.continueRequest",{requestId:z.requestId})}catch{await B.send("Fetch.failRequest",{requestId:z.requestId,errorReason:"Failed"}).catch(()=>{})}}),await B.send("Network.enable"),await B.send("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"}]}),J.add(V)})();return Y.set(V,F),F};return await $.route("**/*",async(V)=>{let G=V.request().url(),F=I9(G,Q);if(F.allowed&&Q.mode==="public_web"){await V.continue();return}let B=V.request();if(F.allowed&&F.host&&u0.isIP(F.host)&&B.isNavigationRequest?.()){let H=B.frame();if(J.has(H.page())&&H===H.page().mainFrame()){await V.continue();return}}if(F.allowed&&(Q.mode==="off"||F.reason==="local_document")){await V.continue();return}if(F.allowed&&F.host)try{let H=F.host,z=l0(H),L,W=await(async()=>{if(z!=="hostname")return[{address:H,family:u0.isIP(H)}];if(F.reason==="loopback")return[{address:"127.0.0.1",family:4}];try{return await Promise.race([X.lookup(H),new Promise((U,j)=>{L=setTimeout(()=>j(Error("hands_browser_dns_timeout")),5000)})])}finally{if(L)clearTimeout(L)}})();if(!W.length||W.some(({address:U})=>{let j=l0(U);return!u0.isIP(U)||Q.mode==="enforce"&&p8(U,Q.deniedHosts)||(F.reason==="loopback"?j!=="loopback":j!=="public")}))F={...F,allowed:!1,reason:"private_network"};else{let U=await X.fetch(V.request(),W[0].address);if(U.status>=300&&U.status<400){let j=U.headers.location??G;try{j=new URL(j,G).href}catch{}let O=I9(j,Q);F=O.allowed?{...O,allowed:!1,reason:"redirect_not_supported"}:O}else{await V.fulfill(U);return}}}catch{await V.abort("failed");return}Z(F),await V.abort("blockedbyclient")}),await $.routeWebSocket("**/*",async(V)=>{let G=I9(V.url(),Q);if(Q.mode==="enforce"&&G.allowed&&(!G.host||!u0.isIP(G.host)))G={...G,allowed:!1,reason:"destination_not_allowed"};if(G.allowed){V.connectToServer();return}Z(G),await V.close({code:1008,reason:"Reason egress policy denied"})}),Q.mode==="off"?void 0:{preparePage:K}}async function _Z($,Q=DZ(),Z){if(Z){let J=await n8(Z,{platform:Q,systemCandidates:$});return J.status==="resolved"?J.executablePath:null}if($!==void 0){let J=o1($,Q);if(J)return J}let X=await G9({platform:Q,systemCandidates:$,allowSystemBrowser:!0});return X.status==="resolved"?X.executablePath:null}function TZ($,Q){if(!$)throw Error("hands_repl_workspace_required");let Z=a8($),X=z9($),J=o8(X,z9(X,Q)),K=J!==".."&&!J.startsWith(`..${r8}`)&&!jZ(J)?z9(Z,J):z9(Z,Q);if(b0(z9(X,Q))||b0(K))throw Error("hands_repl_protected_path");let V=(W)=>{let U=o8(Z,W);return U!==""&&U!==".."&&!U.startsWith(`..${r8}`)&&!jZ(U)},G=a8(K);if(b0(G))throw Error("hands_repl_protected_path");if(!V(K)||!V(G))throw Error("hands_repl_file_outside_workspace");let F=o8(Z,K).split(r8),B=[Z,...F.map((W,U)=>z9(Z,...F.slice(0,U+1)))],H=B.map((W)=>MZ(W));if(H.some((W)=>W.isSymbolicLink()))throw Error("hands_repl_file_symlink");let z=H[H.length-1];if(!z.isFile()||z.nlink!==1||z.size>16777216)throw Error("hands_repl_file_not_regular_or_too_large");let L=v1(K,i8.O_RDONLY|i8.O_NOFOLLOW|i8.O_NONBLOCK);try{let W=h1(L);if(W.dev!==z.dev||W.ino!==z.ino||!W.isFile())throw Error("hands_repl_file_changed");for(let q=0;q<B.length;q++){let A=MZ(B[q]);if(A.dev!==H[q].dev||A.ino!==H[q].ino||A.isSymbolicLink())throw Error("hands_repl_file_changed")}if(!V(a8(K)))throw Error("hands_repl_file_outside_workspace");let U=Buffer.alloc(16777217),j=0;while(j<U.length){let q=c1(L,U,j,U.length-j,null);if(!q)break;j+=q}if(j===U.length)throw Error("hands_repl_file_too_large");let O=U.subarray(0,j);return{name:n1(K),mimeType:J7[i1(K).toLowerCase()]??"application/octet-stream",buffer:O}}finally{y1(L)}}function K9($,Q){$.end(`${JSON.stringify(Q)}
308
308
  `)}function X8($){try{d1($)}catch{}}async function AZ($){if($.managedBrowser&&$.driverModuleDirectory!==void 0)throw Error("hands_browser_ambiguous_driver_configuration");let Q=$.launch||$.targetContext?null:$.managedBrowser?await n8($.managedBrowser,{executablePath:$.browserExecutablePath}):await G9({executablePath:$.browserExecutablePath,driverModuleDirectory:$.driverModuleDirectory});if(Q?.status==="unavailable")throw Error(`hands_browser_${Q.reason}`);let Z=Q?.status==="resolved"?Q.executablePath:$.browserExecutablePath;if(!Z||!R9(Z))throw Error("hands_browser_unavailable");let X=$.launch??(async(N)=>($.targetContext?await r1():(await Z8($.managedBrowser?.driverModuleDirectory??$.driverModuleDirectory)).chromium).launch(N)),J=[],Y={},K=null,V=null,G=null,F=null,B=!1,H=null,z=new Map,L=new WeakMap,W=null,U=()=>{if(B)throw Error("hands_repl_stopped");if(F)throw F},j=(N)=>{let M=L.get(N);if(M)return M;let D=Promise.resolve().then(()=>N.close()).then(()=>{z.delete(N)});return L.set(N,D),D},O=async()=>{let N=[...z.entries()].reverse(),M=W??=performance.now()+Z7,D=Promise.allSettled(N.filter(([,_])=>_==="context").map(([_])=>j(_))),w;try{await Promise.race([D,new Promise((_)=>{w=setTimeout(_,Math.max(0,M-performance.now()))})])}finally{if(w)clearTimeout(w)}let k=await Promise.allSettled(N.map(([_])=>j(_))),f=[];for(let[_,m]of k.entries()){if(m.status!=="rejected")continue;let c=m.reason instanceof Error&&["Error","TimeoutError","ProtocolError"].includes(m.reason.name)?m.reason.name:"unknown";f.push(Error(`hands_repl_close_failed: ${N[_][1]}: ${c}`))}if(f.length)throw AggregateError(f,"hands_repl_stop_unconfirmed")},q=(N,M)=>{if(z.set(N,M),B||F)j(N).catch(()=>{return}),U();return N},A=async()=>{let N=await X({executablePath:Z,headless:!0,chromiumSandbox:$.managedBrowser===void 0,args:["--disable-background-networking","--disable-quic","--disable-dev-shm-usage","--disable-gpu","--disable-software-rasterizer","--dns-prefetch-disable","--force-webrtc-ip-handling-policy=disable_non_proxied_udp","--no-pings"]}),M=null;try{q(N,"browser"),M=$.targetContext??q(await N.newContext({viewport:{width:1440,height:900},screen:{width:1440,height:900},serviceWorkers:"block",acceptDownloads:!1}),"context");let D=await G7(M,$.networkPolicy??{mode:"off"},$.onEgressDenied);if(U(),D){let b=M.newPage.bind(M);M.newPage=async()=>{let h=await b();return await D.preparePage(h),h}}let k=M.pages()[0]??await M.newPage();await D?.preparePage(k),U();let f=async(b=k)=>{let h=b;if(typeof h.ariaSnapshot==="function")return h.ariaSnapshot({timeout:1e4});return k.locator("body").innerText({timeout:1e4})},_=async(b,h={})=>{let d=h&&typeof h==="object"&&!Array.isArray(h)?h:{},u,G0="image/png";if(Buffer.isBuffer(b)||b instanceof Uint8Array)u=Buffer.from(b);else if(typeof b==="string"&&(b.startsWith("data:")||/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(b)))u=Buffer.from(b.replace(/^data:[^,]*,/,""),"base64");else if(typeof b==="string"){let T0=TZ($.workspaceRoot,b);u=T0.buffer,G0=T0.mimeType}else throw Error("view() needs a Buffer, a base64 string, or a path to an image file");if(u.length===0)throw Error("view(): the image is empty");let M0=String(d.label??"").replace(/[\r\n>]+/g," ").trim().slice(0,120),U0=Number(d.maxWidth)||1024,W0=Number(d.quality)||72,y0=$.targetContext?await N.newPage():await M.newPage();try{let T0=`data:${G0};base64,${u.toString("base64")}`;for(let r=0;r<5;r+=1){let j0=await y0.evaluate(async(B0)=>{let C0=new Image;C0.src=B0.url,await C0.decode();let h0=Math.min(1,B0.maxWidth/C0.naturalWidth),Y0=document.createElement("canvas");Y0.width=Math.max(1,Math.round(C0.naturalWidth*h0)),Y0.height=Math.max(1,Math.round(C0.naturalHeight*h0));let X0=Y0.getContext("2d");if(!X0)throw Error("view(): canvas unavailable");return X0.fillStyle="#ffffff",X0.fillRect(0,0,Y0.width,Y0.height),X0.drawImage(C0,0,0,Y0.width,Y0.height),{data:Y0.toDataURL("image/jpeg",B0.q/100).split(",")[1]??"",width:Y0.width,height:Y0.height,sourceWidth:C0.naturalWidth,sourceHeight:C0.naturalHeight}},{url:T0,maxWidth:U0,q:W0}),r0=Buffer.from(j0.data,"base64");if(r0.length<=qZ){let B0=M0||"image";return`<<<ARA_VIEW_IMAGE ${j0.data} image/jpeg ${B0}>>>
309
309
  Viewing ${B0} (${j0.sourceWidth}x${j0.sourceHeight} source, sent at ${j0.width}x${j0.height}, ${Math.round(r0.length/1024)}KB).`}if(U0>640)U0=Math.round(U0*0.75);else W0=Math.max(30,W0-15)}throw Error(`view(): could not reduce the image under ${Math.round(qZ/1024)}KB`)}finally{await y0.close().catch(()=>{return})}},m=XZ({browser:$.targetContext?.browser()??N,context:M,page:k,a11y:f,view:_,readWorkspaceFile:(b)=>TZ($.workspaceRoot,b),privateProfile:$.privateProfile,beforeNavigation:$.beforeNavigation,recording:$.recording,screenshotExport:$.screenshotExport,actionRecorder:()=>{let b=J,h=Y;return(d,u)=>{if(b.length<OZ)b.push(d);if(u)h.page=u}}}),c=async(b)=>{U();let h=q(await N.newContext({serviceWorkers:"block",acceptDownloads:!1}),"context");try{await h.route("**/*",(u)=>u.abort()),U(),await h.routeWebSocket("**/*",(u)=>u.close({code:1008,reason:"Reason evaluator network denied"})),U(),await h.exposeBinding("__araHandsRpc",async(u,G0)=>$.onBrowserOperation?$.onBrowserOperation(b,()=>m.dispatch(G0)):m.dispatch(G0)),U();let d=await h.newPage();return U(),await d.goto("data:text/html,<title>Reason Hands evaluator</title>"),U(),await d.evaluate(`(${nQ})(${JSON.stringify(m.roots)})`),{context:h,page:d,runId:b}}catch(d){throw await j(h).catch(()=>{return}),d}},l=await c(),o={browser:N,context:M,page:k,evaluator:l,async captureProgressFrame(b){return _(await b.screenshot({type:"jpeg",quality:65,timeout:2000}),{label:"Screen after browser action"})},async resetEvaluator(b){await j(o.evaluator.context),o.evaluator=await c(b)}};return U(),o}catch(D){throw await O().catch(()=>{return}),D}},R=async()=>{if(U(),K)return K;if(!G){V=A();let N;G=Promise.race([V,new Promise((M,D)=>{N=setTimeout(()=>D(Error("hands_browser_unavailable: startup timed out")),$7)})]).then((M)=>{return U(),K=M,M}).catch(async()=>{F=Error("hands_browser_unavailable: startup failed or timed out");let M;try{await Promise.race([O(),new Promise((D,w)=>{M=setTimeout(()=>w(Error("hands_repl_stop_timeout")),CZ)})])}catch{F=Error("hands_browser_unavailable: startup cleanup unconfirmed")}finally{if(M)clearTimeout(M)}throw F}).finally(()=>{if(N)clearTimeout(N)})}return G},P=async(N,M,D=!1)=>{let w=await R(),k=Y;if($.onBrowserOperation&&w.evaluator.runId!==M)await w.resetEvaluator(M);let _=(async()=>{let l=await w.evaluator.page.evaluate(`(${iQ})(${JSON.stringify({code:N})})`);if(typeof l!=="string")throw Error("hands_repl_invalid_evaluator_output");let o=k.page;if(D&&o&&!l.includes("<<<ARA_VIEW_IMAGE")){let b=()=>w.captureProgressFrame(o);try{let h=await($.onBrowserOperation?$.onBrowserOperation(M,b):b());return k.automaticProgressImage=!0,`${l}
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{lc as i,mc as l,nc as g,oc as y}from"./vm-hands-entry-lite-k469tezz.js";import{Ag as k,Cg as G,Eg as X,Fg as M,Gg as Y,Hg as H,Ig as V,Kg as S,Lg as _,Ng as P,Og as C,Pg as I,Rg as O,Ug as A,ug as Q,vg as J,wg as z,xg as Z,yg as K,zg as $}from"./vm-hands-entry-lite-2mhzfg6b.js";import{bi as L,ci as W,di as F,ei as j}from"./vm-hands-entry-lite-3s5fdvat.js";var d=["cgroup_membership_read_failed","cgroup_v2_membership_absent","cgroup_scope_invalid","cgroup_root_unavailable","cgroup_directory_unavailable","cgroup_limit_read_failed","cgroup_events_read_failed","cgroup_current_read_failed","cgroup_stat_read_failed","boot_id_read_failed","boot_id_invalid","guest_meminfo_read_failed","guest_vmstat_read_failed","memory_counter_invalid","memory_field_missing","memory_capacity_invalid"];var a=String.raw`(function(fs, path) {
2
+ import{lc as i,mc as l,nc as g,oc as y}from"./vm-hands-entry-lite-k469tezz.js";import{Ag as K,Bg as $,Cg as k,Eg as G,Gg as X,Hg as M,Ig as Y,Jg as H,Kg as V,Mg as S,Ng as _,Pg as P,Qg as C,Rg as I,Tg as O,Wg as A,wg as Q,xg as J,yg as z,zg as Z}from"./vm-hands-entry-lite-knfh7w3j.js";import{di as L,ei as W,fi as F,gi as j}from"./vm-hands-entry-lite-289bc9v7.js";var d=["cgroup_membership_read_failed","cgroup_v2_membership_absent","cgroup_scope_invalid","cgroup_root_unavailable","cgroup_directory_unavailable","cgroup_limit_read_failed","cgroup_events_read_failed","cgroup_current_read_failed","cgroup_stat_read_failed","boot_id_read_failed","boot_id_invalid","guest_meminfo_read_failed","guest_vmstat_read_failed","memory_counter_invalid","memory_field_missing","memory_capacity_invalid"];var a=String.raw`(function(fs, path) {
3
3
  const fail = (message, reasonCode) => { throw Object.assign(Error(message), {reasonCode}); };
4
4
  const read = (p, reasonCode, trim=true) => { try { const text=fs.readFileSync(p, "utf8"); return trim?text.trim():text; }
5
5
  catch { fail("memory_read", reasonCode); } };
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Mb as j,Nb as q}from"./vm-hands-entry-lite-p7x3vnz5.js";function y(v=process.platform){if(j(),v==="linux")q("strict")}
2
+ import{Mb as j,Nb as q}from"./vm-hands-entry-lite-7ba3nhgv.js";function y(v=process.platform){if(j(),v==="linux")q("strict")}
3
3
  export{y as u};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{_h as f}from"./vm-hands-entry-lite-3s5fdvat.js";var j=["Click browser element","Double click browser element","Type text","Clear browser field","Press key","Scroll browser element into view","Drag on computer","Select browser option","Check browser control","Uncheck browser control","Hover browser element","Focus browser element","Open browser page","Reload browser page","Go back in browser","Go forward in browser","Take browser screenshot"],$A=32;function R(x){if(!Array.isArray(x)||x.length>32||!x.every((A)=>typeof A==="string"&&j.includes(A)))return;return x.slice()}var KA="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",QA=262144;function Y(x){if(!x||typeof x!=="object"||Array.isArray(x))return!1;let A=x,W=Object.keys(A);return W.length===2&&W.includes("template")&&W.includes("quoteDepth")&&typeof A.template==="string"&&A.template.length<=262144&&!A.template.includes("\x00")&&A.template.split("__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__").length===2&&(A.quoteDepth===1||A.quoteDepth===2||A.quoteDepth===3)}var I=2,b=33554432,K=200000,D=4000000,_=240000,YA=`
2
+ import{ai as f}from"./vm-hands-entry-lite-289bc9v7.js";var j=["Click browser element","Double click browser element","Type text","Clear browser field","Press key","Scroll browser element into view","Drag on computer","Select browser option","Check browser control","Uncheck browser control","Hover browser element","Focus browser element","Open browser page","Reload browser page","Go back in browser","Go forward in browser","Take browser screenshot"],$A=32;function R(x){if(!Array.isArray(x)||x.length>32||!x.every((A)=>typeof A==="string"&&j.includes(A)))return;return x.slice()}var KA="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",QA=262144;function Y(x){if(!x||typeof x!=="object"||Array.isArray(x))return!1;let A=x,W=Object.keys(A);return W.length===2&&W.includes("template")&&W.includes("quoteDepth")&&typeof A.template==="string"&&A.template.length<=262144&&!A.template.includes("\x00")&&A.template.split("__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__").length===2&&(A.quoteDepth===1||A.quoteDepth===2||A.quoteDepth===3)}var I=2,b=33554432,K=200000,D=4000000,_=240000,YA=`
3
3
  ...[executor output truncated]`,p=2000,k=1,i=16384,d=32768,y=128,LA=64,s=2097152,H=1,m=16384,c=32768,OA=8388608,n=1000,t=2500,r=2000,zA=t+r,o=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/,v=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,l={text_only:4430,invalid_json:4431,invalid_cancel_request:4432,invalid_sdk_response:4433,claim_required:4434,invalid_claim:4435,executor_mismatch:4436,stale_generation:4437,fence_conflict:4438,frame_too_large:4439,result_too_large:4440,progress_too_large:4441,terminal_cleanup_started:4442,job_journal_unavailable:4443},u=new Map(Object.entries(l).map(([x,A])=>[A,x]));function SA(x,A){return A||(u.get(x)??"")}var a=["cancelled","command_failed","duplicate_request_id","duplicate_result_evicted","invalid_repl_response","invalid_request","process_group_cleanup_unconfirmed","repl_failed","result_too_large","repl_response_too_large","repl_transport_failed","request_ledger_full","request_journal_unavailable","request_outcome_uncertain","maintenance_held","request_not_found","resume_digest_mismatch","spawn_failed","stale_generation","timeout"],e=new Set(a),w=16384,AA=200,xA=2000,WA=["maintenance_held","invalid_job_request","jobs_disabled","job_not_found","job_conflict","job_capacity","job_journal_unavailable","job_not_running","job_lease_expired","job_input_sequence","job_input_backpressure","stale_generation","pty_unsupported","job_mode_mismatch"];class G extends Error{code;constructor(x){super(x);this.name="HandsProtocolError",this.code=x}}function g(x){return new TextEncoder().encode(x).byteLength}function U(x){return typeof x==="object"&&x!==null&&!Array.isArray(x)}function B(x,A){let W=new Set(A);return Object.keys(x).every((N)=>W.has(N))}function M(x){return typeof x==="string"&&o.test(x)}function Z(x){return Number.isSafeInteger(x)&&Number(x)>=1}function J(x){return typeof x==="string"&&v.test(x)}function C(x){return typeof x==="string"&&x.startsWith("pty-")&&J(x.slice(4))}function z(x){return[x.cols,x.rows].every((A)=>Number.isSafeInteger(A)&&Number(A)>=1&&Number(A)<=n)}function E(x){if(typeof x!=="string"||x.length>Math.ceil(m/3)*4||x.length%4!==0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(x))return-1;let A=x.endsWith("==")?2:x.endsWith("=")?1:0;if(A&&"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(x[x.length-A-1])&(A===2?15:3))return-1;let N=x.length/4*3-A;return N<=m?N:-1}function S(x){return typeof x==="string"&&/^[0-9a-f]{64}$/.test(x)}function $(x){if(g(x)>b)throw new G("frame_too_large");try{return JSON.parse(x)}catch{throw new G("invalid_json")}}function BA(x){let A=$(x);if(!U(A)||!B(A,["version","generation","id","tool","input","semanticDigest","lifecycleLeaseId","workspaceBefore"])||A.version!==I||!Z(A.generation)||!M(A.id)||!["bash","repl","resume","read","edit","write","pi_tool"].includes(String(A.tool))||!U(A.input)||A.lifecycleLeaseId!==void 0&&(A.tool!=="bash"||!J(A.lifecycleLeaseId))||A.workspaceBefore!==void 0&&(!(A.tool==="bash"||A.tool==="repl"||A.tool==="pi_tool"&&A.input.tool==="bash")||!U(A.workspaceBefore)||!B(A.workspaceBefore,["script"])||typeof A.workspaceBefore.script!=="string"||A.workspaceBefore.script.length>K))throw new G("invalid_request");let W=U(A.workspaceBefore)&&typeof A.workspaceBefore.script==="string"?{workspaceBefore:{script:A.workspaceBefore.script}}:{};if(A.tool==="bash"){if(!B(A.input,["script","retainBackground","machineSdk"])||typeof A.input.script!=="string"||A.input.script.length>K||A.input.retainBackground!==void 0&&A.input.retainBackground!==!0||A.input.machineSdk!==void 0&&A.input.machineSdk!==!0||A.semanticDigest!==void 0&&!S(A.semanticDigest))throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"bash",input:{script:A.input.script,...A.input.retainBackground===!0?{retainBackground:!0}:{},...A.input.machineSdk===!0?{machineSdk:!0}:{}},...A.semanticDigest===void 0?{}:{semanticDigest:A.semanticDigest},...A.lifecycleLeaseId===void 0?{}:{lifecycleLeaseId:A.lifecycleLeaseId},...W}}if(A.tool==="resume"){if(A.semanticDigest!==void 0||!B(A.input,["semanticDigest"])||!S(A.input.semanticDigest))throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"resume",input:{semanticDigest:A.input.semanticDigest}}}if(A.tool==="repl"){if(!B(A.input,["code"])||typeof A.input.code!=="string"||A.input.code.length>K||A.semanticDigest!==void 0)throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"repl",input:{code:A.input.code},...W}}if(A.tool==="pi_tool"){let N=A.semanticDigest===void 0?GA(A.input):null;if(!N)throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"pi_tool",input:N,...W}}if(A.tool==="read"){if(!B(A.input,["path","offset","limit"])||typeof A.input.path!=="string"||A.input.path.length<1||A.input.path.length>K||A.semanticDigest!==void 0||A.input.offset!==void 0&&(!Number.isSafeInteger(A.input.offset)||Number(A.input.offset)<1)||A.input.limit!==void 0&&(!Number.isSafeInteger(A.input.limit)||Number(A.input.limit)<1||Number(A.input.limit)>2000))throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"read",input:{path:A.input.path,...A.input.offset===void 0?{}:{offset:Number(A.input.offset)},...A.input.limit===void 0?{}:{limit:Number(A.input.limit)}}}}if(A.tool==="edit"){if(!B(A.input,["path","edits"])||typeof A.input.path!=="string"||A.input.path.length<1||!Array.isArray(A.input.edits)||A.input.edits.length<1||A.input.edits.length>128||A.semanticDigest!==void 0)throw new G("invalid_request");let N=A.input.path.length,X=[];for(let V of A.input.edits){if(!U(V)||!B(V,["oldText","newText"])||typeof V.oldText!=="string"||V.oldText.length<1||typeof V.newText!=="string")throw new G("invalid_request");if(N+=V.oldText.length+V.newText.length,N>D)throw new G("invalid_request");X.push({oldText:V.oldText,newText:V.newText})}return{version:I,generation:A.generation,id:A.id,tool:"edit",input:{path:A.input.path,edits:X}}}if(A.tool!=="write"||!B(A.input,["path","content"])||typeof A.input.path!=="string"||A.input.path.length<1||typeof A.input.content!=="string"||A.input.path.length+A.input.content.length>D||A.semanticDigest!==void 0)throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"write",input:{path:A.input.path,content:A.input.content}}}function L(x){return x===void 0||typeof x==="number"&&Number.isFinite(x)}function GA(x){let A=x.args;if(!B(x,["tool","args"])||!U(A))return null;if(x.tool==="bash")return B(A,["command","timeout"])&&typeof A.command==="string"&&A.command.length<=K&&L(A.timeout)?{tool:"bash",args:{command:A.command,...A.timeout===void 0?{}:{timeout:Number(A.timeout)}}}:null;if(typeof A.path!=="string"||A.path.length>K)return null;if(x.tool==="read")return B(A,["path","offset","limit"])&&L(A.offset)&&L(A.limit)?{tool:"read",args:{path:A.path,...A.offset===void 0?{}:{offset:Number(A.offset)},...A.limit===void 0?{}:{limit:Number(A.limit)}}}:null;if(x.tool==="write")return B(A,["path","content"])&&typeof A.content==="string"&&A.path.length+A.content.length<=D?{tool:"write",args:{path:A.path,content:A.content}}:null;if(x.tool!=="edit"||!B(A,["path","edits"])||!Array.isArray(A.edits))return null;let W=A.path.length,N=[];for(let X of A.edits){if(!U(X)||!B(X,["oldText","newText"])||typeof X.oldText!=="string"||typeof X.newText!=="string")return null;if(W+=X.oldText.length+X.newText.length,W>D)return null;N.push({oldText:X.oldText,newText:X.newText})}return{tool:"edit",args:{path:A.path,edits:N}}}function NA(x){if(!U(x))return null;if("thrown"in x)return B(x,["thrown"])&&typeof x.thrown==="string"?{thrown:x.thrown}:null;let A=x.structuredContent;if(!B(x,["content","details","structuredContent","isError"])||!Array.isArray(x.content)||x.isError!==void 0&&x.isError!==!0||A!==void 0&&(!U(A)||!B(A,["output","truncated","full_output_path","exit_code","wall_time_seconds"])||typeof A.output!=="string"||typeof A.truncated!=="boolean"||A.full_output_path!==void 0&&typeof A.full_output_path!=="string"||typeof A.exit_code!=="number"||typeof A.wall_time_seconds!=="number"))return null;let W=[];for(let N of x.content)if(U(N)&&N.type==="text"&&B(N,["type","text"])&&typeof N.text==="string")W.push({type:"text",text:N.text});else if(U(N)&&N.type==="image"&&B(N,["type","data","mimeType"])&&typeof N.data==="string"&&typeof N.mimeType==="string")W.push({type:"image",data:N.data,mimeType:N.mimeType});else return null;return{content:W,...x.details===void 0?{}:{details:x.details},...U(A)?{structuredContent:{output:String(A.output),truncated:A.truncated===!0,...typeof A.full_output_path==="string"?{full_output_path:A.full_output_path}:{},exit_code:Number(A.exit_code),wall_time_seconds:Number(A.wall_time_seconds)}}:{},...x.isError===!0?{isError:!0}:{}}}function UA(x){let A=$(x);if(!U(A)||!B(A,["version","generation","id","ok","exitCode","stdout","stderr","cwd","error","resumed","browserActions","automaticProgressImage","piToolOutcome","workerElapsedMs","environmentWaitMs","workspaceBefore"])||A.version!==I||!Z(A.generation)||!M(A.id)||typeof A.ok!=="boolean"||!Number.isSafeInteger(A.exitCode)||Number(A.exitCode)<0||Number(A.exitCode)>255||typeof A.stdout!=="string"||A.stdout.length>_||typeof A.stderr!=="string"||A.stderr.length>_||A.cwd!==void 0&&(typeof A.cwd!=="string"||A.cwd.length<1||A.cwd.length>4096||!A.cwd.startsWith("/")||A.cwd.includes("\x00"))||A.error!==void 0&&(typeof A.error!=="string"||A.error.length<1||A.error.length>p||!e.has(A.error))||A.browserActions!==void 0&&!R(A.browserActions)||A.automaticProgressImage!==void 0&&(A.automaticProgressImage!==!0||!A.ok)||A.resumed!==void 0&&A.resumed!==!0||A.workerElapsedMs!==void 0&&(!Number.isSafeInteger(A.workerElapsedMs)||Number(A.workerElapsedMs)<0)||A.environmentWaitMs!==void 0&&(!Number.isSafeInteger(A.environmentWaitMs)||Number(A.environmentWaitMs)<0)||A.workspaceBefore!==void 0&&!h(A.workspaceBefore)||A.ok&&(A.exitCode!==0||A.error!==void 0)||!A.ok&&A.exitCode===0)throw new G("invalid_result");let W=A.piToolOutcome===void 0?void 0:NA(A.piToolOutcome);if(W===null||W&&!A.ok)throw new G("invalid_result");return{version:I,generation:A.generation,id:A.id,ok:A.ok,exitCode:Number(A.exitCode),stdout:A.stdout,stderr:A.stderr,...typeof A.cwd==="string"?{cwd:A.cwd}:{},...A.browserActions!==void 0?{browserActions:R(A.browserActions)}:{},...typeof A.error==="string"?{error:A.error}:{},...A.automaticProgressImage===!0?{automaticProgressImage:!0}:{},...A.resumed===!0?{resumed:!0}:{},...W?{piToolOutcome:W}:{},...A.workerElapsedMs!==void 0?{workerElapsedMs:Number(A.workerElapsedMs)}:{},...A.environmentWaitMs!==void 0?{environmentWaitMs:Number(A.environmentWaitMs)}:{},...h(A.workspaceBefore)?{workspaceBefore:{exitCode:A.workspaceBefore.exitCode,stdout:A.workspaceBefore.stdout,stderr:A.workspaceBefore.stderr}}:{}}}function h(x){return U(x)&&B(x,["exitCode","stdout","stderr"])&&Number.isSafeInteger(x.exitCode)&&Number(x.exitCode)>=0&&Number(x.exitCode)<=255&&typeof x.stdout==="string"&&x.stdout.length<=w&&typeof x.stderr==="string"&&x.stderr.length<=w}function FA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","sequence","stdout","stderr"])||A.type!=="progress"||A.version!==I||!Z(A.generation)||!M(A.id)||!Number.isSafeInteger(A.sequence)||Number(A.sequence)<1||typeof A.stdout!=="string"||A.stdout.length>_||typeof A.stderr!=="string"||A.stderr.length>_)throw new G("invalid_progress");return{type:"progress",version:I,generation:Number(A.generation),id:A.id,sequence:Number(A.sequence),stdout:A.stdout,stderr:A.stderr}}function IA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","fenceId","executorLaunchId","requestCancelVersion","managedJobsVersion","browserRunEnvelopeVersion","terminalCleanupVersion","guestMemoryVersion","guestMemoryDiagnosticsVersion","piToolsVersion","piToolsConfinement","backgroundBashVersion","machineSdkVersion","executionTimingVersion","environmentWaitVersion","workspaceBeforeVersion"])||A.type!=="claim"||A.version!==I||!Z(A.generation)||!J(A.fenceId)||!J(A.executorLaunchId)||A.requestCancelVersion!==void 0&&A.requestCancelVersion!==1||A.managedJobsVersion!==void 0&&A.managedJobsVersion!==k||A.guestMemoryVersion!==void 0&&A.guestMemoryVersion!==1||A.guestMemoryDiagnosticsVersion!==void 0&&(A.guestMemoryDiagnosticsVersion!==1||A.guestMemoryVersion!==1)||A.terminalCleanupVersion!==void 0&&A.terminalCleanupVersion!==1||A.browserRunEnvelopeVersion!==void 0&&A.browserRunEnvelopeVersion!==1||A.piToolsVersion!==void 0&&A.piToolsVersion!==1||A.piToolsConfinement!==void 0&&(!Y(A.piToolsConfinement)||A.piToolsVersion!==1)||A.backgroundBashVersion!==void 0&&A.backgroundBashVersion!==1||A.machineSdkVersion!==void 0&&A.machineSdkVersion!==1||A.executionTimingVersion!==void 0&&A.executionTimingVersion!==1||A.environmentWaitVersion!==void 0&&(A.environmentWaitVersion!==1||A.executionTimingVersion!==1)||A.workspaceBeforeVersion!==void 0&&A.workspaceBeforeVersion!==1)throw new G("invalid_claim");return{type:"claim",version:I,generation:A.generation,fenceId:A.fenceId,executorLaunchId:A.executorLaunchId,...A.requestCancelVersion===1?{requestCancelVersion:1}:{},...A.managedJobsVersion===1?{managedJobsVersion:1}:{},...A.guestMemoryVersion===1?{guestMemoryVersion:1}:{},...A.guestMemoryDiagnosticsVersion===1?{guestMemoryDiagnosticsVersion:1}:{},...A.terminalCleanupVersion===1?{terminalCleanupVersion:1}:{},...A.browserRunEnvelopeVersion===1?{browserRunEnvelopeVersion:1}:{},...A.piToolsVersion===1?{piToolsVersion:1}:{},...Y(A.piToolsConfinement)?{piToolsConfinement:{template:A.piToolsConfinement.template,quoteDepth:A.piToolsConfinement.quoteDepth}}:{},...A.backgroundBashVersion===1?{backgroundBashVersion:1}:{},...A.machineSdkVersion===1?{machineSdkVersion:1}:{},...A.executionTimingVersion===1?{executionTimingVersion:1}:{},...A.environmentWaitVersion===1?{environmentWaitVersion:1}:{},...A.workspaceBeforeVersion===1?{workspaceBeforeVersion:1}:{}}}function XA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","fenceId","executorLaunchId","workerVersion","workerArtifactSha256","requestCancelVersion","managedJobsVersion","lifecycleVersion","browserRunEnvelopeVersion","terminalCleanupVersion","guestMemoryVersion","guestMemoryDiagnosticsVersion","piToolsVersion","piToolsConfinementVersion","backgroundBashVersion","machineSdkVersion","executionTimingVersion","environmentWaitVersion","workspaceBeforeVersion"])||A.lifecycleVersion!==void 0&&A.lifecycleVersion!==1||A.workspaceBeforeVersion!==void 0&&A.workspaceBeforeVersion!==1||A.piToolsVersion!==void 0&&A.piToolsVersion!==1||A.piToolsConfinementVersion!==void 0&&(A.piToolsConfinementVersion!==1||A.piToolsVersion!==1)||A.backgroundBashVersion!==void 0&&A.backgroundBashVersion!==1||A.machineSdkVersion!==void 0&&A.machineSdkVersion!==1||A.executionTimingVersion!==void 0&&A.executionTimingVersion!==1||A.environmentWaitVersion!==void 0&&(A.environmentWaitVersion!==1||A.executionTimingVersion!==1)||A.guestMemoryVersion!==void 0&&A.guestMemoryVersion!==1||A.guestMemoryDiagnosticsVersion!==void 0&&(A.guestMemoryDiagnosticsVersion!==1||A.guestMemoryVersion!==1)||A.terminalCleanupVersion!==void 0&&A.terminalCleanupVersion!==1||A.browserRunEnvelopeVersion!==void 0&&A.browserRunEnvelopeVersion!==1||A.type!=="claim_ack"||A.version!==I||!Z(A.generation)||!J(A.fenceId)||!J(A.executorLaunchId)||!Number.isSafeInteger(A.workerVersion)||Number(A.workerVersion)<1||!S(A.workerArtifactSha256)||A.requestCancelVersion!==void 0&&A.requestCancelVersion!==1||A.managedJobsVersion!==void 0&&A.managedJobsVersion!==k)throw new G("invalid_claim_ack");return{type:"claim_ack",...A.guestMemoryVersion===1?{guestMemoryVersion:1}:{},...A.guestMemoryDiagnosticsVersion===1?{guestMemoryDiagnosticsVersion:1}:{},...A.terminalCleanupVersion===1?{terminalCleanupVersion:1}:{},...A.browserRunEnvelopeVersion===1?{browserRunEnvelopeVersion:1}:{},...A.lifecycleVersion===1?{lifecycleVersion:1}:{},...A.piToolsVersion===1?{piToolsVersion:1}:{},...A.piToolsConfinementVersion===1?{piToolsConfinementVersion:1}:{},...A.backgroundBashVersion===1?{backgroundBashVersion:1}:{},...A.machineSdkVersion===1?{machineSdkVersion:1}:{},...A.executionTimingVersion===1?{executionTimingVersion:1}:{},...A.environmentWaitVersion===1?{environmentWaitVersion:1}:{},...A.workspaceBeforeVersion===1?{workspaceBeforeVersion:1}:{},version:I,generation:A.generation,fenceId:A.fenceId,executorLaunchId:A.executorLaunchId,workerVersion:Number(A.workerVersion),workerArtifactSha256:A.workerArtifactSha256,...A.requestCancelVersion===1?{requestCancelVersion:1}:{},...A.managedJobsVersion===1?{managedJobsVersion:1}:{}}}function TA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","jobId","action","input"])||A.type!=="job"||A.version!==I||!Z(A.generation)||!M(A.id)||!M(A.jobId)||!U(A.input))throw new G("invalid_job_request");let W=A.input,N=Number.isSafeInteger(W.leaseExpiresAtMs)&&Number(W.leaseExpiresAtMs)>0,X=Number.isSafeInteger(W.sequence)&&Number(W.sequence)>=1;if(!(A.action==="start"?W.mode==="pty"?B(W,["mode","cols","rows","leaseExpiresAtMs"])&&C(A.jobId)&&z(W)&&N:B(W,["script","leaseExpiresAtMs"])&&typeof W.script==="string"&&W.script.length<=K&&N:A.action==="inspect"?B(W,["after"])&&Number.isSafeInteger(W.after)&&Number(W.after)>=0:A.action==="input"?"dataBase64"in W?B(W,["sequence","dataBase64"])&&C(A.jobId)&&X&&E(W.dataBase64)>0:B(W,["sequence","data","eof"])&&X&&typeof W.data==="string"&&W.data.length<=i&&typeof W.eof==="boolean":A.action==="resize"?B(W,["sequence","cols","rows"])&&C(A.jobId)&&X&&z(W):A.action==="renew"?B(W,["leaseExpiresAtMs"])&&N:A.action==="cancel"&&B(W,[])))throw new G("invalid_job_request");return A}function MA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","ok","job","error"])||A.type!=="job_result"||A.version!==I||!Z(A.generation)||!M(A.id))throw new G("invalid_job_result");if(A.ok===!1&&A.job===void 0&&typeof A.error==="string"&&WA.some((F)=>F===A.error))return A;let W=A.job;if(A.ok!==!0||A.error!==void 0||!U(W)||!B(W,["jobId","state","startedAtMs","finishedAtMs","leaseExpiresAtMs","exitCode","inputSequence","output","firstCursor","nextCursor","truncated","process","environmentRevision","environmentSnapshotId","pty"])||!M(W.jobId)||!["starting","running","exited","cancelled","expired","uncertain"].includes(String(W.state))||!Number.isSafeInteger(W.startedAtMs)||Number(W.startedAtMs)<1||!Number.isSafeInteger(W.leaseExpiresAtMs)||Number(W.leaseExpiresAtMs)<1||W.finishedAtMs!==null&&(!Number.isSafeInteger(W.finishedAtMs)||Number(W.finishedAtMs)<Number(W.startedAtMs))||W.exitCode!==null&&(!Number.isSafeInteger(W.exitCode)||Number(W.exitCode)<0||Number(W.exitCode)>255)||!Number.isSafeInteger(W.inputSequence)||Number(W.inputSequence)<0||!Number.isSafeInteger(W.firstCursor)||Number(W.firstCursor)<1||!Number.isSafeInteger(W.nextCursor)||Number(W.nextCursor)<Number(W.firstCursor)-1||typeof W.truncated!=="boolean"||!Array.isArray(W.output)||W.output.length>y)throw new G("invalid_job_result");if(W.environmentRevision===void 0!==(W.environmentSnapshotId===void 0)||W.environmentRevision!==void 0&&(!Number.isSafeInteger(W.environmentRevision)||Number(W.environmentRevision)<1||!J(W.environmentSnapshotId)))throw new G("invalid_job_result");let N=Number(W.firstCursor)-1,X=0;for(let F of W.output){if(!U(F)||!B(F,["cursor","stream","text"])||!Number.isSafeInteger(F.cursor)||Number(F.cursor)<=N||Number(F.cursor)>Number(W.nextCursor)||!["stdout","stderr"].includes(String(F.stream))||typeof F.text!=="string")throw new G("invalid_job_result");X+=F.text.length,N=Number(F.cursor)}if(X>d)throw new G("invalid_job_result");let V=W.state==="starting"||W.state==="running";if(V&&(W.finishedAtMs!==null||W.exitCode!==null)||!V&&W.finishedAtMs===null||W.state==="uncertain"&&W.exitCode!==null||W.state==="exited"&&W.exitCode===null||W.state==="cancelled"&&W.exitCode!==130||W.state==="expired"&&W.exitCode!==124)throw new G("invalid_job_result");if(W.process!==void 0){let F=W.process;if(!U(F)||!B(F,["pid","processGroupId","executorLaunchId"])||!Number.isSafeInteger(F.pid)||Number(F.pid)<1||F.processGroupId!==F.pid||!J(F.executorLaunchId)||!["starting","running"].includes(String(W.state)))throw new G("invalid_job_result")}if(W.pty!==void 0){let F=W.pty;if(!U(F)||!B(F,["version","cols","rows","output","cleanup"])||F.version!==H||!C(W.jobId)||!z(F)||W.output.length!==0||!Array.isArray(F.output)||F.output.length>y||(V?F.cleanup!=="pending":W.state==="uncertain"?F.cleanup!=="unconfirmed":F.cleanup!=="confirmed")||W.state==="running"&&(W.process===void 0||W.environmentRevision===void 0))throw new G("invalid_job_result");let T=Number(W.firstCursor)-1,P=0;for(let Q of F.output){if(!U(Q)||!B(Q,["cursor","dataBase64"])||!Number.isSafeInteger(Q.cursor)||Number(Q.cursor)<=T||Number(Q.cursor)>Number(W.nextCursor))throw new G("invalid_job_result");let q=E(Q.dataBase64);if(q<=0||(P+=q)>c)throw new G("invalid_job_result");T=Number(Q.cursor)}}return A}function qA(x){if(g(x)>s)throw new G("frame_too_large");let A=$(x);if(!U(A)||!B(A,["version","sessionId","operationId","runId","deviceId","rootId","workspace","binding","targetRevision","rootGrantRevision","generation","fenceId","executorLaunchId","job"])||A.version!==H||![A.sessionId,A.operationId,A.runId].every(M)||![A.deviceId,A.rootId,A.fenceId,A.executorLaunchId].every(J)||!Z(A.generation)||!Number.isSafeInteger(A.rootGrantRevision)||Number(A.rootGrantRevision)<1||!["workspace_source","mcp_control"].includes(String(A.binding))||!Number.isSafeInteger(A.targetRevision)||Number(A.targetRevision)<0||A.binding==="workspace_source"&&A.targetRevision!==0||!U(A.workspace))throw new G("invalid_pty_receipt");if(!f(A.workspace))throw new G("invalid_pty_receipt");let W=MA(JSON.stringify({type:"job_result",version:I,generation:A.generation,id:A.operationId,ok:!0,job:A.job}));if(!W.ok||!W.job.pty||W.job.pty.output.length!==0||W.job.process&&W.job.process.executorLaunchId!==A.executorLaunchId)throw new G("invalid_pty_receipt");return A}function yA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","targetId"])||A.type!=="cancel_request"||A.version!==I||!Z(A.generation)||!M(A.id)||!M(A.targetId))throw new G("invalid_cancel_request");return A}function mA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","targetId","status"])||A.type!=="cancel_ack"||A.version!==I||!Z(A.generation)||!M(A.id)||!M(A.targetId)||!["cancelled","settled","not_found","unsupported","unconfirmed"].includes(String(A.status)))throw new G("invalid_cancel_ack");return A}function wA(x){let A=JSON.stringify(x);return BA(A),A}function hA(x){let A=JSON.stringify(x);return UA(A),A}function fA(x){let A=JSON.stringify(x);return FA(A),A}function kA(x){let A=JSON.stringify(x);return IA(A),A}function HA(x){let A=JSON.stringify(x);return XA(A),A}function O(x){return typeof x==="string"&&x.length>=1&&x.length<=AA&&!x.includes("\x00")}function VA(x){let A=["type","version","generation","id","jobRequestId","verb"];if(x.verb==="help")return B(x,A)?{verb:"help"}:null;if(x.verb==="describe"||x.verb==="namespace")return B(x,[...A,"name"])&&O(x.name)?{verb:x.verb,name:x.name}:null;if(x.verb==="search"){let W=x.args;if(!B(x,[...A,"query","args"])||typeof x.query!=="string"||x.query.trim().length<1||x.query.length>xA)return null;if(W===void 0)return{verb:"search",query:x.query};if(!U(W)||!B(W,["namespace","limit"])||W.namespace!==void 0&&!O(W.namespace)||W.limit!==void 0&&(!Number.isSafeInteger(W.limit)||Number(W.limit)<1||Number(W.limit)>50))return null;return{verb:"search",query:x.query,args:{...typeof W.namespace==="string"?{namespace:W.namespace}:{},...W.limit===void 0?{}:{limit:Number(W.limit)}}}}if(x.verb!=="call"||!B(x,[...A,"name","args"])||!O(x.name)||!U(x.args)||JSON.stringify(x.args).length>K)return null;return{verb:"call",name:x.name,args:x.args}}function gA(x){let A=$(x);if(!U(A)||A.type!=="sdk_request"||A.version!==I||!Z(A.generation)||!M(A.id)||!M(A.jobRequestId))throw new G("invalid_sdk_request");let W=VA(A);if(!W)throw new G("invalid_sdk_request");return{type:"sdk_request",version:I,generation:Number(A.generation),id:A.id,jobRequestId:A.jobRequestId,...W}}function ZA(x){let A=$(x);if(!U(A)||A.type!=="sdk_response"||A.version!==I||!Z(A.generation)||!M(A.id))throw new G("invalid_sdk_response");let W={type:"sdk_response",version:I,generation:Number(A.generation),id:A.id},N=["type","version","generation","id","ok"];if(A.ok===!0&&B(A,[...N,"result"])&&typeof A.result==="string"&&A.result.length<=_)return{...W,ok:!0,result:A.result};if(A.ok===!1&&B(A,[...N,"error"])&&typeof A.error==="string"&&A.error.length>=1&&A.error.length<=_)return{...W,ok:!1,error:A.error};throw new G("invalid_sdk_response")}function EA(x){let A=JSON.stringify(x);return ZA(A),A}
4
- export{$A as tg,KA as ug,QA as vg,I as wg,b as xg,K as yg,D as zg,_ as Ag,YA as Bg,p as Cg,k as Dg,i as Eg,d as Fg,y as Gg,LA as Hg,s as Ig,H as Jg,m as Kg,c as Lg,OA as Mg,n as Ng,t as Og,r as Pg,zA as Qg,l as Rg,SA as Sg,a as Tg,w as Ug,AA as Vg,xA as Wg,WA as Xg,G as Yg,M as Zg,Z as _g,J as $g,C as ah,S as bh,BA as ch,UA as dh,FA as eh,IA as fh,XA as gh,TA as hh,MA as ih,qA as jh,yA as kh,mA as lh,wA as mh,hA as nh,fA as oh,kA as ph,HA as qh,gA as rh,ZA as sh,EA as th};
4
+ export{$A as vg,KA as wg,QA as xg,I as yg,b as zg,K as Ag,D as Bg,_ as Cg,YA as Dg,p as Eg,k as Fg,i as Gg,d as Hg,y as Ig,LA as Jg,s as Kg,H as Lg,m as Mg,c as Ng,OA as Og,n as Pg,t as Qg,r as Rg,zA as Sg,l as Tg,SA as Ug,a as Vg,w as Wg,AA as Xg,xA as Yg,WA as Zg,G as _g,M as $g,Z as ah,J as bh,C as ch,S as dh,BA as eh,UA as fh,FA as gh,IA as hh,XA as ih,TA as jh,MA as kh,qA as lh,yA as mh,mA as nh,wA as oh,hA as ph,fA as qh,kA as rh,HA as sh,gA as th,ZA as uh,EA as vh};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ch as e,Fh as p,Gh as c,Hh as QQ,xh as a}from"./vm-hands-entry-lite-70d6f5r9.js";import{Mh as O}from"./vm-hands-entry-lite-p9eyqdq7.js";import{ki as Y}from"./vm-hands-entry-lite-6z2g0td2.js";import{createHmac as EQ,createPublicKey as hQ,randomBytes as yQ,randomUUID as ZQ,verify as vQ}from"crypto";import{chmodSync as _,existsSync as $Q,mkdirSync as pQ,readFileSync as cQ,realpathSync as uQ,renameSync as dQ,statSync as lQ,unlinkSync as iQ,writeFileSync as sQ}from"fs";import{basename as nQ,dirname as R,isAbsolute as WQ,join as N,resolve as oQ}from"path";var GZ=[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 wQ="REASON_DESKTOP_RUNTIME",xQ="REASON_DESKTOP_RUNTIME_CHANNEL",VQ="REASON_DESKTOP_RUNTIME_INSTANCE_ID",MQ="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",VZ={[wQ]:"ARA_DESKTOP_RUNTIME",[xQ]:"ARA_DESKTOP_RUNTIME_CHANNEL",[VQ]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[MQ]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function C(Q){if(Q===void 0)return;if(!/^[a-f0-9]{64}$/.test(Q))throw Error("Invalid desktop workspace scope.");return Q}import{chmodSync as f,existsSync as U,mkdirSync as B,readFileSync as E,realpathSync as KQ,renameSync as fQ,unlinkSync as k,writeFileSync as A}from"fs";import{createPrivateKey as BQ,createPublicKey as kQ,generateKeyPairSync as AQ,randomUUID as FQ,sign as TQ}from"crypto";import{createRequire as _Q}from"module";import{homedir as PQ,platform as u}from"os";import{dirname as RQ,join as H}from"path";import{existsSync as NQ}from"fs";import{join as m}from"path";var K="libara_device_keychain.dylib",I="libreason_device_keychain.dylib";class OQ extends Error{code;constructor(Q,Z){super(Z);this.code=Q;this.name="ManagedRuntimeError"}}function g(Q){let Z=m(Q,I);return NQ(Z)?Z:m(Q,K)}var h=1,DQ=16384,w=65536,bQ=128,SQ=128,d=65536;class X 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 l(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 F=null;function i(){if(!F)try{F=_Q(import.meta.url)("bun:ffi")}catch{throw new X("native_boundary_unavailable")}return F}function LQ(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 CQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))throw new X("invalid_credential_record");let Z=Q,$=LQ(Z.apiOrigin);if(Z.version!==h||!$||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 X("invalid_credential_record");return{version:h,apiOrigin:$,orgId:Z.orgId,deviceId:Z.deviceId,credential:Z.credential}}function IQ(Q=process.execPath){let Z=Q;try{Z=KQ(Q)}catch{}return g(RQ(Z))}function z(Q){return i().ptr(Q)}function mQ(Q){if(!U(Q))throw new X("native_boundary_unavailable");let{dlopen:Z,FFIType:$}=i();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(W){if(W instanceof X)throw W;throw new X("native_boundary_unavailable")}}function y(Q){return Buffer.from(Q).toString("base64url")}function x(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 s(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 n{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(Q=IQ(),Z=u(),$){this.libraryPath=Q;this.runtimePlatform=Z;this.workspaceScope=$;C($)}symbols(){if(this.runtimePlatform!=="darwin")throw new X("unsupported_platform");this.library??=mQ(this.libraryPath);let Q=new TextEncoder().encode(this.workspaceScope??""),Z=this.library.symbols.ara_device_configure_scope(z(Q.length?Q:new Uint8Array(1)),BigInt(Q.length));if(Z!==0)throw new X("native_boundary_unavailable",Z);return this.library.symbols}publicKey(Q){let Z=new Uint8Array(bQ),$=new BigUint64Array(1),W=Q==="load"?this.symbols().ara_device_key_load_public(z(Z),BigInt(Z.byteLength),z($)):this.symbols().ara_device_key_create_fresh_public(z(Z),BigInt(Z.byteLength),z($));if(W!==0)throw new X(Q==="load"?"proof_key_read_failed":"proof_key_generation_failed",W);let j=Number($[0]);if(!Number.isSafeInteger(j)||j!==65)throw new X("invalid_public_key");let q=y(Z.subarray(0,j));if(!x(q))throw new X("invalid_public_key");return q}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(Q){if(Q.byteLength<1||Q.byteLength>d)throw new X("proof_sign_failed");let Z=new Uint8Array(SQ),$=new BigUint64Array(1),W=this.symbols().ara_device_key_sign(z(Q),BigInt(Q.byteLength),z(Z),BigInt(Z.byteLength),z($));if(W!==0)throw new X("proof_sign_failed",W);let j=Number($[0]);if(!Number.isSafeInteger(j)||j<1||j>Z.byteLength)throw new X("invalid_signature");let q=Z.subarray(0,j);if(!s(q))throw new X("invalid_signature");return y(q)}privateKeyIsNonExtractable(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_is_non_extractable(z(Q));if(Z!==0||Q[0]!==1)throw new X("proof_key_read_failed",Z);return!0}deleteKey(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_delete(z(Q));if(Z!==0)throw new X("proof_key_delete_failed",Z);return Q[0]===1}loadBinding(){let Q=new Uint8Array(w),Z=new BigUint64Array(1),$=this.symbols().ara_device_binding_read(z(Q),BigInt(Q.byteLength),z(Z));if($===1)return null;if($!==0)throw new X("binding_read_failed",$);let W=Number(Z[0]);if(!Number.isSafeInteger(W)||W<1||W>Q.byteLength)throw new X("invalid_binding");return Q.slice(0,W)}createBinding(Q){if(Q.byteLength<1||Q.byteLength>w)throw new X("invalid_binding");let Z=this.symbols().ara_device_binding_create(z(Q),BigInt(Q.byteLength));if(Z!==0)throw new X("binding_create_failed",Z)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>w)throw new X("invalid_binding");let Z=this.symbols().ara_device_binding_update(z(Q),BigInt(Q.byteLength));if(Z!==0)throw new X("binding_update_failed",Z)}deleteBinding(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_binding_delete(z(Q));if(Z!==0)throw new X("binding_delete_failed",Z);return Q[0]===1}loadLegacyCredential(){let Q=new Uint8Array(DQ),Z=new BigUint64Array(1),$=this.symbols().ara_device_keychain_read(z(Q),BigInt(Q.byteLength),z(Z));if($===1)return null;if($!==0)throw new X("legacy_credential_read_failed",$);let W=Number(Z[0]);if(!Number.isSafeInteger(W)||W<1||W>Q.byteLength)throw new X("invalid_credential_record");try{let j=new TextDecoder("utf-8",{fatal:!0}).decode(Q.subarray(0,W));return CQ(JSON.parse(j))}catch(j){if(j instanceof X)throw j;throw new X("invalid_credential_record")}}deleteLegacyCredential(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_keychain_delete(z(Q));if(Z!==0)throw new X("legacy_credential_delete_failed",Z);return Q[0]===1}}function v(Q){let Z=Q.export({format:"jwk"});if(Z.crv!=="P-256"||typeof Z.x!=="string"||typeof Z.y!=="string")throw new X("invalid_public_key");let $=Buffer.from(Z.x,"base64url"),W=Buffer.from(Z.y,"base64url");if($.byteLength!==32||W.byteLength!==32)throw new X("invalid_public_key");let j=Buffer.concat([Buffer.of(4),$,W]).toString("base64url");if(!x(j))throw new X("invalid_public_key");return j}function gQ(){let Q=process.env.XDG_CONFIG_HOME?.trim()||H(PQ(),".config");c(Q);let Z=H(Q,"ara");return p(Z)?Z:H(Q,"reason")}class o{directory;constructor(Q=gQ()){this.directory=Q}keyPath(){return H(this.directory,"local-device.key")}bindingPath(){return H(this.directory,"local-device.binding")}loadPrivateKeyObject(){let Q=this.keyPath();if(!U(Q))throw new X("proof_key_read_failed");try{let Z=E(Q,"utf8");return BQ({key:Z,format:"pem"})}catch{throw new X("proof_key_read_failed")}}loadPublicKey(){let Q=this.loadPrivateKeyObject(),Z=kQ(Q);return v(Z)}createFreshPublicKey(){B(this.directory,{recursive:!0,mode:448});let{privateKey:Q,publicKey:Z}=AQ("ec",{namedCurve:"P-256"}),$=Q.export({type:"pkcs8",format:"pem"}),W=this.keyPath();return A(W,$,{mode:384}),f(W,384),v(Z)}sign(Q){if(Q.byteLength<1||Q.byteLength>d)throw new X("proof_sign_failed");let Z=this.loadPrivateKeyObject(),$;try{$=TQ("sha256",Q,Z)}catch{throw new X("proof_sign_failed")}if(!s($))throw new X("invalid_signature");return $.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let Q=this.keyPath();if(!U(Q))return!1;return k(Q),!0}loadBinding(){let Q=this.bindingPath();if(!U(Q))return null;try{return new Uint8Array(E(Q))}catch{return null}}createBinding(Q){if(Q.byteLength<1||Q.byteLength>w)throw new X("invalid_binding");B(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(U(Z))throw new X("binding_create_failed");A(Z,Q,{mode:384}),f(Z,384)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>w)throw new X("invalid_binding");B(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(!U(Z))throw new X("binding_update_failed");let $=`${Z}.${FQ()}`;try{A($,Q,{mode:384,flag:"wx"}),f($,384),fQ($,Z)}finally{if(U($))k($)}}deleteBinding(){let Q=this.bindingPath();if(!U(Q))return!1;return k(Q),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function T(){return u()==="darwin"?new n:new o}var V=Y.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),r=Y.object({id:V,kind:Y.literal("permission_denied"),operation:Y.enum(["bash","read","write","edit"]),provenance:Y.enum(["sandbox_policy","os_permission_unknown"]),occurredAt:Y.string().datetime(),expiresAt:Y.string().datetime(),sessionId:V,deviceId:V,organizationId:V}).strict();var D=4;var M="macos-keychain-p256-v1",XQ=1,rQ=`ARA-DEVICE-BINDING-V1
2
+ import{Eh as e,Hh as p,Ih as c,Jh as QQ,zh as a}from"./vm-hands-entry-lite-1xjtcxpn.js";import{Oh as O}from"./vm-hands-entry-lite-9dx3at21.js";import{mi as Y}from"./vm-hands-entry-lite-2xh7sjs0.js";import{createHmac as EQ,createPublicKey as hQ,randomBytes as yQ,randomUUID as ZQ,verify as vQ}from"crypto";import{chmodSync as _,existsSync as $Q,mkdirSync as pQ,readFileSync as cQ,realpathSync as uQ,renameSync as dQ,statSync as lQ,unlinkSync as iQ,writeFileSync as sQ}from"fs";import{basename as nQ,dirname as R,isAbsolute as WQ,join as N,resolve as oQ}from"path";var GZ=[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 wQ="REASON_DESKTOP_RUNTIME",xQ="REASON_DESKTOP_RUNTIME_CHANNEL",VQ="REASON_DESKTOP_RUNTIME_INSTANCE_ID",MQ="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",VZ={[wQ]:"ARA_DESKTOP_RUNTIME",[xQ]:"ARA_DESKTOP_RUNTIME_CHANNEL",[VQ]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[MQ]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function C(Q){if(Q===void 0)return;if(!/^[a-f0-9]{64}$/.test(Q))throw Error("Invalid desktop workspace scope.");return Q}import{chmodSync as f,existsSync as U,mkdirSync as B,readFileSync as E,realpathSync as KQ,renameSync as fQ,unlinkSync as k,writeFileSync as A}from"fs";import{createPrivateKey as BQ,createPublicKey as kQ,generateKeyPairSync as AQ,randomUUID as FQ,sign as TQ}from"crypto";import{createRequire as _Q}from"module";import{homedir as PQ,platform as u}from"os";import{dirname as RQ,join as H}from"path";import{existsSync as NQ}from"fs";import{join as m}from"path";var K="libara_device_keychain.dylib",I="libreason_device_keychain.dylib";class OQ extends Error{code;constructor(Q,Z){super(Z);this.code=Q;this.name="ManagedRuntimeError"}}function g(Q){let Z=m(Q,I);return NQ(Z)?Z:m(Q,K)}var h=1,DQ=16384,w=65536,bQ=128,SQ=128,d=65536;class X 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 l(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 F=null;function i(){if(!F)try{F=_Q(import.meta.url)("bun:ffi")}catch{throw new X("native_boundary_unavailable")}return F}function LQ(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 CQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))throw new X("invalid_credential_record");let Z=Q,$=LQ(Z.apiOrigin);if(Z.version!==h||!$||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 X("invalid_credential_record");return{version:h,apiOrigin:$,orgId:Z.orgId,deviceId:Z.deviceId,credential:Z.credential}}function IQ(Q=process.execPath){let Z=Q;try{Z=KQ(Q)}catch{}return g(RQ(Z))}function z(Q){return i().ptr(Q)}function mQ(Q){if(!U(Q))throw new X("native_boundary_unavailable");let{dlopen:Z,FFIType:$}=i();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(W){if(W instanceof X)throw W;throw new X("native_boundary_unavailable")}}function y(Q){return Buffer.from(Q).toString("base64url")}function x(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 s(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 n{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(Q=IQ(),Z=u(),$){this.libraryPath=Q;this.runtimePlatform=Z;this.workspaceScope=$;C($)}symbols(){if(this.runtimePlatform!=="darwin")throw new X("unsupported_platform");this.library??=mQ(this.libraryPath);let Q=new TextEncoder().encode(this.workspaceScope??""),Z=this.library.symbols.ara_device_configure_scope(z(Q.length?Q:new Uint8Array(1)),BigInt(Q.length));if(Z!==0)throw new X("native_boundary_unavailable",Z);return this.library.symbols}publicKey(Q){let Z=new Uint8Array(bQ),$=new BigUint64Array(1),W=Q==="load"?this.symbols().ara_device_key_load_public(z(Z),BigInt(Z.byteLength),z($)):this.symbols().ara_device_key_create_fresh_public(z(Z),BigInt(Z.byteLength),z($));if(W!==0)throw new X(Q==="load"?"proof_key_read_failed":"proof_key_generation_failed",W);let j=Number($[0]);if(!Number.isSafeInteger(j)||j!==65)throw new X("invalid_public_key");let q=y(Z.subarray(0,j));if(!x(q))throw new X("invalid_public_key");return q}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(Q){if(Q.byteLength<1||Q.byteLength>d)throw new X("proof_sign_failed");let Z=new Uint8Array(SQ),$=new BigUint64Array(1),W=this.symbols().ara_device_key_sign(z(Q),BigInt(Q.byteLength),z(Z),BigInt(Z.byteLength),z($));if(W!==0)throw new X("proof_sign_failed",W);let j=Number($[0]);if(!Number.isSafeInteger(j)||j<1||j>Z.byteLength)throw new X("invalid_signature");let q=Z.subarray(0,j);if(!s(q))throw new X("invalid_signature");return y(q)}privateKeyIsNonExtractable(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_is_non_extractable(z(Q));if(Z!==0||Q[0]!==1)throw new X("proof_key_read_failed",Z);return!0}deleteKey(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_delete(z(Q));if(Z!==0)throw new X("proof_key_delete_failed",Z);return Q[0]===1}loadBinding(){let Q=new Uint8Array(w),Z=new BigUint64Array(1),$=this.symbols().ara_device_binding_read(z(Q),BigInt(Q.byteLength),z(Z));if($===1)return null;if($!==0)throw new X("binding_read_failed",$);let W=Number(Z[0]);if(!Number.isSafeInteger(W)||W<1||W>Q.byteLength)throw new X("invalid_binding");return Q.slice(0,W)}createBinding(Q){if(Q.byteLength<1||Q.byteLength>w)throw new X("invalid_binding");let Z=this.symbols().ara_device_binding_create(z(Q),BigInt(Q.byteLength));if(Z!==0)throw new X("binding_create_failed",Z)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>w)throw new X("invalid_binding");let Z=this.symbols().ara_device_binding_update(z(Q),BigInt(Q.byteLength));if(Z!==0)throw new X("binding_update_failed",Z)}deleteBinding(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_binding_delete(z(Q));if(Z!==0)throw new X("binding_delete_failed",Z);return Q[0]===1}loadLegacyCredential(){let Q=new Uint8Array(DQ),Z=new BigUint64Array(1),$=this.symbols().ara_device_keychain_read(z(Q),BigInt(Q.byteLength),z(Z));if($===1)return null;if($!==0)throw new X("legacy_credential_read_failed",$);let W=Number(Z[0]);if(!Number.isSafeInteger(W)||W<1||W>Q.byteLength)throw new X("invalid_credential_record");try{let j=new TextDecoder("utf-8",{fatal:!0}).decode(Q.subarray(0,W));return CQ(JSON.parse(j))}catch(j){if(j instanceof X)throw j;throw new X("invalid_credential_record")}}deleteLegacyCredential(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_keychain_delete(z(Q));if(Z!==0)throw new X("legacy_credential_delete_failed",Z);return Q[0]===1}}function v(Q){let Z=Q.export({format:"jwk"});if(Z.crv!=="P-256"||typeof Z.x!=="string"||typeof Z.y!=="string")throw new X("invalid_public_key");let $=Buffer.from(Z.x,"base64url"),W=Buffer.from(Z.y,"base64url");if($.byteLength!==32||W.byteLength!==32)throw new X("invalid_public_key");let j=Buffer.concat([Buffer.of(4),$,W]).toString("base64url");if(!x(j))throw new X("invalid_public_key");return j}function gQ(){let Q=process.env.XDG_CONFIG_HOME?.trim()||H(PQ(),".config");c(Q);let Z=H(Q,"ara");return p(Z)?Z:H(Q,"reason")}class o{directory;constructor(Q=gQ()){this.directory=Q}keyPath(){return H(this.directory,"local-device.key")}bindingPath(){return H(this.directory,"local-device.binding")}loadPrivateKeyObject(){let Q=this.keyPath();if(!U(Q))throw new X("proof_key_read_failed");try{let Z=E(Q,"utf8");return BQ({key:Z,format:"pem"})}catch{throw new X("proof_key_read_failed")}}loadPublicKey(){let Q=this.loadPrivateKeyObject(),Z=kQ(Q);return v(Z)}createFreshPublicKey(){B(this.directory,{recursive:!0,mode:448});let{privateKey:Q,publicKey:Z}=AQ("ec",{namedCurve:"P-256"}),$=Q.export({type:"pkcs8",format:"pem"}),W=this.keyPath();return A(W,$,{mode:384}),f(W,384),v(Z)}sign(Q){if(Q.byteLength<1||Q.byteLength>d)throw new X("proof_sign_failed");let Z=this.loadPrivateKeyObject(),$;try{$=TQ("sha256",Q,Z)}catch{throw new X("proof_sign_failed")}if(!s($))throw new X("invalid_signature");return $.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let Q=this.keyPath();if(!U(Q))return!1;return k(Q),!0}loadBinding(){let Q=this.bindingPath();if(!U(Q))return null;try{return new Uint8Array(E(Q))}catch{return null}}createBinding(Q){if(Q.byteLength<1||Q.byteLength>w)throw new X("invalid_binding");B(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(U(Z))throw new X("binding_create_failed");A(Z,Q,{mode:384}),f(Z,384)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>w)throw new X("invalid_binding");B(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(!U(Z))throw new X("binding_update_failed");let $=`${Z}.${FQ()}`;try{A($,Q,{mode:384,flag:"wx"}),f($,384),fQ($,Z)}finally{if(U($))k($)}}deleteBinding(){let Q=this.bindingPath();if(!U(Q))return!1;return k(Q),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function T(){return u()==="darwin"?new n:new o}var V=Y.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),r=Y.object({id:V,kind:Y.literal("permission_denied"),operation:Y.enum(["bash","read","write","edit"]),provenance:Y.enum(["sandbox_policy","os_permission_unknown"]),occurredAt:Y.string().datetime(),expiresAt:Y.string().datetime(),sessionId:V,deviceId:V,organizationId:V}).strict();var D=4;var M="macos-keychain-p256-v1",XQ=1,rQ=`ARA-DEVICE-BINDING-V1
3
3
  `;function tQ(Q){return Q===void 0||typeof Q==="number"&&Number.isInteger(Q)&&Q>=1&&Q<=4}function jQ(Q,Z=Date.now()){let $=r.safeParse(Q);if(!$.success)return!1;let W=$.data,j=typeof W.occurredAt==="string"?Date.parse(W.occurredAt):NaN,q=typeof W.expiresAt==="string"?Date.parse(W.expiresAt):NaN;return W.kind==="permission_denied"&&["bash","read","write","edit"].includes(W.operation)&&["sandbox_policy","os_permission_unknown"].includes(W.provenance)&&Number.isFinite(j)&&j<=Z&&q>Z&&q>j&&q-j<=600000}function uZ(Q,Z,$=Date.now()){if(!Q||!Z||Q.state!=="connected"||Q.deviceId!==Z.deviceId)return null;let W=Date.parse(Q.lastHeartbeatAt??""),j=Q.permissionRecovery;if(!($-W>=0&&$-W<30000)||!jQ(j,$)||j.deviceId!==Z.deviceId||j.organizationId!==Z.orgId)return null;try{process.kill(Q.pid,0)}catch{return null}return j}function qQ(Q={},Z=O()){let $=a({env:{...process.env,...Q}}),W=Q.XDG_CONFIG_HOME?.trim()||N(Z,".config");return QQ(W,...$==="staging"?["staging"]:[])}function b(Q={},Z=O()){return N(qQ(Q,Z),"local-device.json")}function zQ(Q={},Z=O()){return N(qQ(Q,Z),"local-daemon.json")}function S(Q,Z){pQ(R(Q),{recursive:!0,mode:448}),_(R(Q),448);let $=`${Q}.${process.pid}.${ZQ()}.tmp`;try{sQ($,`${JSON.stringify(Z,null,2)}
4
4
  `,{mode:384,flag:"wx"}),_($,384),dQ($,Q),_(Q,384)}finally{if($Q($))iQ($)}return Q}function L(Q){if(!$Q(Q))return null;try{return JSON.parse(cQ(Q,"utf8"))}catch{return null}}function P(Q,Z,$){try{Q.onCredentialLifecycle?.({event:Z,...$?{reasonCode:$}:{}})}catch{}}function aQ(Q){if(!Array.isArray(Q))return null;let Z=[];for(let $ of Q){if(!$||typeof $!=="object")return null;let W=$;if(typeof W.id!=="string"||typeof W.label!=="string"||typeof W.path!=="string"||typeof W.pathFingerprint!=="string"||!W.permissions||typeof W.permissions.read!=="boolean"||typeof W.permissions.write!=="boolean"||typeof W.permissions.execute!=="boolean"||typeof W.permissions.discover_environment!=="boolean"||typeof W.permissions.expose_mcp!=="boolean")return null;Z.push({id:W.id,label:W.label,path:W.path,pathFingerprint:W.pathFingerprint,permissions:W.permissions})}return Z}function GQ(Q,Z,$=[]){let W=Object.keys(Q);return Z.every((j)=>Object.hasOwn(Q,j))&&W.every((j)=>Z.includes(j)||$.includes(j))}function eQ(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 JQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let Z=Q,$=aQ(Z.roots),W=eQ(Z.apiOrigin);if(!W||typeof Z.orgId!=="string"||typeof Z.deviceId!=="string"||typeof Z.displayName!=="string"||typeof Z.registeredAt!=="string"||!tQ(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:W,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 QZ(Q){return{...Q,credentialStorage:M}}function ZZ(Q){return{version:D,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:M}}function UQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let Z=Q;if(!GQ(Z,["version","apiOrigin","orgId","deviceId","devicePublicKey","displayName","registeredAt","roots","credentialStorage"],["handsSlots","worker"]))return null;let $=JQ(Z);if(!$||Z.version!==D||Z.credentialStorage!==M||!x(Z.devicePublicKey))return null;return{version:D,...$,devicePublicKey:Z.devicePublicKey,credentialStorage:M}}function YQ(Q){return new TextEncoder().encode(`${rQ}${JSON.stringify(ZZ(Q))}`)}function $Z(Q){let Z=Buffer.from(Q,"base64url");return hQ({format:"jwk",key:{kty:"EC",crv:"P-256",x:Z.subarray(1,33).toString("base64url"),y:Z.subarray(33,65).toString("base64url")}})}function WZ(Q,Z){let $={version:XQ,state:Q,signature:Z.sign(YQ(Q))};return new TextEncoder().encode(JSON.stringify($))}function HQ(Q){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Q))}catch{throw new X("invalid_binding")}if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new X("invalid_binding");let $=Z;if(!GQ($,["version","state","signature"])||$.version!==XQ||typeof $.signature!=="string"||!/^[A-Za-z0-9_-]{10,128}$/.test($.signature))throw new X("invalid_binding");let W=UQ($.state);if(!W)throw new X("invalid_binding");let j=!1;try{j=vQ("sha256",YQ(W),$Z(W.devicePublicKey),Buffer.from($.signature,"base64url"))}catch{j=!1}if(!j)throw new X("invalid_binding");return W}function XZ(Q){let{credentialStorage:Z,...$}=Q;return $}function jZ(Q){return Q instanceof X?l(Q):"credential_boundary_failed"}function dZ(Q=b(),Z={}){let $=L(Q),W=Z.proofStore??Z.credentialStore??T(),j=W.loadBinding();if(!j){if($&&typeof $==="object"&&!Array.isArray($)&&qZ($))return null;if($!==null)throw new X("invalid_binding");return null}let q=HQ(j),G=W.loadPublicKey();if(W.privateKeyIsNonExtractable(),G!==q.devicePublicKey)throw new X("invalid_public_key");let J=UQ($);if(Z.repair!==!1&&(!J||JSON.stringify(J)!==JSON.stringify(q)))S(Q,q);return XZ(q)}function qZ(Q){let Z=Q,$=JQ(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 lZ(Q,Z=b(),$={}){let W=$.proofStore??$.credentialStore??T();P($,"credential.store_started");try{if(!x(Q.devicePublicKey)||W.loadPublicKey()!==Q.devicePublicKey)throw new X("invalid_public_key");W.privateKeyIsNonExtractable();let j=QZ(Q),q=W.loadBinding();if(q){let J=HQ(q);if(J.devicePublicKey!==Q.devicePublicKey||J.orgId!==Q.orgId||J.deviceId!==Q.deviceId||J.apiOrigin!==Q.apiOrigin&&!e(J.apiOrigin,Q.apiOrigin))throw new X("invalid_binding")}let G=WZ(j,W);if(q)W.updateBinding(G);else W.createBinding(G);return S(Z,j),P($,"credential.store_completed"),Z}catch(j){throw P($,"credential.store_failed",jZ(j)),j}}function iZ(Q=zQ()){let Z=L(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;if($.permissionRecovery!==void 0&&!jQ($.permissionRecovery))delete $.permissionRecovery;return $}function sZ(Q,Z=zQ()){return S(Z,Q)}var t=1;function zZ(Q=b()){return N(R(Q),"local-device.proxy.json")}function nZ(Q=zZ()){let Z=L(Q);if(!Z||typeof Z!=="object"||Array.isArray(Z))return null;let $=Z;if($.version!==t||typeof $.url!=="string"||$.url.length===0||$.caFile!==void 0&&(typeof $.caFile!=="string"||!WQ($.caFile)))return null;return{version:t,url:$.url,...$.caFile?{caFile:$.caFile}:{}}}function oZ(Q,Z={read:!0,write:!1,execute:!1,discover_environment:!1,expose_mcp:!1},$=yQ(32)){let W=new Set,j=[];for(let q of Q){let G=uQ(WQ(q)?q:oQ(q));if(!lQ(G).isDirectory())throw Error(`Local execution root is not a directory: ${q}`);if(W.has(G))continue;W.add(G),j.push({id:ZQ(),label:nQ(G)||G,path:G,pathFingerprint:EQ("sha256",$).update(G).digest("hex"),permissions:{...Z}})}if(j.length===0)throw Error("At least one explicit local execution root is required.");return j}
5
- export{OQ as bg,X as cg,IQ as dg,x as eg,s as fg,n as gg,o as hg,jQ as ig,uZ as jg,b as kg,zQ as lg,dZ as mg,lZ as ng,iZ as og,sZ as pg,t as qg,nZ as rg,oZ as sg};
5
+ export{OQ as dg,X as eg,IQ as fg,x as gg,s as hg,n as ig,o as jg,jQ as kg,uZ as lg,b as mg,zQ as ng,dZ as og,lZ as pg,iZ as qg,sZ as rg,t as sg,nZ as tg,oZ as ug};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{D as T,F as U}from"./vm-hands-entry-lite-5qe562gn.js";import{qc as V}from"./vm-hands-entry-lite-8ynztq9j.js";import{uh as G,xh as M,yh as Q}from"./vm-hands-entry-lite-70d6f5r9.js";function W(j,B){let k=G(j,"REASON_API_URL")?.trim();if(!k)return Q(B);let z=new URL(k);if(z.protocol!=="https:"&&!(z.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(z.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return z.origin}function X(j){return G(j,"REASON_API_URL")?.trim()?W(j,"production"):void 0}function $(j){return G(j,"REASON_API_KEY")?.trim()||void 0}async function N(j,B){let k=j.env??process.env,z=$(k);if(!z)return(j.getCredentials??T)({apiOrigin:X(k),signal:B});let J=W(k,j.channel??M({env:k})),D=await(j.fetchImpl??fetch)(J+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+z,accept:"application/json"},signal:B}),L=await D.json().catch(()=>({})),w=V(L)?L:{};if(!D.ok){let H=typeof w.detail==="string"?w.detail:typeof w.message==="string"?w.message:"API key authentication failed ("+D.status+")";throw new U(D.status,typeof w.error==="string"?w.error:"api_key_auth_failed",H)}if(typeof w.org_id!=="string"||!w.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let Z=Array.isArray(w.scopes)?w.scopes.filter((H)=>typeof H==="string"):[];return{credentialKind:"api_key",apiOrigin:J,accessToken:z,orgId:w.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:Z}}async function P(j){let B=await N(j),k=X(j.env??process.env);if(!B)throw Error(k?`Not signed in to ${k}. Set REASON_API_KEY, or run \`reason login --api-url ${k}\`.`:"Not signed in. Run `reason login`, or set REASON_API_KEY.");return B}
2
+ import{D as T,F as U}from"./vm-hands-entry-lite-pnkfgnqz.js";import{qc as V}from"./vm-hands-entry-lite-8ynztq9j.js";import{Ah as Q,wh as G,zh as M}from"./vm-hands-entry-lite-1xjtcxpn.js";function W(j,B){let k=G(j,"REASON_API_URL")?.trim();if(!k)return Q(B);let z=new URL(k);if(z.protocol!=="https:"&&!(z.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(z.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return z.origin}function X(j){return G(j,"REASON_API_URL")?.trim()?W(j,"production"):void 0}function $(j){return G(j,"REASON_API_KEY")?.trim()||void 0}async function N(j,B){let k=j.env??process.env,z=$(k);if(!z)return(j.getCredentials??T)({apiOrigin:X(k),signal:B});let J=W(k,j.channel??M({env:k})),D=await(j.fetchImpl??fetch)(J+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+z,accept:"application/json"},signal:B}),L=await D.json().catch(()=>({})),w=V(L)?L:{};if(!D.ok){let H=typeof w.detail==="string"?w.detail:typeof w.message==="string"?w.message:"API key authentication failed ("+D.status+")";throw new U(D.status,typeof w.error==="string"?w.error:"api_key_auth_failed",H)}if(typeof w.org_id!=="string"||!w.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let Z=Array.isArray(w.scopes)?w.scopes.filter((H)=>typeof H==="string"):[];return{credentialKind:"api_key",apiOrigin:J,accessToken:z,orgId:w.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:Z}}async function P(j){let B=await N(j),k=X(j.env??process.env);if(!B)throw Error(k?`Not signed in to ${k}. Set REASON_API_KEY, or run \`reason login --api-url ${k}\`.`:"Not signed in. Run `reason login`, or set REASON_API_KEY.");return B}
3
3
  export{W as v,X as w,$ as x,N as y,P as z};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var n=Object.create;var{getPrototypeOf:o,defineProperty:e,getOwnPropertyNames:k,getOwnPropertyDescriptor:p}=Object,l=Object.prototype.hasOwnProperty;function m(a){return this[a]}var q,r,u=(a,b,c)=>{var d=a!=null&&typeof a==="object";if(d){var h=b?q??=new WeakMap:r??=new WeakMap,i=h.get(a);if(i)return i}c=a!=null?n(o(a)):{};let f=b||!a||!a.__esModule?e(c,"default",{value:a,enumerable:!0}):c;for(let g of k(a))if(!l.call(f,g))e(f,g,{get:m.bind(a,g),enumerable:!0});if(d)h.set(a,f);return f},v=(a)=>{var b=(j??=new WeakMap).get(a),c;if(b)return b;if(b=e({},"__esModule",{value:!0}),a&&typeof a==="object"||typeof a==="function"){for(var d of k(a))if(!l.call(b,d))e(b,d,{get:m.bind(a,d),enumerable:!(c=p(a,d))||c.enumerable})}return j.set(a,b),b},j,w=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var s=(a)=>a;function t(a,b){this[a]=s.bind(null,b)}var x=(a,b)=>{for(var c in b)e(a,c,{get:b[c],enumerable:!0,configurable:!0,set:t.bind(b,c)})};var y=(a,b)=>()=>(a&&(b=a(a=0)),b);var z=import.meta.require;
3
- export{u as ti,v as ui,w as vi,x as wi,y as xi,z as yi};
3
+ export{u as vi,v as wi,w as xi,x as yi,y as zi,z as Ai};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Mh as J}from"./vm-hands-entry-lite-p9eyqdq7.js";import{readFileSync as L}from"fs";import{isAbsolute as M,normalize as Q}from"path";var W="REASON_WORKER_DESKTOP_USER",G=null;function X(q,B){for(let I of B.split(`
2
+ import{Oh as J}from"./vm-hands-entry-lite-9dx3at21.js";import{readFileSync as L}from"fs";import{isAbsolute as M,normalize as Q}from"path";var W="REASON_WORKER_DESKTOP_USER",G=null;function X(q,B){for(let I of B.split(`
3
3
  `)){let j=I.split(":");if(j.length<7||Number(j[2])!==q||!/^\d+$/.test(j[2])||!/^\d+$/.test(j[3]))continue;let x=j[5];if(!/^[a-z_][a-z0-9_-]*$/i.test(j[0])||!M(x)||Q(x)!==x||x==="/")return null;return{username:j[0],uid:q,gid:Number(j[3]),home:x}}return null}function b(q={}){let B="value"in q?q.value:process.env[W];if(G=null,B===void 0||B==="")return null;let I=q.platform??process.platform,j="euid"in q?q.euid:process.geteuid?.(),x=/^[1-9]\d{0,9}$/.test(B)?Number(B):NaN,C=I==="linux"&&j===0&&Number.isSafeInteger(x)?X(x,(q.passwd??(()=>L("/etc/passwd","utf8")))()):null;if(!C||C.gid===0)throw Error("worker_desktop_user_invalid");return G=C,C}function k(){return G}function y(){return G?.home??J()}
4
- export{W as Xe,X as Ye,b as Ze,k as _e,y as $e};
4
+ export{W as Ze,X as _e,b as $e,k as af,y as bf};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{M as f}from"./vm-hands-entry-lite-21sg3fyz.js";import{Ah as U,Bh as y,Hh as T,uh as v,xh as K}from"./vm-hands-entry-lite-70d6f5r9.js";import{ki as $}from"./vm-hands-entry-lite-6z2g0td2.js";var c=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function _(x){let w=typeof x==="string"?c.exec(x):null;return w?{major:Number(w[1]),minor:Number(w[2])}:null}import{createHash as s,randomBytes as j}from"crypto";import{createInterface as o}from"readline";import{randomBytes as d}from"crypto";import{chmodSync as q,existsSync as C,lstatSync as l,mkdirSync as a,readFileSync as b,renameSync as p,unlinkSync as O,writeFileSync as L}from"fs";import{homedir as t}from"os";import{dirname as i,join as F}from"path";function B(x=process.env,w=t()){let H=x.XDG_CONFIG_HOME?.trim()||F(w,".config"),J=K({env:x})==="staging"?["staging"]:[];return F(T(H,...J),"credentials.json")}function A(x,w=B()){return a(i(w),{recursive:!0,mode:448}),L(w,`${JSON.stringify(x,null,2)}
2
+ import{M as f}from"./vm-hands-entry-lite-tfpebnar.js";import{Ch as U,Dh as y,Jh as T,wh as v,zh as K}from"./vm-hands-entry-lite-1xjtcxpn.js";import{mi as $}from"./vm-hands-entry-lite-2xh7sjs0.js";var c=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function _(x){let w=typeof x==="string"?c.exec(x):null;return w?{major:Number(w[1]),minor:Number(w[2])}:null}import{createHash as s,randomBytes as j}from"crypto";import{createInterface as o}from"readline";import{randomBytes as d}from"crypto";import{chmodSync as q,existsSync as C,lstatSync as l,mkdirSync as a,readFileSync as b,renameSync as p,unlinkSync as O,writeFileSync as L}from"fs";import{homedir as t}from"os";import{dirname as i,join as F}from"path";function B(x=process.env,w=t()){let H=x.XDG_CONFIG_HOME?.trim()||F(w,".config"),J=K({env:x})==="staging"?["staging"]:[];return F(T(H,...J),"credentials.json")}function A(x,w=B()){return a(i(w),{recursive:!0,mode:448}),L(w,`${JSON.stringify(x,null,2)}
3
3
  `,{mode:384}),q(w,384),w}function M(x=B()){if(!C(x))return null;try{let w=b(x,"utf8"),H=JSON.parse(w);if(typeof H.apiOrigin!=="string"||typeof H.clientId!=="string"||typeof H.accessToken!=="string"||typeof H.refreshToken!=="string"||typeof H.expiresAt!=="string"||typeof H.orgId!=="string"||!Array.isArray(H.scopes))return null;let G=new URL(H.apiOrigin).origin,J=U(G);if(J!==G)n(x,w,J);return{apiOrigin:J,clientId:H.clientId,accessToken:H.accessToken,refreshToken:H.refreshToken,expiresAt:H.expiresAt,scopes:H.scopes.filter((Q)=>typeof Q==="string"),orgId:H.orgId}}catch{return null}}function n(x,w,H){let G=`${x}.${process.pid}.${d(6).toString("hex")}.tmp`;try{let J=l(x);if(!J.isFile()||J.uid!==process.geteuid?.())return;let Q=JSON.parse(w);if(L(G,`${JSON.stringify({...Q,apiOrigin:H},null,2)}
4
4
  `,{mode:384,flag:"wx"}),q(G,384),b(x,"utf8")!==w)throw Error("credentials_changed");p(G,x)}catch{try{O(G)}catch{}}}function R(x=B()){if(!C(x))return!1;return O(x),!0}var S=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var n0=S.filter((x)=>x!=="network:read"&&x!=="network:write");class D extends Error{oauthCode;constructor(x,w=null){super(x);this.oauthCode=w;this.name="LoginError"}}function s0(){let x=j(48).toString("base64url"),w=s("sha256").update(x).digest("base64url");return{verifier:x,challenge:w,state:j(32).toString("base64url")}}function r(x,w){let H=typeof x.error==="string"?x.error:null,G=typeof x.error_description==="string"?x.error_description:H?H:w;return new D(G,H)}async function e(x,w,H,G){let J=await H(`${x}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:w,signal:G}),Q=await J.json().catch(()=>({}));if(!J.ok)throw r(Q,`OAuth token request failed (${J.status})`);return Q}var x0=1e4;async function w0(x,w={}){let H=w.fetchImpl??fetch,G=await e(x.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:x.clientId,refresh_token:x.refreshToken}),H,AbortSignal.timeout(x0)).catch((Q)=>{if(Q instanceof Error&&Q.name==="TimeoutError")throw new D("Reason did not answer the login refresh in time. Check the network and retry.");throw Q});if(typeof G.access_token!=="string"||typeof G.refresh_token!=="string"||typeof G.expires_in!=="number")throw new D("Reason returned an incomplete refreshed login.");let J={...x,accessToken:G.access_token,refreshToken:G.refresh_token,expiresAt:new Date(Date.now()+G.expires_in*1000).toISOString(),scopes:typeof G.scope==="string"?G.scope.split(/\s+/).filter(Boolean):x.scopes};return A(J,w.path??B()),J}var z=new Map;function k(x,w){if(!w)return x;if(w.aborted)return Promise.reject(w.reason);return new Promise((H,G)=>{let J=()=>G(w.reason);w.addEventListener("abort",J,{once:!0}),x.then(H,G).finally(()=>w.removeEventListener("abort",J))})}async function P(x={}){let w=x.path??B(),H=M(w);if(!H)return null;let G=x.apiOrigin??v(process.env,"REASON_API_URL")?.trim();if(G&&!y(H.apiOrigin,new URL(G).origin))return null;let J=Date.parse(H.expiresAt)<=Date.now()+60000;if(!x.forceRefresh&&!J)return H;let Q=[w,H.apiOrigin,H.clientId,H.refreshToken].join("\x00"),V=z.get(Q);if(V)return k(V,x.signal);let Z;return Z=w0(H,{fetchImpl:x.fetchImpl,path:w}).catch(async(Y)=>{if(!(Y instanceof D)||Y.oauthCode!=="invalid_grant"&&Y.oauthCode!=="invalid_client")throw Y;let N=M(w),u=Y.oauthCode==="invalid_client"?N?.clientId!==H.clientId:N?.refreshToken!==H.refreshToken;if(N&&u)return P({fetchImpl:x.fetchImpl,path:w});return R(w),null}).finally(()=>{if(z.get(Q)===Z)z.delete(Q)}),z.set(Q,Z),k(Z,x.signal)}function o0(x,w){return new Promise((H)=>{let G=o({input:x}),J=!1,Q=(Z)=>{if(J)return;J=!0,w.removeEventListener("abort",V),G.close(),x.pause(),H(Z)},V=()=>Q(null);w.addEventListener("abort",V,{once:!0}),G.once("line",(Z)=>Q(Z)),G.once("close",()=>Q(null))})}var $0=$.object({label:$.string(),used_percent:$.number().min(0).max(100).nullable(),resets_at:$.string().nullable(),exhausted:$.boolean().nullable()}),H0=$.object({groups:$.array($.object({selectable:$.boolean().optional(),accounts:$.array($.object({source_id:$.string().min(1),model_ids:$.array($.string().min(1)).optional()}))}))});function G0(x){let w=H0.safeParse(x);if(!w.success)return;return w.data.groups.some((H)=>H.selectable!==!1&&H.accounts.some((G)=>G.model_ids===void 0||G.model_ids.length>0))}class X extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor(x,w,H,G,J,Q){super(H);this.status=x;this.code=w;this.suggestedModel=G;this.retryAfterMs=J;this.resolutionReason=Q;this.name="ApiError"}static rateLimitDelayMs(x,w){if(!(x instanceof X)||x.status!==429)return null;return Math.min(60000,Math.max(w,x.retryAfterMs??0))}}var J0=["minimal","low","medium","high","xhigh","max"],Q0=$.object({id:$.string().min(1),kind:$.string(),name:$.string(),custom_name:$.string().nullish(),status:$.string(),online:$.boolean(),compatible:$.boolean().optional(),compatibility_reason:$.string().nullish(),folder_lane_of:$.string().nullish(),roots:$.array($.object({id:$.string().min(1),label:$.string()}))}),W0=$.object({devices:$.array(Q0),end_cursor:$.string().nullish(),has_next_page:$.boolean().optional()}),Z0=$.object({id:$.string().min(1),name:$.string()}),V0=$.object({items:$.array(Z0)}),X0=$.object({id:$.string().min(1),name:$.string(),main:$.boolean(),mine:$.boolean(),session_id:$.string().nullish(),appearance:$.object({color:$.string().nullish()}).nullish().catch(null)}),Y0=$.object({items:$.array(X0)}),B0=$.object({skill_id:$.string().min(1),name:$.string(),description:$.string().nullish(),activation_keywords:$.array($.string()).default([]),is_enabled:$.boolean().default(!0)}),D0=$.object({items:$.array(B0).default([])}),z0=$.object({id:$.string().min(1),kind:$.string(),enabled:$.boolean(),schedule:$.object({expression:$.string().nullish(),every_seconds:$.number().nullish(),next_run_at:$.string().nullish()}).nullish(),github:$.object({event:$.string().nullish(),action:$.string().nullish(),repo:$.string().nullish()}).nullish(),last_fired_at:$.string().nullish()}),I=$.object({id:$.string().min(1),name:$.string().nullish(),instructions:$.string().nullish(),enabled:$.boolean(),triggers:$.array(z0).default([])}),N0=$.object({items:$.array(I).default([]),end_cursor:$.string().nullish(),has_next_page:$.boolean().optional()}),K0=$.object({id:$.string().min(1),slug:$.string().nullish(),name:$.string(),description:$.string().nullish(),transport:$.string().nullish(),url:$.string().nullish(),enabled:$.boolean()}),M0=$.object({items:$.array(K0).default([])}),P0=$.object({status:$.string(),summary:$.string().nullish(),category:$.string().nullish(),outcome:$.string().nullish(),message_count:$.number().nullish(),pr_url:$.string().nullish(),cost_usd:$.number().nullish(),generated_at:$.string().nullish()}),E=$.object({tags:$.array($.string()).default([])}),_0=$.enum(["linux","macos"]),h=$.object({id:$.string().min(1),name:$.string().min(1),platform:_0.nullable(),workers:$.object({total:$.number().int(),online:$.number().int(),busy:$.number().int(),idle:$.number().int()}),sessions:$.object({queued:$.number().int(),running:$.number().int()})}),F0=$.object({machines:$.array(h)}),U0=$.object({machine:h}),T0=$.object({deleted:$.literal(!0),revoked_workers:$.number().int(),revoked_tokens:$.number().int()}),q0=$.object({token:$.object({id:$.string().min(1),machine_id:$.string().min(1),token_prefix:$.string()}),secret:$.string().startsWith("rmt_")}),g=$.looseObject({machine_id:$.string().min(1),machine_name:$.string().min(1)}),C0=g.extend({organization_id:$.string().min(1)}),b0=$.object({id:$.string().min(1),name:$.string().min(1),state:$.enum(["waiting","placed"]),queue_position:$.number().int().nullable()});function H1(x){let w=b0.safeParse(x.machine);return w.success?w.data:null}var O0=$.union([$.object({kind:$.literal("cloud")}),$.object({kind:$.enum(["mac","headless"]),device_id:$.string().min(1),root_id:$.string().min(1)})]);function G1(x){let w=O0.safeParse(x.runs_on);return w.success?w.data:null}function W(x,w,H){let G=x.safeParse(w);if(!G.success)throw new X(502,H,"Reason returned an unexpected response.");return G.data}var L0=$.object({error:$.object({type:$.string(),message:$.string()})});function m(x,w,H){let G=L0.safeParse(w),J=typeof w.error==="string"?w.error:G.success?G.data.error.type:`http_${x}`,Q=typeof w.detail==="string"?w.detail:typeof w.message==="string"?w.message:G.success?G.data.error.message:`Reason request failed (${x}${typeof w.error==="string"?` ${w.error}`:""})`,V=J==="github_connection_required"&&typeof w.connect_url==="string"&&/^https?:\/\//.test(w.connect_url)?` Connect it at ${w.connect_url}`:"",Z=H===null||H.trim()===""?NaN:Number(H);return new X(x,J,`${Q}${V}`,typeof w.suggested_model==="string"?w.suggested_model:void 0,Number.isFinite(Z)&&Z>=0?Z*1000:void 0,typeof w.resolution_reason==="string"?w.resolution_reason:void 0)}async function J1(x){let w=await(x.fetchImpl??fetch)(`${x.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${x.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(x.body),signal:AbortSignal.timeout(30000),redirect:"error"}),H=await w.json().catch(()=>({}));if(!w.ok)throw m(w.status,H,w.headers.get("retry-after"));return W(C0,H,"invalid_machine_ticket")}class A0{options;credentials;constructor(x,w={}){this.options=w;this.credentials=x}trackEvent(x,w={}){}async request(x,w={},H=!1){let G=this.options.fetchImpl??fetch,J=await G(`${this.credentials.apiOrigin}/v3${x}`,{method:w.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":"reason-cli","x-reason-agent":"Reason CLI",...w.raw?{"content-type":w.raw.contentType}:w.body===void 0?{}:{"content-type":"application/json"},...w.headers},body:w.raw?w.raw.bytes:w.body===void 0?void 0:JSON.stringify(w.body),signal:w.signal,redirect:"error"}),Q=await J.json().catch(()=>({}));if(J.status===401&&!H&&w.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let V=await P({fetchImpl:G,path:this.options.credentialsPath,forceRefresh:!0,signal:w.signal});if(V)return this.credentials=V,this.request(x,w,!0)}if(!J.ok)throw m(J.status,Q,J.headers.get("retry-after"));return Q}createHeadlessDeviceEnrollmentTicket(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:x,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(x){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:x,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(w){if(w instanceof X&&(w.status===404||w.status===405||w.status===403&&w.code==="endpoint_not_available"))return null;throw w}}addDeviceRoot(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(x)}/roots`,{method:"POST",body:w,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(x)}/roots/${encodeURIComponent(w)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(x,w=""){let H=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return x===void 0?H:`${H}/${encodeURIComponent(x)}${w}`}async listMachines(){return W(F0,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(x){let w=await this.request(this.machinePath(),{method:"POST",body:{name:x.name,...x.platform?{platform:x.platform}:{}}});return W(U0,w,"invalid_machine").machine}async deleteMachine(x){let w=await this.request(this.machinePath(x),{method:"DELETE"});return W(T0,w,"invalid_machine_deletion")}async createMachineToken(x){let w=await this.request(this.machinePath(x,"/tokens"),{method:"POST",body:{}});return W(q0,w,"invalid_machine_token")}async createMachineEnrollmentTicket(x,w){let H=await this.request(this.machinePath(x,"/enrollment-tickets"),{method:"POST",body:w,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return W(g,H,"invalid_machine_ticket")}self(x){return this.request("/self",{signal:x})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:x,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:x,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(x,w){let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:x,signal:w});return W(f,H,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(x)}`,{method:"POST",body:w,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(x){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:{messages:x},signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((w)=>typeof w.email==="string"?[{email:w.email,role:typeof w.role==="string"?w.role:"member"}]:[])}claimExistingCliPairing(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:x}})}connectAnthropicProvider(x,w,H={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:H.retryUnauthorized,signal:H.signal,body:{access_token:x.access,refresh_token:x.refresh,expires_at:new Date(x.expires).toISOString(),...w?{account_key:w}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((w)=>{let H=typeof w.full_name==="string"?w.full_name:typeof w.repo_full_name==="string"?w.repo_full_name:null;if(!H)return[];return[{repo_id:typeof w.repo_id==="string"?w.repo_id:void 0,full_name:H,provider:w.provider==="gitlab"?"gitlab":"github",default_branch:typeof w.default_branch==="string"?w.default_branch:null,private:typeof w.private==="boolean"?w.private:void 0}]})}async listProjects(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),w=V0.safeParse(x);if(!w.success)throw new X(502,"invalid_project_list","Reason returned an unexpected project list.");return w.data.items}async listReasons(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return W(Y0,x,"invalid_reason_list").items}async openReasonConversation(x){let w=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(x)}/conversation`,{method:"POST"});return W($.object({session_id:$.string().min(1)}),w,"invalid_reason_conversation").session_id}async listSkills(){try{let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return W(D0,x,"invalid_skill_list").items}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return[];throw x}}async listDevices(){let x=[],w=null;for(let H=0;H<50;H+=1){let G=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${w?`?after=${encodeURIComponent(w)}`:""}`),J=W0.safeParse(G);if(!J.success)throw new X(502,"invalid_device_list","Reason returned an unexpected machine list.");if(x.push(...J.data.devices),w=J.data.has_next_page?J.data.end_cursor??null:null,!w)break}return x}async listModels(){try{let w=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((J)=>J.hidden!==!0),H=w.filter((J)=>J.available!==!1).map(({reasoning_efforts:J,hidden:Q,available:V,...Z})=>({...Z,...Array.isArray(J)?{reasoning_efforts:J0.filter((Y)=>J.includes(Y))}:{}})),G=new Set(H.map((J)=>J.detail));return{models:H.length>1&&G.size===1?H.map(({detail:J,...Q})=>Q):H,runnable:H.length>0||w.length===0}}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return{models:[],runnable:!0};throw x}}async getAgentVersion(x){try{let w=await this.request("/deployment",{signal:x,retryUnauthorized:!1});return _(w.reason_version)?w.reason_version:null}catch{return null}}async getUsageQuota(){try{let x=$0.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!x.success)return null;let w;try{w=G0(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...x.data,own_inference:w}}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return null;throw x}}async listSessions(x=50,w,H={}){let G=new URLSearchParams({first:String(Math.min(Math.max(x,1),200)),status:H.status??"active"});if(w)G.set("project_id",w);if(H.origin)G.set("origin",H.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${G.toString()}`)).items??[]}getSession(x,w){let H=w?.fields.length?`?fields=${encodeURIComponent(w.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}${H}`)}async prestartSession(x){let w=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:x}});return w?.status==="starting"||w?.status==="ready"}async createSession(x){let w=x.mode==="ephemeral"||x.workspaceOwnership==="externally-managed";if(x.attachments?.length)await this.requireSessionAttachments();if(w||x.runtimeProfile){let J=await this.request("/deployment");if(w&&(!Array.isArray(J.session_modes)||!J.session_modes.includes(x.mode??"standard")||!Array.isArray(J.workspace_ownerships)||!J.workspace_ownerships.includes(x.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(x.runtimeProfile&&(!Array.isArray(J.experimental_runtime_profiles)||!J.experimental_runtime_profiles.includes(x.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:x.prompt,...x.attachments?.length?{attachments:x.attachments}:{},...x.mode?{mode:x.mode}:{},...x.workspaceOwnership?{workspace_ownership:x.workspaceOwnership}:{},...x.target?{target:x.target}:{},...x.repo?{repo:x.repo}:{},...x.provider?{provider:x.provider}:{},...x.model?{model:x.model}:{},...x.reasoningEffort?{reasoning_effort:x.reasoningEffort}:{},...x.runtimeProfile?{experimental_runtime_profile:x.runtimeProfile}:{},...x.ref?{ref:x.ref}:{},...x.branch?{branch:x.branch}:{},...x.completionMode?{completion_mode:x.completionMode}:{},...x.env&&Object.keys(x.env).length>0?{env:x.env}:{},...x.clientSessionId?{client_session_id:x.clientSessionId}:{},...x.longRunning?{long_running:{enabled:!0}}:{},...x.spendLimitRcu?{spend_limit_rcu:x.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),G=await this.getSession(H.session_id);if(w){let J=G.session_policy,Q=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!J||J.version!==1||J.mode!==(x.mode??"standard")||J.workspaceOwnership!==(x.workspaceOwnership??"managed")||!J.components||Q.some((V)=>J.components[V]!==!0))throw await this.cancelSession(H.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(x.runtimeProfile&&G.experimental_runtime_profile!==x.runtimeProfile)throw await this.cancelSession(H.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return G}async getEvents(x,w=-1,H={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/events?after_seq=${w}&limit=500${H.waitMs?`&wait_ms=${H.waitMs}`:""}`,H.signal?{signal:H.signal}:{})}catch(G){if(!(G instanceof X)||G.status!==403&&G.status!==404)throw G;return{session:await this.getSession(x),items:[],next_seq:w}}}async getMessages(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages?first=500${w===void 0?"":`&after_seq=${w}`}`)}async getAttachments(x,w){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/attachments${w?`?view=${w}`:""}`)).items??[]}catch(H){if(H instanceof X&&(H.status===403||H.status===404))return[];throw H}}async requireSessionAttachments(){let x=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(x.session_attachments!==!0){let w=typeof x.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(x.reason_version)?`Agent ${x.reason_version}`:null,H=typeof x.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(x.commit_sha)?`server ${x.commit_sha.slice(0,12)}`:null,G=[w,H].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${G?` (${G})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(x,w,H={}){if(H.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages`,{method:"POST",body:{message:w,...H.attachments?.length?{attachments:H.attachments}:{},...H.model?{model:H.model}:{},...H.reasoningEffort?{reasoning_effort:H.reasoningEffort}:{},...H.target?{target:H.target}:{},...H.delivery?{delivery:H.delivery}:{}}})}async steerQueuedMessage(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages/${encodeURIComponent(w)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages/${encodeURIComponent(w)}/queued`,{method:"DELETE"})}async getConversation(x){let w=[],H=null;for(let G=0;G<50;G+=1){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/conversation${H?`?after=${encodeURIComponent(H)}`:""}`);if(w.push(...J.items??[]),!J.has_next_page||!J.end_cursor)break;H=J.end_cursor}return w}createSharedLink(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/shared-links`,{method:"POST",body:{url:w.url,...w.label?{label:w.label}:{},...w.expiresInSeconds!==void 0?{expires_in_seconds:w.expiresInSeconds}:{}}})}sessionAction(x,w,H={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/${w}`,{method:"POST",body:H})}renameSession(x,w){return this.sessionAction(x,"rename",{title:w||null})}moveSessionToProject(x,w){return this.sessionAction(x,"project",{project_id:w})}compactSession(x){return this.sessionAction(x,"compact")}retrySession(x){return this.sessionAction(x,"retry")}rewindSession(x,w){return this.sessionAction(x,"rewind",{message_id:w.messageId,content:w.content,request_id:w.requestId})}forkSession(x,w){return this.sessionAction(x,"fork",{...w.message?{message:w.message}:{},client_session_id:w.clientSessionId})}cancelSession(x,w={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/cancel`,{method:"POST",body:w.mode==="hard"?{mode:"hard"}:{}})}sessionPath(x,w=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}${w}`}async archiveSession(x){await this.request(this.sessionPath(x,"/archive"),{method:"POST",body:{}})}async unarchiveSession(x){await this.request(this.sessionPath(x,"/unarchive"),{method:"POST",body:{}})}async deleteSession(x){await this.request(this.sessionPath(x),{method:"DELETE"})}async listSessionTags(x){return W(E,await this.request(this.sessionPath(x,"/tags")),"invalid_session_tags").tags}async appendSessionTags(x,w){let H=await this.request(this.sessionPath(x,"/tags"),{method:"POST",body:{tags:w}});return W(E,H,"invalid_session_tags").tags}async sessionInsight(x,w=!1){let H=await this.request(this.sessionPath(x,w?"/insights/generate":"/insights"),w?{method:"POST",body:{}}:{});return W(P0,H,"invalid_session_insight")}async listAutomations(){let x=[],w=null;for(let H=0;H<20;H+=1){let G=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${w?`&after=${encodeURIComponent(w)}`:""}`),J=W(N0,G,"invalid_automation_list");if(x.push(...J.items),w=J.has_next_page?J.end_cursor??null:null,!w)break}return x}async createScheduledAutomation(x,w){let H=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,G=W(I,await this.request(H,{method:"POST",body:{name:x.name,instructions:x.instructions,...x.repo?{repo:x.repo.full_name,provider:x.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${H}/${encodeURIComponent(G.id)}/triggers`,{method:"POST",body:w})}catch(J){throw await this.deleteAutomation(G.id).catch(()=>{return}),J}return G}async setAutomationEnabled(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(x)}`,{method:"PATCH",body:{enabled:w}})}async deleteAutomation(x){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(x)}`,{method:"DELETE"})}async transcribe(x,w){let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:x,contentType:w}});return W($.object({transcript:$.string()}),H,"invalid_transcript").transcript}async listMcpServers(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return W(M0,x,"invalid_mcp_server_list").items}async setSkillEnabled(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(x)}`,{method:"PUT",body:{is_enabled:w}})}}
5
5
  export{B as A,M as B,s0 as C,P as D,o0 as E,X as F,J0 as G,H1 as H,G1 as I,J1 as J,A0 as K};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{ki as j}from"./vm-hands-entry-lite-6z2g0td2.js";var q=25,K=j.object({machine:j.string().min(1).max(200),person:j.string().min(1).max(200),team:j.string().min(1).max(200),version:j.string().max(64).optional(),wait_seconds:j.number().int().min(0).max(q).optional()}),v=j.discriminatedUnion("kind",[j.object({id:j.string(),kind:j.literal("who")}),j.object({id:j.string(),kind:j.literal("send"),to:j.string(),body:j.string(),from_name:j.string(),from_agent:j.string(),wake:j.boolean()})]),P=j.object({job:v.nullable(),retry_after_seconds:j.number().optional()}),x=j.object({address:j.string(),person:j.string(),machine:j.string(),agent:j.string(),repo:j.string().nullable(),branch:j.string().nullable(),status:j.string(),since:j.number().nullable(),doing:j.string().nullable(),worker:j.boolean()}),B=j.object({person:j.string(),machine:j.string(),online:j.boolean()}),F=j.object({team:j.string().nullable(),sessions:j.array(x).max(2000),machines:j.array(B).max(500)}),Q=j.union([j.object({who:F}),j.object({sent:j.object({ids:j.array(j.string().max(100)).max(500),recipients:j.array(j.string().max(300)).max(500),from:j.string().max(300)})}),j.object({error:j.string().min(1).max(2000)})]),G=j.object({id:j.string().max(100),from:j.string().max(300),from_agent:j.string().max(100).nullable(),to:j.string().max(300),reply_to:j.string().max(100).nullable(),body:j.string().max(64000),sent_at:j.number()}),U=j.object({messages:j.array(G).max(100)});
2
+ import{mi as j}from"./vm-hands-entry-lite-2xh7sjs0.js";var q=25,K=j.object({machine:j.string().min(1).max(200),person:j.string().min(1).max(200),team:j.string().min(1).max(200),version:j.string().max(64).optional(),wait_seconds:j.number().int().min(0).max(q).optional()}),v=j.discriminatedUnion("kind",[j.object({id:j.string(),kind:j.literal("who")}),j.object({id:j.string(),kind:j.literal("send"),to:j.string(),body:j.string(),from_name:j.string(),from_agent:j.string(),wake:j.boolean()})]),P=j.object({job:v.nullable(),retry_after_seconds:j.number().optional()}),x=j.object({address:j.string(),person:j.string(),machine:j.string(),agent:j.string(),repo:j.string().nullable(),branch:j.string().nullable(),status:j.string(),since:j.number().nullable(),doing:j.string().nullable(),worker:j.boolean()}),B=j.object({person:j.string(),machine:j.string(),online:j.boolean()}),F=j.object({team:j.string().nullable(),sessions:j.array(x).max(2000),machines:j.array(B).max(500)}),Q=j.union([j.object({who:F}),j.object({sent:j.object({ids:j.array(j.string().max(100)).max(500),recipients:j.array(j.string().max(300)).max(500),from:j.string().max(300)})}),j.object({error:j.string().min(1).max(2000)})]),G=j.object({id:j.string().max(100),from:j.string().max(300),from_agent:j.string().max(100).nullable(),to:j.string().max(300),reply_to:j.string().max(100).nullable(),body:j.string().max(64000),sent_at:j.number()}),U=j.object({messages:j.array(G).max(100)});
3
3
  export{q as L,P as M};