@reason-machines/cli-linux-arm64-musl 0.2.336 → 0.2.338

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-cb63vj4j.js +2 -0
  3. package/bin/vm-hands/api-credentials-r3gava82.js +2 -0
  4. package/bin/vm-hands/{ask-relay-62f753v8.js → ask-relay-ak0qxs4j.js} +2 -2
  5. package/bin/vm-hands/connect-cli-7h9nkgqd.js +2 -0
  6. package/bin/vm-hands/custom-endpoint-device-zhkesj7w.js +2 -0
  7. package/bin/vm-hands/desktop-account-a0tc6tgz.js +2 -0
  8. package/bin/vm-hands/{device-workspace-nqxczwd3.js → device-workspace-kmdera1y.js} +1 -1
  9. package/bin/vm-hands/{hands-worker-source-tc1snvve.js → hands-worker-source-gffxw6cf.js} +1 -1
  10. package/bin/vm-hands/{index-g4t2q0ep.js → index-n922jg9n.js} +1 -1
  11. package/bin/vm-hands/local-automation-bqazvms0.js +2 -0
  12. package/bin/vm-hands/local-capabilities-4v5p6yp3.js +2 -0
  13. package/bin/vm-hands/local-desktop-users-xwcgrstv.js +2 -0
  14. package/bin/vm-hands/local-display-mac-6hn25df7.js +2 -0
  15. package/bin/vm-hands/local-display-session-9bb5x27r.js +2 -0
  16. package/bin/vm-hands/local-pty-session-2r99e4z9.js +2 -0
  17. package/bin/vm-hands/network-contract-cg7j1pz9.js +2 -0
  18. package/bin/vm-hands/package-65d4a80w.js +2 -0
  19. package/bin/vm-hands/permissions-snk9a206.js +2 -0
  20. package/bin/vm-hands/{reason-hands-protocol-n14gyf7k.js → reason-hands-protocol-08mbrn5k.js} +1 -1
  21. package/bin/vm-hands/{status-9y1eqg06.js → status-1ahcrm8s.js} +2 -2
  22. package/bin/vm-hands/version-4cwn2qqp.js +2 -0
  23. package/bin/vm-hands/{vm-hands-entry-lite-ghav09mm.js → vm-hands-entry-lite-08tz9p24.js} +2 -2
  24. package/bin/vm-hands/{vm-hands-entry-lite-s64raarx.js → vm-hands-entry-lite-0nb9zkz1.js} +2 -2
  25. package/bin/vm-hands/{vm-hands-entry-lite-dtcpbbkc.js → vm-hands-entry-lite-4b8ypyym.js} +1 -1
  26. package/bin/vm-hands/{vm-hands-entry-lite-t36vzcw7.js → vm-hands-entry-lite-4ge4ez6h.js} +2 -2
  27. package/bin/vm-hands/{vm-hands-entry-lite-9enw55fp.js → vm-hands-entry-lite-622rzyfg.js} +2 -2
  28. package/bin/vm-hands/{vm-hands-entry-lite-5n6vc7je.js → vm-hands-entry-lite-6cj7s7rc.js} +1 -1
  29. package/bin/vm-hands/{vm-hands-entry-lite-9k57wmkv.js → vm-hands-entry-lite-723q0mmr.js} +5 -5
  30. package/bin/vm-hands/{vm-hands-entry-lite-px64jhhn.js → vm-hands-entry-lite-9n6m4qgf.js} +1 -1
  31. package/bin/vm-hands/{vm-hands-entry-lite-cnmd8nft.js → vm-hands-entry-lite-bbezym6j.js} +2 -2
  32. package/bin/vm-hands/{vm-hands-entry-lite-983czfdb.js → vm-hands-entry-lite-cag8nazq.js} +2 -2
  33. package/bin/vm-hands/{vm-hands-entry-lite-dhzcvvt2.js → vm-hands-entry-lite-d17bx1yc.js} +2 -2
  34. package/bin/vm-hands/{vm-hands-entry-lite-jzms4xs2.js → vm-hands-entry-lite-dnx92ytp.js} +2 -2
  35. package/bin/vm-hands/{vm-hands-entry-lite-4fcs46fz.js → vm-hands-entry-lite-efvwgjhe.js} +2 -2
  36. package/bin/vm-hands/{vm-hands-entry-lite-yr493k0q.js → vm-hands-entry-lite-f2bcqmvr.js} +75 -75
  37. package/bin/vm-hands/{vm-hands-entry-lite-3dx1yqhd.js → vm-hands-entry-lite-gbekj59z.js} +1 -1
  38. package/bin/vm-hands/{vm-hands-entry-lite-thtd61xk.js → vm-hands-entry-lite-h9jdthmf.js} +1 -1
  39. package/bin/vm-hands/{vm-hands-entry-lite-zgs6j8wj.js → vm-hands-entry-lite-hh0002ye.js} +1 -1
  40. package/bin/vm-hands/{vm-hands-entry-lite-fpb440k0.js → vm-hands-entry-lite-hj1gnypx.js} +2 -2
  41. package/bin/vm-hands/{vm-hands-entry-lite-feaxcj0x.js → vm-hands-entry-lite-k9sm5kaf.js} +1 -1
  42. package/bin/vm-hands/{vm-hands-entry-lite-awwev9zg.js → vm-hands-entry-lite-kf5eeggb.js} +2 -2
  43. package/bin/vm-hands/{vm-hands-entry-lite-n0j2t2eb.js → vm-hands-entry-lite-me8b4f14.js} +2 -2
  44. package/bin/vm-hands/{vm-hands-entry-lite-mm72ht4e.js → vm-hands-entry-lite-png3h0cm.js} +1 -1
  45. package/bin/vm-hands/{vm-hands-entry-lite-hj6jjk24.js → vm-hands-entry-lite-pqama7tv.js} +1 -1
  46. package/bin/vm-hands/{vm-hands-entry-lite-k3cq8g9w.js → vm-hands-entry-lite-rasqv4xz.js} +3 -3
  47. package/bin/vm-hands/{vm-hands-entry-lite-c64behya.js → vm-hands-entry-lite-rhpmp59p.js} +1 -1
  48. package/bin/vm-hands/{vm-hands-entry-lite-mtp2h66e.js → vm-hands-entry-lite-samn6qm5.js} +2 -2
  49. package/bin/vm-hands/{vm-hands-entry-lite-7kzy7rxj.js → vm-hands-entry-lite-t2q10vjr.js} +1 -1
  50. package/bin/vm-hands/{vm-hands-entry-lite-4b8f37q4.js → vm-hands-entry-lite-w2yb86jm.js} +2 -2
  51. package/bin/vm-hands/{vm-hands-entry-lite-070nd0vy.js → vm-hands-entry-lite-y4nntb2w.js} +1 -1
  52. package/bin/vm-hands/{vm-hands-entry-lite-9rr6gh58.js → vm-hands-entry-lite-ytmcecfr.js} +1 -1
  53. package/bin/vm-hands/{vm-hands-entry-lite-tf5mepq5.js → vm-hands-entry-lite-z59ar4qz.js} +2 -2
  54. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  55. package/bin/vm-hands/{vm-hands-executor-bk5c02sn.js → vm-hands-executor-wz80d281.js} +1 -1
  56. package/bin/vm-hands/vm-hands-op-runner-430cgtn6.js +2 -0
  57. package/bin/vm-hands/{vm-hands-runtime-8eq6jwht.js → vm-hands-runtime-4tb05b3m.js} +3 -3
  58. package/bin/vm-hands/worker-sandbox-g70ryvcd.js +2 -0
  59. package/package.json +1 -1
  60. package/bin/vm-hands/api-36ywgdp3.js +0 -2
  61. package/bin/vm-hands/api-credentials-41xjt55r.js +0 -2
  62. package/bin/vm-hands/connect-cli-1defgnfc.js +0 -2
  63. package/bin/vm-hands/custom-endpoint-device-dt74zv7m.js +0 -2
  64. package/bin/vm-hands/desktop-account-a16gh9sj.js +0 -2
  65. package/bin/vm-hands/local-automation-h75bcz8g.js +0 -2
  66. package/bin/vm-hands/local-capabilities-95a5rydg.js +0 -2
  67. package/bin/vm-hands/local-desktop-users-qej2mfhx.js +0 -2
  68. package/bin/vm-hands/local-display-mac-4pddah9q.js +0 -2
  69. package/bin/vm-hands/local-display-session-fpdqc03v.js +0 -2
  70. package/bin/vm-hands/local-pty-session-kq8bd4pm.js +0 -2
  71. package/bin/vm-hands/network-contract-qxn4pg15.js +0 -2
  72. package/bin/vm-hands/package-s8sef5wh.js +0 -2
  73. package/bin/vm-hands/permissions-ecneehn3.js +0 -2
  74. package/bin/vm-hands/version-zrj419tq.js +0 -2
  75. package/bin/vm-hands/vm-hands-op-runner-cxytfman.js +0 -2
  76. package/bin/vm-hands/worker-sandbox-1m0s1vnq.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ed as _J,fe as CJ,wd as UJ}from"./vm-hands-entry-lite-9k57wmkv.js";import{createHash as y,randomBytes as zJ}from"crypto";import{closeSync as LJ,fsyncSync as qJ,mkdirSync as RJ,openSync as NJ,renameSync as fJ,rmSync as mJ,statSync as DJ,writeSync as AJ,constants as V}from"fs";import{join as o}from"path";var bJ=1;var d=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function KJ(J){if(J.environment!==void 0||J.payload.environment!==void 0)throw new W("vm_hands_bind_invalid","bind carries a plaintext environment");if(J.payload.vm_hands_env_deferred===!0&&J.environment_sealed!==void 0)throw new W("vm_hands_bind_invalid","split bind carries an environment");return J.environment_sealed!==void 0}function jJ(J,Z){let{payload:z,authority:K}=J;if(!z||typeof z!=="object"||Array.isArray(z)||!K||typeof K!=="object"||Array.isArray(K)||!Z.deviceId||!Z.rootId||z.run_id!==Z.runId||z.device_id!==Z.deviceId||K.device_id!==Z.deviceId||z.root_id!==Z.rootId||Z.snapshotId!==void 0&&z.snapshot_id!==Z.snapshotId)throw new W("vm_hands_env_invalid","environment does not match this Hands");return z}function xJ(J){if(J.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not a hands.connect claim");let Z=J.payload;return{kind:"vm_hands.bind",v:1,bind_id:J.attempt_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,run_id:J.run_id,session_id:typeof Z.workspace_id==="string"&&d.test(Z.workspace_id)?Z.workspace_id:J.run_id,brain_generation:Z.target_generation,fence_id:Z.target_fence_id,lease_until:J.lease_until,policy:{agent_profile:"",confinement_key:String(Z.hands_confinement??""),browser_egress:Z.browser_egress??null,policy_digest:Z.vm_hands_policy_digest},cwd:typeof Z.cwd==="string"?Z.cwd:"",claim:J,env:KJ(J)?J.environment_sealed:null}}class W extends Error{code;constructor(J,Z){super(Z);this.code=J}}var H=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),I=(J)=>new Uint8Array(Buffer.from(J,"base64url"));function R(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return`[${J.map(R).join(",")}]`;return`{${Object.keys(J).sort().map((Z)=>`${JSON.stringify(Z)}:${R(J[Z])}`).join(",")}}`}async function QZ(J){let Z=await crypto.subtle.importKey("pkcs8",I(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),z=I(J.device_key.spki),K=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),U=new Uint8Array(await crypto.subtle.exportKey("spki",K.publicKey)),L=y("sha256").update(z).digest("base64url");return{signing:{privateKey:Z},agreement:K,signingSpki:z,agreementSpki:U,fingerprint:L}}var cJ=4;class pJ{init;keys;hooks;options;identity="identity_free";lastBrainGeneration=new Map;bound=new Map;binding=new Map;unbinding=new Set;servedRun=!1;verifiedSinceRun=!1;unverified=new Set;structural=Promise.resolve();exclusive(J){let Z=this.structural.then(J,J);return this.structural=Z.catch(()=>{return}),Z}constructor(J,Z,z,K){this.init=J;this.keys=Z;this.hooks=z;this.options=K;if(!d.test(J.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(J.workspace_id))throw new W("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(J.instance_generation)||J.instance_generation<1)throw new W("vm_hands_layout_invalid","bad generation")}get phase(){if(this.identity==="identity_free")return"identity_free";if(this.unbinding.size)return"unbinding";return this.bound.size||this.binding.size?"bound":"registered"}isBoundRun(J){for(let Z of this.bound.values())if(Z.runId===J)return!0;return!1}bindIdForRun(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}async environmentInstalled(J,Z,z){for(let K=Date.now()+Z;;){let U=this.bound.get(J);if(!U)return!1;if(U.envInstalled)return!0;if(Date.now()>=K||z?.aborted)return!1;await new Promise((L)=>setTimeout(L,25))}}canSpawn(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.envInstalled;return!1}async registerFrame(J){if(this.identity!=="identity_free")throw new W("vm_hands_register_twice","already registered");if(typeof J!=="string"||J.length<16||J.length>256)throw new W("vm_hands_challenge_invalid","bad register challenge");let Z={challenge:J,t:"register",v:bJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:H(this.keys.signingSpki),env_public_key:H(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:H(zJ(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},z=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(R(Z)));return{...Z,device_signature:H(z)}}async helloFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","hello before register");let z=String((this.options.now??Date.now)()),K=H(zJ(32)),U=CJ({method:"GET",pathAndQuery:UJ,timestamp:z,nonce:K,challenge:J,bodySha256:y("sha256").update("").digest("hex")}),L=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(U)));return{t:"hello",timestamp:z,nonce:K,signature:H(lJ(L)),...Z?{vm_hands_previous_connection:Z}:{}}}registered(){if(this.identity!=="identity_free")throw new W("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(J){if(this.identity!=="registered")throw new W("vm_hands_not_registered","bind before register");if(J.kind!=="vm_hands.bind"||J.v!==1)throw new W("vm_hands_bind_invalid","bad bind");for(let z of[J.bind_id,J.attempt_id,J.run_id,J.session_id,J.fence_id])if(!d.test(z))throw new W("vm_hands_bind_invalid","bad id");if(!Number.isSafeInteger(J.brain_generation)||J.brain_generation<=(this.lastBrainGeneration.get(J.run_id)??0))throw new W("vm_hands_generation_stale","brain generation not strictly higher");if(J.env&&(J.env.aad!==J.bind_id||J.env.alg!=="ECDH-P256+A256GCM"))throw new W("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(J.policy.policy_digest))throw new W("vm_hands_bind_invalid","bad policy or nonce");if(y("sha256").update(R({hands_confinement:J.policy.confinement_key||null,browser_egress:J.policy.browser_egress??null})).digest("hex")!==J.policy.policy_digest)throw new W("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(J.bind_id)||[...this.bound.values()].some((z)=>z.runId===J.run_id)||[...this.binding.values()].includes(J.run_id))throw new W("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=cJ)throw new W("vm_hands_busy","every bind slot is held");return this.lastBrainGeneration.set(J.run_id,J.brain_generation),this.binding.set(J.bind_id,J.run_id),this.exclusive(()=>this.setUp(J))}async setUp(J){let Z=[...this.bound.keys()],z=null,K=!1;try{if(Z.length===0){if(this.servedRun&&!this.verifiedSinceRun)await this.hooks.killAndVerifyPayload(),this.unverified.clear()}else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({keep:Z}),this.unverified.clear();this.verifiedSinceRun=!1,this.servedRun=!0,K=!0;let{launchId:U,applied:L,readyData:P}=await this.hooks.startExecutor({bindId:J.bind_id,sessionId:J.session_id,policyDigest:J.policy.policy_digest,confinementKey:J.policy.confinement_key,browserEgress:J.policy.browser_egress,cwd:J.cwd,claim:J.claim}),E=this.hooks.restatLayout(),A=null;if(J.env){let O=J.claim?.owner??{},g=jJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof O.device_id==="string"?O.device_id:"",rootId:J.claim?.root_id??""});A=this.hooks.installEnvironment(J.bind_id,g),z=this.writeJobEnvRootOnly(J.bind_id,g)}if(this.unbinding.has(J.bind_id))throw new W("vm_hands_bind_lost","unbound while binding");return this.bound.set(J.bind_id,{bindId:J.bind_id,runId:J.run_id,sessionId:J.session_id,brainGeneration:J.brain_generation,policyDigest:J.policy.policy_digest,launchId:U,envInstalled:A!==null,rootId:J.claim?.root_id??"",envDirectory:z}),this.binding.delete(J.bind_id),{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:U,snapshot_revision:A,layout:E,...P?{ready_data:P}:{},policy_digest:y("sha256").update(R({hands_confinement:L.hands_confinement??null,browser_egress:L.browser_egress??null})).digest("hex")}}catch(U){if(z)GJ(z);if(K){let P=[...this.bound.keys()];await this.hooks.killAndVerifyPayload(P.length?{bindId:J.bind_id,keep:P}:void 0).then(()=>{if(!P.length)this.verifiedSinceRun=!0,this.unverified.clear()},()=>{this.unverified.add(J.bind_id),this.verifiedSinceRun=!1})}this.binding.delete(J.bind_id);let L=U&&typeof U==="object"&&"code"in U&&typeof U.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(U.code)?U.code:"vm_hands_bind_failed";throw U instanceof W?U:new W(L,"executor refused the bind")}}async deliverEnvironment(J){let Z=this.bound.get(J.attemptId);if(!Z||this.unbinding.has(J.attemptId))throw new W("vm_hands_not_bound","environment delivered while not bound");if(!d.test(J.attemptId)||typeof J.snapshotId!=="string"||!J.snapshotId||J.snapshotId.length>128||J.snapshotId.includes("/"))throw new W("vm_hands_env_invalid","bad snapshot id");let z=`${J.attemptId}/${J.snapshotId}`;if(J.sealed?.alg!=="ECDH-P256+A256GCM"||J.sealed.aad!==z)throw new W("vm_hands_env_invalid","bad env envelope");let K=jJ(await this.openSealed(J.sealed,z),{runId:Z.runId,deviceId:J.deviceId,rootId:Z.rootId,snapshotId:J.snapshotId}),U=this.hooks.installEnvironment(Z.bindId,K);if(Z.envInstalled=!0,Z.envDirectory)GJ(Z.envDirectory);return Z.envDirectory=null,Z.envDirectory=this.writeJobEnvRootOnly(`${Z.bindId}-r${U}`,K),{snapshot_id:J.snapshotId,installed_revision:U,installed:!0}}async attestFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","attest before register");if(!J||J.length>65536)throw new W("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new W("vm_hands_attest_invalid","attest beside a bind");let z=await this.hooks.runProbe({nonce:Z,script:J});try{await this.hooks.killProbe()}catch{this.servedRun=!0,this.verifiedSinceRun=!1}return{t:"attest",nonce:Z,exit_code:z.exitCode,markers:z.markers,proof_dir_inode:z.proofDirInode,script_sha256:y("sha256").update(J).digest("hex")}})}executorExited(J){return this.hooks.executorExited?.(J)??new Promise(()=>{})}async boundRefused(J){await this.unbind(J)}async unbind(J){let Z=this.bound.get(J)??null;if(this.unbinding.add(J),this.bound.delete(J),Z)try{this.hooks.freezeBind?.(J)}catch{}return this.exclusive(()=>this.tearDown(J,Z))}async tearDown(J,Z){try{this.bound.delete(J);let z=[...this.bound.keys()].filter((K)=>K!==J);try{await this.hooks.killAndVerifyPayload(z.length?{bindId:J,keep:z}:void 0)}catch(K){throw this.unverified.add(J),this.verifiedSinceRun=!1,K}if(!z.length)this.verifiedSinceRun=!0,this.unverified.clear();if(Z?.envDirectory)GJ(Z.envDirectory);return{bind_id:Z?J:null,killed_verified:!0,shredded:!0,srt_fallbacks:z.length?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(J)}}async openSealed(J,Z){let z=()=>{throw new W("vm_hands_env_invalid","env did not decrypt")},K=await crypto.subtle.importKey("spki",I(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(z),U=await crypto.subtle.deriveKey({name:"ECDH",public:K},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),L=await crypto.subtle.decrypt({name:"AES-GCM",iv:I(J.iv),additionalData:new TextEncoder().encode(Z)},U,I(J.ct)).catch(z),P=JSON.parse(new TextDecoder().decode(L));if(!P||typeof P!=="object"||Array.isArray(P))throw new W("vm_hands_env_invalid","env not an object");return P}writeJobEnvRootOnly(J,Z){let z=o(this.options.envRoot,`bind-${J}`);RJ(z,{mode:448});let K=DJ(z);if(!K.isDirectory()||(K.mode&63)!==0||K.uid!==(process.getuid?.()??-1))throw new W("vm_hands_env_dir_unsafe","env directory is not root's 0700");let U=Z.variables&&typeof Z.variables==="object"?Z.variables:{},L=Object.entries(U).filter(([A,O])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(A)&&typeof O==="string").map(([A,O])=>`export ${A}='${String(O).replaceAll("'","'\\''")}'`).join(`
2
+ import{Gd as _J,ie as CJ,yd as UJ}from"./vm-hands-entry-lite-723q0mmr.js";import{createHash as y,randomBytes as zJ}from"crypto";import{closeSync as LJ,fsyncSync as qJ,mkdirSync as RJ,openSync as NJ,renameSync as fJ,rmSync as mJ,statSync as DJ,writeSync as AJ,constants as V}from"fs";import{join as o}from"path";var bJ=1;var d=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function KJ(J){if(J.environment!==void 0||J.payload.environment!==void 0)throw new W("vm_hands_bind_invalid","bind carries a plaintext environment");if(J.payload.vm_hands_env_deferred===!0&&J.environment_sealed!==void 0)throw new W("vm_hands_bind_invalid","split bind carries an environment");return J.environment_sealed!==void 0}function jJ(J,Z){let{payload:z,authority:K}=J;if(!z||typeof z!=="object"||Array.isArray(z)||!K||typeof K!=="object"||Array.isArray(K)||!Z.deviceId||!Z.rootId||z.run_id!==Z.runId||z.device_id!==Z.deviceId||K.device_id!==Z.deviceId||z.root_id!==Z.rootId||Z.snapshotId!==void 0&&z.snapshot_id!==Z.snapshotId)throw new W("vm_hands_env_invalid","environment does not match this Hands");return z}function xJ(J){if(J.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not a hands.connect claim");let Z=J.payload;return{kind:"vm_hands.bind",v:1,bind_id:J.attempt_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,run_id:J.run_id,session_id:typeof Z.workspace_id==="string"&&d.test(Z.workspace_id)?Z.workspace_id:J.run_id,brain_generation:Z.target_generation,fence_id:Z.target_fence_id,lease_until:J.lease_until,policy:{agent_profile:"",confinement_key:String(Z.hands_confinement??""),browser_egress:Z.browser_egress??null,policy_digest:Z.vm_hands_policy_digest},cwd:typeof Z.cwd==="string"?Z.cwd:"",claim:J,env:KJ(J)?J.environment_sealed:null}}class W extends Error{code;constructor(J,Z){super(Z);this.code=J}}var H=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),I=(J)=>new Uint8Array(Buffer.from(J,"base64url"));function R(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return`[${J.map(R).join(",")}]`;return`{${Object.keys(J).sort().map((Z)=>`${JSON.stringify(Z)}:${R(J[Z])}`).join(",")}}`}async function QZ(J){let Z=await crypto.subtle.importKey("pkcs8",I(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),z=I(J.device_key.spki),K=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),U=new Uint8Array(await crypto.subtle.exportKey("spki",K.publicKey)),L=y("sha256").update(z).digest("base64url");return{signing:{privateKey:Z},agreement:K,signingSpki:z,agreementSpki:U,fingerprint:L}}var cJ=4;class pJ{init;keys;hooks;options;identity="identity_free";lastBrainGeneration=new Map;bound=new Map;binding=new Map;unbinding=new Set;servedRun=!1;verifiedSinceRun=!1;unverified=new Set;structural=Promise.resolve();exclusive(J){let Z=this.structural.then(J,J);return this.structural=Z.catch(()=>{return}),Z}constructor(J,Z,z,K){this.init=J;this.keys=Z;this.hooks=z;this.options=K;if(!d.test(J.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(J.workspace_id))throw new W("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(J.instance_generation)||J.instance_generation<1)throw new W("vm_hands_layout_invalid","bad generation")}get phase(){if(this.identity==="identity_free")return"identity_free";if(this.unbinding.size)return"unbinding";return this.bound.size||this.binding.size?"bound":"registered"}isBoundRun(J){for(let Z of this.bound.values())if(Z.runId===J)return!0;return!1}bindIdForRun(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}async environmentInstalled(J,Z,z){for(let K=Date.now()+Z;;){let U=this.bound.get(J);if(!U)return!1;if(U.envInstalled)return!0;if(Date.now()>=K||z?.aborted)return!1;await new Promise((L)=>setTimeout(L,25))}}canSpawn(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.envInstalled;return!1}async registerFrame(J){if(this.identity!=="identity_free")throw new W("vm_hands_register_twice","already registered");if(typeof J!=="string"||J.length<16||J.length>256)throw new W("vm_hands_challenge_invalid","bad register challenge");let Z={challenge:J,t:"register",v:bJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:H(this.keys.signingSpki),env_public_key:H(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:H(zJ(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},z=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(R(Z)));return{...Z,device_signature:H(z)}}async helloFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","hello before register");let z=String((this.options.now??Date.now)()),K=H(zJ(32)),U=CJ({method:"GET",pathAndQuery:UJ,timestamp:z,nonce:K,challenge:J,bodySha256:y("sha256").update("").digest("hex")}),L=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(U)));return{t:"hello",timestamp:z,nonce:K,signature:H(lJ(L)),...Z?{vm_hands_previous_connection:Z}:{}}}registered(){if(this.identity!=="identity_free")throw new W("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(J){if(this.identity!=="registered")throw new W("vm_hands_not_registered","bind before register");if(J.kind!=="vm_hands.bind"||J.v!==1)throw new W("vm_hands_bind_invalid","bad bind");for(let z of[J.bind_id,J.attempt_id,J.run_id,J.session_id,J.fence_id])if(!d.test(z))throw new W("vm_hands_bind_invalid","bad id");if(!Number.isSafeInteger(J.brain_generation)||J.brain_generation<=(this.lastBrainGeneration.get(J.run_id)??0))throw new W("vm_hands_generation_stale","brain generation not strictly higher");if(J.env&&(J.env.aad!==J.bind_id||J.env.alg!=="ECDH-P256+A256GCM"))throw new W("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(J.policy.policy_digest))throw new W("vm_hands_bind_invalid","bad policy or nonce");if(y("sha256").update(R({hands_confinement:J.policy.confinement_key||null,browser_egress:J.policy.browser_egress??null})).digest("hex")!==J.policy.policy_digest)throw new W("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(J.bind_id)||[...this.bound.values()].some((z)=>z.runId===J.run_id)||[...this.binding.values()].includes(J.run_id))throw new W("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=cJ)throw new W("vm_hands_busy","every bind slot is held");return this.lastBrainGeneration.set(J.run_id,J.brain_generation),this.binding.set(J.bind_id,J.run_id),this.exclusive(()=>this.setUp(J))}async setUp(J){let Z=[...this.bound.keys()],z=null,K=!1;try{if(Z.length===0){if(this.servedRun&&!this.verifiedSinceRun)await this.hooks.killAndVerifyPayload(),this.unverified.clear()}else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({keep:Z}),this.unverified.clear();this.verifiedSinceRun=!1,this.servedRun=!0,K=!0;let{launchId:U,applied:L,readyData:P}=await this.hooks.startExecutor({bindId:J.bind_id,sessionId:J.session_id,policyDigest:J.policy.policy_digest,confinementKey:J.policy.confinement_key,browserEgress:J.policy.browser_egress,cwd:J.cwd,claim:J.claim}),E=this.hooks.restatLayout(),A=null;if(J.env){let O=J.claim?.owner??{},g=jJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof O.device_id==="string"?O.device_id:"",rootId:J.claim?.root_id??""});A=this.hooks.installEnvironment(J.bind_id,g),z=this.writeJobEnvRootOnly(J.bind_id,g)}if(this.unbinding.has(J.bind_id))throw new W("vm_hands_bind_lost","unbound while binding");return this.bound.set(J.bind_id,{bindId:J.bind_id,runId:J.run_id,sessionId:J.session_id,brainGeneration:J.brain_generation,policyDigest:J.policy.policy_digest,launchId:U,envInstalled:A!==null,rootId:J.claim?.root_id??"",envDirectory:z}),this.binding.delete(J.bind_id),{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:U,snapshot_revision:A,layout:E,...P?{ready_data:P}:{},policy_digest:y("sha256").update(R({hands_confinement:L.hands_confinement??null,browser_egress:L.browser_egress??null})).digest("hex")}}catch(U){if(z)GJ(z);if(K){let P=[...this.bound.keys()];await this.hooks.killAndVerifyPayload(P.length?{bindId:J.bind_id,keep:P}:void 0).then(()=>{if(!P.length)this.verifiedSinceRun=!0,this.unverified.clear()},()=>{this.unverified.add(J.bind_id),this.verifiedSinceRun=!1})}this.binding.delete(J.bind_id);let L=U&&typeof U==="object"&&"code"in U&&typeof U.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(U.code)?U.code:"vm_hands_bind_failed";throw U instanceof W?U:new W(L,"executor refused the bind")}}async deliverEnvironment(J){let Z=this.bound.get(J.attemptId);if(!Z||this.unbinding.has(J.attemptId))throw new W("vm_hands_not_bound","environment delivered while not bound");if(!d.test(J.attemptId)||typeof J.snapshotId!=="string"||!J.snapshotId||J.snapshotId.length>128||J.snapshotId.includes("/"))throw new W("vm_hands_env_invalid","bad snapshot id");let z=`${J.attemptId}/${J.snapshotId}`;if(J.sealed?.alg!=="ECDH-P256+A256GCM"||J.sealed.aad!==z)throw new W("vm_hands_env_invalid","bad env envelope");let K=jJ(await this.openSealed(J.sealed,z),{runId:Z.runId,deviceId:J.deviceId,rootId:Z.rootId,snapshotId:J.snapshotId}),U=this.hooks.installEnvironment(Z.bindId,K);if(Z.envInstalled=!0,Z.envDirectory)GJ(Z.envDirectory);return Z.envDirectory=null,Z.envDirectory=this.writeJobEnvRootOnly(`${Z.bindId}-r${U}`,K),{snapshot_id:J.snapshotId,installed_revision:U,installed:!0}}async attestFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","attest before register");if(!J||J.length>65536)throw new W("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new W("vm_hands_attest_invalid","attest beside a bind");let z=await this.hooks.runProbe({nonce:Z,script:J});try{await this.hooks.killProbe()}catch{this.servedRun=!0,this.verifiedSinceRun=!1}return{t:"attest",nonce:Z,exit_code:z.exitCode,markers:z.markers,proof_dir_inode:z.proofDirInode,script_sha256:y("sha256").update(J).digest("hex")}})}executorExited(J){return this.hooks.executorExited?.(J)??new Promise(()=>{})}async boundRefused(J){await this.unbind(J)}async unbind(J){let Z=this.bound.get(J)??null;if(this.unbinding.add(J),this.bound.delete(J),Z)try{this.hooks.freezeBind?.(J)}catch{}return this.exclusive(()=>this.tearDown(J,Z))}async tearDown(J,Z){try{this.bound.delete(J);let z=[...this.bound.keys()].filter((K)=>K!==J);try{await this.hooks.killAndVerifyPayload(z.length?{bindId:J,keep:z}:void 0)}catch(K){throw this.unverified.add(J),this.verifiedSinceRun=!1,K}if(!z.length)this.verifiedSinceRun=!0,this.unverified.clear();if(Z?.envDirectory)GJ(Z.envDirectory);return{bind_id:Z?J:null,killed_verified:!0,shredded:!0,srt_fallbacks:z.length?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(J)}}async openSealed(J,Z){let z=()=>{throw new W("vm_hands_env_invalid","env did not decrypt")},K=await crypto.subtle.importKey("spki",I(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(z),U=await crypto.subtle.deriveKey({name:"ECDH",public:K},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),L=await crypto.subtle.decrypt({name:"AES-GCM",iv:I(J.iv),additionalData:new TextEncoder().encode(Z)},U,I(J.ct)).catch(z),P=JSON.parse(new TextDecoder().decode(L));if(!P||typeof P!=="object"||Array.isArray(P))throw new W("vm_hands_env_invalid","env not an object");return P}writeJobEnvRootOnly(J,Z){let z=o(this.options.envRoot,`bind-${J}`);RJ(z,{mode:448});let K=DJ(z);if(!K.isDirectory()||(K.mode&63)!==0||K.uid!==(process.getuid?.()??-1))throw new W("vm_hands_env_dir_unsafe","env directory is not root's 0700");let U=Z.variables&&typeof Z.variables==="object"?Z.variables:{},L=Object.entries(U).filter(([A,O])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(A)&&typeof O==="string").map(([A,O])=>`export ${A}='${String(O).replaceAll("'","'\\''")}'`).join(`
3
3
  `)+`
4
4
  `,P=o(z,`.job.env.${zJ(8).toString("hex")}`),E=NJ(P,V.O_WRONLY|V.O_CREAT|V.O_EXCL|V.O_NOFOLLOW,384);try{AJ(E,L),qJ(E)}finally{LJ(E)}return fJ(P,o(z,"job.env")),z}}function GJ(J){try{let Z=o(J,"job.env"),z=DJ(Z).size,K=NJ(Z,V.O_WRONLY|V.O_NOFOLLOW);try{AJ(K,Buffer.alloc(z)),qJ(K)}finally{LJ(K)}}catch{}mJ(J,{recursive:!0,force:!0})}function lJ(J){if(J.length!==64)throw new W("vm_hands_signature_invalid","unexpected ECDSA signature length");let Z=(U)=>{let L=0;while(L<U.length-1&&U[L]===0)L++;let P=U.subarray(L),E=P[0]&128?Uint8Array.of(0,...P):P;return Uint8Array.of(2,E.length,...E)},z=Z(J.subarray(0,32)),K=Z(J.subarray(32));return Uint8Array.of(48,z.length+K.length,...z,...K)}import{randomUUID as uJ}from"crypto";var oJ="/app/local-runtime/session?register=vm_hands_v1",dJ="/app/local-runtime",MJ=25000,rJ=20000,iJ=1e4,TJ=5000,sJ=new Set(["pty.start","jobs.control","preview.serve.v1","display.stream.v1"]),YJ=75000,aJ=2000,nJ=1e4,r=20000;function EJ(J,Z){return typeof J==="string"&&/^[A-Za-z0-9._:-]{1,160}$/.test(J)?J:Z}class T extends Error{}var tJ=64;async function hJ(J,Z){let z=[...J.modelOps.get(Z)??[]];for(let K of z)K.abort.abort();await Promise.race([Promise.all(z.map((K)=>K.settled)),new Promise((K)=>setTimeout(K,TJ))])}async function eJ(J){let Z=[...J.personTerminals];for(let z of Z)z.abort.abort();if(Z.length)await Promise.race([Promise.all(Z.map((z)=>z.settled)),new Promise((z)=>setTimeout(z,TJ))]);return Z.length}async function f(J,Z,z){return await hJ(J,z),Z.unbind(z)}function i(J){for(let Z of J.outbox?.splice(0)??[])Z.reject(Error("vm_hands_attempt_ended"))}var OJ=15000,JZ=1e4,ZZ=1000;async function jZ(J){let Z=Date.now(),z={deviceId:null,connection:null,turns:new Map,lostAt:0,receipts:[],attest:"pending",attestWaiters:[],modelOps:new Map,personTerminals:new Set,bindsStarting:0},K=J.log??(()=>{}),U=async(L)=>{for(let[P,E]of[...z.turns]){z.turns.delete(P),J.onTurn?.(P,null),i(E);let A=await f(z,J.agent,P).catch(()=>null);if(A)z.receipts.push({turn:E,failure:"vm_hands_bind_lost",unbound:A});K("vm_hands.bound_dropped",{reason:L})}};try{for(let L=0;!J.signal.aborted;L++){let P=await $Z(J,z).catch((A)=>{if(A instanceof W&&z.deviceId===null&&A.code==="vm_hands_no_session"&&Date.now()-Z<nJ)return{closeCode:0,closeReason:"vm_hands_no_session"};if(A instanceof W&&z.deviceId===null)throw A;return{closeCode:0,closeReason:A instanceof Error?A.message:String(A)}});if(K("vm_hands.session_closed",{close_code:P.closeCode,reason:P.closeReason.slice(0,120),registered:z.deviceId!==null}),P.closeCode===4401||z.attest==="refused")return;if(J.signal.aborted)return;if(z.turns.size&&Date.now()-z.lostAt>=YJ)await U("reconnect_deadline");if(z.served)z.served=!1,L=0;let E=P.closeReason==="drain_reconnect"?0:P.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(L,5),2000):z.turns.size?Math.min(250*2**Math.min(L,5),5000,Math.max(0,z.lostAt+YJ-Date.now())):Math.min(500*2**L,30000);if(await new Promise((A)=>setTimeout(A,E)),z.turns.size&&Date.now()-z.lostAt>=YJ)await U("reconnect_deadline")}}finally{await U("session_ended")}}async function $Z(J,Z){let z=Z.deviceId,K=J.log??(()=>{}),U=z?`/app/local-runtime/session?device_id=${encodeURIComponent(z)}`:oJ,L=`${J.apiOrigin.replace(/^http/,"ws")}${U}`,P=new WebSocket(L),E=0,A="",O=new Map,g=[],m=null,wJ=new Promise(($)=>{P.onclose=(Q)=>{E=Q.code,A=Q.reason;for(let G of O.values())G.reject(new T(`session closed ${Q.code}`));for(let G of Z.attestWaiters.splice(0))G(!1);O.clear(),$()}});P.onmessage=($)=>{let Q;try{Q=JSON.parse(String($.data))}catch{P.close(4400);return}if(Q.t==="res"){let G=Q;O.get(G.id)?.resolve({status:G.status,body:G.body}),O.delete(G.id);return}if(Q.t==="reconnect"){let G=Math.max(0,Math.min(Number(Q.after_ms)||0,ZZ));K("vm_hands.drain_reconnect",{after_ms:G}),setTimeout(()=>{try{P.close(4001,"drain_reconnect")}catch{}},G).unref?.();return}if(!m?.(Q))g.push(Q)};let b=($,Q)=>new Promise((G,X)=>{let j=g.findIndex((C)=>$.includes(C.t));if(j>=0){G(g.splice(j,1)[0]);return}let q=setTimeout(()=>{m=null,X(new W("vm_hands_no_register",`no ${$.join("/")} in ${Q} ms`))},Q);m=(C)=>{if(!$.includes(C.t))return!1;return clearTimeout(q),m=null,G(C),!0}}),c=($)=>P.send(JSON.stringify($)),h=($,Q)=>new Promise((G,X)=>{if(P.readyState!==WebSocket.OPEN){X(new T("session closed"));return}let j=uJ(),q=typeof Q.wait_ms==="number"?Q.wait_ms:0,C=setTimeout(()=>{if(!O.delete(j))return;X(new T(`no answer to ${$.split("/").pop()} in ${q+OJ} ms`)),P.close(4000,"request_timeout")},q+OJ);O.set(j,{reject:(Y)=>{clearTimeout(C),X(Y)},resolve:({status:Y,body:F})=>{clearTimeout(C);let B=null;try{B=F?JSON.parse(F):null}catch{}G({status:Y,json:B})}}),c({t:"req",id:j,path:`${dJ}${$}`,body:JSON.stringify(Q)})}),QJ=()=>P.close(1001,"stopping");J.signal.addEventListener("abort",QJ,{once:!0});let s,p=new Map,l=new Map,a=!1,n=new Set,t=new Set,e=Promise.resolve(),u=!1;try{await new Promise((Y,F)=>{let B=setTimeout(()=>F(Error("session open timeout")),JZ);P.onopen=()=>{clearTimeout(B),K("vm_hands.ws_open",{}),Y()},P.onerror=()=>{clearTimeout(B),F(Error("session socket error"))}});let $=await b(["challenge"],5000);K("vm_hands.challenge",{});let Q=[],G=null,X;if(z){c(await J.agent.helloFrame($.challenge,Z.connection));let Y=await b(["ready"],1e4);if(typeof Y.vm_hands_connection==="string")Z.connection=Y.vm_hands_connection;if(X={device_id:z,...Y.cadence?{cadence:Y.cadence}:{}},typeof Y.vm_hands_probe_script==="string"){if(G=Y.vm_hands_probe_script,u=!0,J.agent.phase==="registered"&&!Z.turns.size)Z.attest="pending"}Z.served=!0,K("vm_hands.reconnected",{device_id:z});let F=Array.isArray(Y.vm_hands_binds)?Y.vm_hands_binds:Y.vm_hands_bind?[Y.vm_hands_bind]:[];for(let[B,x]of[...Z.turns]){if(F.some((N)=>N&&N.operation_id===x.claim.operation_id&&N.attempt_id===x.claim.attempt_id)){Q.push(x),K("vm_hands.bound_resumed",{operation_id:x.claim.operation_id});continue}Z.turns.delete(B),J.onTurn?.(B,null),i(x);let D=await f(Z,J.agent,B).catch(()=>null);if(D)Z.receipts.push({turn:x,failure:"vm_hands_bind_lost",unbound:D});K("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}else{c(await J.agent.registerFrame($.challenge)),K("vm_hands.register_sent",{});let Y=await b(["registered","register_refused"],1e4);if(Y.t==="register_refused")throw new W(Y.code,"register refused");J.agent.registered();let F=Y;if(X=F,Z.deviceId=F.device_id,typeof F.vm_hands_connection==="string")Z.connection=F.vm_hands_connection;if(typeof F.vm_hands_probe_script==="string"){if(G=F.vm_hands_probe_script,u=!0,J.agent.phase==="registered"&&!Z.turns.size)Z.attest="pending"}Z.served=!0,K("vm_hands.registered",{device_id:X.device_id})}let j=async()=>{let Y=await h("/heartbeat",await J.heartbeat());if(Y.status>=300)throw Error(`heartbeat ${Y.status}`)};await j();let q=X.cadence?.presence_interval_ms??30000;if(s=setInterval(()=>{j().catch(()=>P.close())},q),G&&Z.attest!=="accepted"&&J.agent.phase==="registered"&&!Z.turns.size)gJ(G,$.challenge);let C=(Y,F)=>{l.set(Y,F().catch(async(B)=>{if(await XJ(B,Y),B instanceof T)P.close();else await JJ().catch(()=>{return})}).finally(()=>{l.delete(Y)}))};try{await JJ();for(let Y of Q)Y.flush=()=>FJ(Y),Y.flush(),C(Y.claim.attempt_id,()=>WJ(Y));while(!J.signal.aborted&&P.readyState===WebSocket.OPEN){let Y=await h("/operations/claim",{wait_ms:Math.min(X.cadence?.claim_wait_ms??MJ,MJ)});if(Y.status===204||!Y.json)continue;if(Y.status>=300)throw Error(`claim ${Y.status}`);let F=Y.json;if(F.capability==="hands.connect"){if(l.has(F.attempt_id)){_({claim:F,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}C(F.attempt_id,()=>SJ(F))}else HJ(F).catch(()=>{return})}}catch(Y){await XJ(Y,null)}}finally{if(s)clearInterval(s);J.signal.removeEventListener("abort",QJ);for(let $ of Z.turns.values())$.flush=null;P.close(),await wJ,await Promise.all([...l.values()]);for(let $ of J.agent.liveBindIds){if(Z.turns.has($))continue;let Q=await f(Z,J.agent,$).catch(()=>null),G=p.get($);if(Q&&G)Z.receipts.push({turn:{...G,eventSeq:G.eventSeq+1},failure:"vm_hands_bind_lost",unbound:Q});K("vm_hands.bound_dropped",{reason:"bound_after_loss"})}for(let $ of n)$.abort()}return{closeCode:E,closeReason:A};async function XJ($,Q){if($ instanceof T){if(!a&&Z.turns.size)Z.lostAt=Date.now();a=!0}else{let G=Q!==null?[Q]:[...new Set([...Z.turns.keys(),...J.agent.liveBindIds])];if(Q===null)a=!0;for(let X of G){let j=Z.turns.get(X);if(Z.turns.delete(X),j)i(j),J.onTurn?.(X,null);if(J.agent.liveBindIds.includes(X)){let q=await f(Z,J.agent,X).catch(()=>null),C=p.get(X)??j;if(q&&C)Z.receipts.push({turn:{...C,eventSeq:C.eventSeq+1},failure:"vm_hands_bind_lost",unbound:q})}}}K("vm_hands.session_lost",{error:$ instanceof Error?$.message:String($),bound_kept:Z.turns.size})}function _($){let Q=$.claim,G={attempt_id:Q.attempt_id,attempt_token:Q.attempt_token},X=encodeURIComponent(Q.operation_id);return{fence:G,op:X,complete:(q,C={})=>h(`/operations/${X}/complete`,{...G,status:q,...C}),emit:(q,C)=>{let Y=($.chain??Promise.resolve()).catch(()=>{return}).then(()=>j(q,C));return $.chain=Y,Y}};async function j(q,C){let Y=$.eventSeq,F=(N)=>h(`/operations/${X}/events`,{...G,event_seq_start:N,events:[{kind:q,payload:{sequence:N,capability:String(Q.capability??"hands.connect"),data:C}}]}),B=Y,x=await F(B),D=x.status===409?x.json?.expected_event_seq:void 0;if(typeof D==="number"&&D===Y+1)x={status:200,json:{duplicate:!0}};else if(typeof D==="number"&&D>=0&&D!==Y)B=D,x=await F(B);if(x.status<300)$.eventSeq=B+1;return x}}function kJ($){return(Q,G)=>new Promise((X,j)=>{if(Z.turns.get($.claim.attempt_id)!==$){j(Error("vm_hands_attempt_ended"));return}if($.outbox??=[],$.outbox.length>=tJ){j(Error("vm_hands_outbox_full"));return}$.outbox.push({kind:Q,data:G,resolve:X,reject:j}),$.flush?.()})}function FJ($){if(t.has($))return;t.add($),(async()=>{try{while($.outbox?.length&&Z.turns.get($.claim.attempt_id)===$&&P.readyState===WebSocket.OPEN){let Q=$.outbox[0],G;try{G=await _($).emit(Q.kind,Q.data)}catch(X){if(X instanceof T)return;G={status:500}}if($.outbox.shift(),G.status<300)Q.resolve();else Q.reject(Error(`${Q.kind} refused ${G.status}`))}}finally{t.delete($)}})()}async function gJ($,Q){try{let G=await J.agent.attestFrame($,Q);if(P.readyState!==WebSocket.OPEN)return;c(G);let X=await b(["attested","attest_refused"],15000);Z.attest=X.t==="attested"?"accepted":"refused";for(let j of Z.attestWaiters.splice(0))j(Z.attest==="accepted");if(K("vm_hands.attest",{result:Z.attest,exit_code:G.exit_code,...X.t==="attest_refused"?{code:String(X.code??"")}:{}}),Z.attest==="refused")P.close(4401,"attest_refused")}catch(G){K("vm_hands.attest_failed",{code:G instanceof W?G.code:"probe_error"});for(let X of Z.attestWaiters.splice(0))X(!1);if(Z.attest!=="accepted")P.close(4000,"attest_unanswered")}}async function SJ($){let Q=u&&Z.attest==="pending",G=$.vm_hands_attest,X=G;if(Z.attest==="refused"){K("vm_hands.claim_attest_refused",{said:typeof G==="string"?G.slice(0,16):typeof G,local:Z.attest}),await _({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(X==="accepted"){if(!Q&&Z.attest!=="accepted"){Z.attest="accepted";for(let N of Z.attestWaiters.splice(0))N(!0)}}else if(X!=="pending"||!Q&&Z.attest!=="accepted"){K("vm_hands.claim_attest_refused",{said:typeof G==="string"?G.slice(0,16):typeof G,local:Z.attest}),await _({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(Z.attest!=="accepted"){let N=Date.parse($.lease_until)-Date.now()-5000,ZJ=Math.max(0,Math.min(r,Number.isFinite(N)?N:r));if(!await new Promise((S)=>{let $J=setTimeout(()=>S(!1),ZJ);Z.attestWaiters.push((M)=>{clearTimeout($J),S(M)})})){await _({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let j={claim:$,eventSeq:0},{complete:q,emit:C}=_(j),Y;try{if($.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not hands.connect");Y=!KJ($)}catch(N){K("vm_hands.bind_refused",{code:N instanceof W?N.code:"unexpected"}),await q("failed",{error_code:N instanceof W?N.code:"vm_hands_bind_invalid"});return}let F;Z.bindsStarting++;try{let N=await eJ(Z);if(N)K("vm_hands.person_terminals_closed",{count:N});F=await J.agent.bind(xJ($))}catch(N){K("vm_hands.bind_refused",{code:N instanceof W?N.code:"unexpected"}),await q("failed",{error_code:N instanceof W?N.code:"vm_hands_bind_failed"});return}finally{Z.bindsStarting--}let B={...F.ready_data??J.readyData({launchId:F.launch_id,claim:$})};if(Y)delete B.environment_installed;p.set($.attempt_id,{claim:$,launchId:F.launch_id,readyData:B,eventSeq:j.eventSeq,ackSeq:-1});let x=await C("hands.ready",{...B,vm_hands:{layout:F.layout,policy_digest:F.policy_digest,launch_id:F.launch_id}});if(p.delete($.attempt_id),x.status>=300){await hJ(Z,$.attempt_id),await J.agent.boundRefused($.attempt_id),await q("failed",{error_code:EJ(x.json?.error,"vm_hands_probe_failed")});return}let D={claim:$,launchId:F.launch_id,readyData:B,eventSeq:j.eventSeq,ackSeq:-1};Z.turns.set($.attempt_id,D),D.flush=()=>FJ(D),J.onTurn?.($.attempt_id,kJ(D)),await WJ(D)}async function WJ($){let{fence:Q,op:G}=_($),X=null,j=null,q=J.agent.executorExited($.claim.attempt_id).then((C)=>{return j=C,null});J:for(;;){let C=await Promise.race([q,h(`/operations/${G}/heartbeat`,{...Q,control_ack_seq:$.ackSeq,wait_ms:rJ})]);if(!C){X="vm_hands_executor_exited",K("vm_hands.executor_exited",{reason:j});break}if(C.status>=300)break;let Y=(C.json?.controls??[]).slice().sort((F,B)=>F.seq-B.seq);for(let F of Y){if(F.seq<=$.ackSeq)continue;if(F.kind==="operation.cancel"||F.kind==="cancel"){$.ackSeq=F.seq;break J}if(F.kind===_J)try{await vJ($,F.payload??{})}catch(B){if(B instanceof T)throw B;X=B instanceof W?B.code:"environment_unavailable";let x=B&&typeof B==="object"&&"code"in B&&typeof B.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(B.code)?B.code:null;K("vm_hands.environment_refused",{code:X,cause:x});break J}$.ackSeq=F.seq}}await VJ($,X)}async function HJ($){let Q=$,G={claim:Q,eventSeq:0},{complete:X,emit:j,fence:q,op:C}={..._(G)},Y=$.vm_hands_origin==="person"?"person":"model",F=String($.capability??"");if(!J.executeOp){await X("failed",{error_code:"vm_hands_op_unsupported"});return}if($.vm_hands_attest==="accepted"&&Z.attest==="pending"&&!(u&&Z.attest==="pending")){Z.attest="accepted";for(let M of Z.attestWaiters.splice(0))M(!0)}if(Z.attest!=="accepted"){let M=Date.parse(String($.lease_until??""))-Date.now()-5000,w=Z.attest==="refused"?0:Math.max(0,Math.min(r,Number.isFinite(M)?M:r));if(!(w>0&&await new Promise((BJ)=>{let yJ=setTimeout(()=>BJ(!1),w);Z.attestWaiters.push((IJ)=>{clearTimeout(yJ),BJ(IJ)})}))){await X("failed",{error_code:"vm_hands_unattested"});return}}let B=J.agent.bindIdForRun(Q.run_id);if(Y==="model"&&B===null){await X("failed",{error_code:"vm_hands_not_bound"});return}let x=F==="pty.start"&&Y==="person"&&!$.authority;if(x&&(J.agent.liveBindIds.length>0||Z.bindsStarting>0)){await X("failed",{error_code:"vm_hands_bound"});return}if(sJ.has(F)&&!x&&J.agent.liveBindIds.length===0){await X("failed",{error_code:"vm_hands_not_bound"});return}let D=new AbortController;n.add(D);let N,ZJ=new Promise((M)=>{N=M}),v={abort:D,settled:ZJ};if(x)Z.personTerminals.add(v);if(Y==="model"&&B){let M=Z.modelOps.get(B)??new Set;M.add(v),Z.modelOps.set(B,M),await J.agent.environmentInstalled(B,aJ,D.signal)}let S=-1,$J=setInterval(()=>{h(`/operations/${C}/heartbeat`,{...q,control_ack_seq:S,wait_ms:0}).then((M)=>{if(M.status>=300){D.abort();return}let w=M.json?.controls??[];for(let k of w)if(S=Math.max(S,k.seq),k.kind==="operation.cancel"||k.kind==="cancel")D.abort()},()=>D.abort())},iJ);try{let M=await J.executeOp({kind:Y,claim:$,...Y==="model"&&B?{bindId:B}:{},signal:D.signal,emit:async(k)=>{await j(k.kind,k.data??{})}}),w=await X(M.status,{...M.result?{result:M.result}:{},...M.error_code?{error_code:EJ(M.error_code,"vm_hands_op_failed")}:{}});K("vm_hands.op",{capability:F,kind:Y,status:M.status,code:M.error_code??null,...w.status>=300?{complete_status:w.status,complete_error:String(w.json?.error??"").slice(0,64)}:{}})}finally{if(clearInterval($J),n.delete(D),B)Z.modelOps.get(B)?.delete(v);Z.personTerminals.delete(v),N()}}async function VJ($,Q){let G=$.claim.attempt_id;if(Z.turns.get(G)===$)Z.turns.delete(G);J.onTurn?.(G,null),i($);let X=await f(Z,J.agent,G);Z.receipts.push({turn:$,failure:Q,unbound:X}),await JJ()}function JJ(){return e=e.then(PJ,PJ),e}async function PJ(){while(Z.receipts.length){let{turn:$,failure:Q,unbound:G}=Z.receipts[0],{complete:X,emit:j}=_($);try{if(await j("hands.stopped",{...$.readyData,reason_code:Q?"failed":"cancelled",killed_verified:G.killed_verified,shredded:G.shredded,...G.srt_fallbacks?{vm_hands_srt_fallbacks:G.srt_fallbacks}:{}}),Q)await X("failed",{error_code:Q});else await X("cancelled",{error_code:"driver_stopped"})}catch(q){if(q instanceof T)return}Z.receipts.shift()}}async function vJ($,Q){let{fence:G,op:X}=_($),j=Q.snapshot_id;if(Q.version!==1||typeof j!=="string"||Object.keys(Q).length!==2)throw new W("vm_hands_env_invalid","invalid environment delivery");let q=await h(`/operations/${X}/environment`,{...G,snapshot_id:j}),C=q.json?.environment_sealed;if(q.status!==200||!C||q.json?.payload!==void 0)throw new W("vm_hands_env_invalid","environment not delivered sealed");let Y=await J.agent.deliverEnvironment({attemptId:$.claim.attempt_id,snapshotId:j,deviceId:Z.deviceId??"",sealed:C});if((await h(`/operations/${X}/environment-ack`,{...G,...Y})).status>=300)throw new W("vm_hands_env_ack_refused","environment ack refused")}}
5
5
  export{QZ as M,pJ as N,jZ as O};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{ki as M}from"./vm-hands-entry-lite-070nd0vy.js";import{qi as G}from"./vm-hands-entry-lite-px64jhhn.js";import{readdirSync as D,readFileSync as I}from"fs";import{userInfo as A}from"os";var O="--vm-hands-op-runner-kind=person";function x(q){let Q=new Set([q]),K=[];try{K=D("/proc")}catch{}for(let z of K){if(!/^\d+$/.test(z))continue;try{let X=I(`/proc/${z}/stat`,"utf8");if(Number(X.slice(X.lastIndexOf(")")+2).split(" ")[3])===q)Q.add(Number(z))}catch{}}for(let z of Q)try{process.kill(z,"SIGKILL")}catch{}}var C=(q)=>{let Q=globalThis.Bun;if(!Q)throw new M("pty_unavailable","Reason terminals require the Bun runtime.");let K=Q.spawn({cmd:[q.shell,...q.args],cwd:q.cwd,env:{...q.environment,TERM:"xterm-256color"},terminal:{cols:q.cols,rows:q.rows,data:(J,Y)=>q.onData(Y)}}),z=K.terminal,X=()=>{x(K.pid);try{z?.close()}catch{}};if(!z)throw X(),new M("pty_unavailable","Reason could not allocate a pseudo-terminal.");return{write:(J)=>z.write(J),resize:(J,Y)=>z.resize(J,Y),kill:X,exited:K.exited.then((J)=>typeof J==="number"?J:null,()=>null)}};function L(){let q=(()=>{try{return A().username}catch{return}})();return{PATH:process.env.PATH,HOME:process.env.HOME,SHELL:process.env.SHELL,LANG:"C.UTF-8",...q?{USER:q,LOGNAME:q}:{}}}async function P(){let[{executeLocalOperation:q,spawnCaptured:Q},{runLocalPtySession:K},{configureDesktopAccount:z},{configureWorkerSandbox:X}]=await Promise.all([import("./local-capabilities-95a5rydg.js"),import("./local-pty-session-kq8bd4pm.js"),import("./desktop-account-a16gh9sj.js"),import("./worker-sandbox-1m0s1vnq.js")]);X();let T=process.argv.includes(O),J=($,j,F)=>Q($,j[0]==="-lic"?["-lc",...j.slice(1)]:j,F),Y=(process.geteuid?.()??0)!==0,H=new Map,Z=($)=>{try{process.send?.($)}catch{}};process.on("message",($)=>{let j=$;if(j?.t==="cancel"){H.get(j.id)?.abort();return}if(j?.t!=="op")return;if(!Y){Z({t:"done",id:j.id,completion:{status:"failed",error_code:"vm_hands_payload_account_unavailable"}});return}let F=j.claim.capability;if(F==="pty.start"&&!T){Z({t:"done",id:j.id,completion:{status:"failed",error_code:"capability_not_granted"}});return}let U=new AbortController;H.set(j.id,U);let V=F==="pty.start"?{runPtySession:(B)=>K(B,{spawnPty:C,environment:L(),loadProxy:()=>null})}:{worker:j.worker,...F==="exec.full"?{spawnFullControl:J}:{}};q(j.state,j.claim,{...V,signal:U.signal,emit:(B)=>{let{deliverySignal:N,...W}=B;Z({t:"event",id:j.id,event:W})}}).then((B)=>Z({t:"done",id:j.id,completion:B}),(B)=>Z({t:"done",id:j.id,completion:{status:"failed",error_code:B&&typeof B==="object"&&"code"in B&&typeof B.code==="string"?B.code:"vm_hands_op_failed"}})).finally(()=>H.delete(j.id))}),process.on("disconnect",()=>process.exit(0)),await new Promise(()=>{})}
2
+ import{ni as M}from"./vm-hands-entry-lite-y4nntb2w.js";import{ti as G}from"./vm-hands-entry-lite-9n6m4qgf.js";import{readdirSync as D,readFileSync as I}from"fs";import{userInfo as A}from"os";var O="--vm-hands-op-runner-kind=person";function x(q){let Q=new Set([q]),K=[];try{K=D("/proc")}catch{}for(let z of K){if(!/^\d+$/.test(z))continue;try{let X=I(`/proc/${z}/stat`,"utf8");if(Number(X.slice(X.lastIndexOf(")")+2).split(" ")[3])===q)Q.add(Number(z))}catch{}}for(let z of Q)try{process.kill(z,"SIGKILL")}catch{}}var C=(q)=>{let Q=globalThis.Bun;if(!Q)throw new M("pty_unavailable","Reason terminals require the Bun runtime.");let K=Q.spawn({cmd:[q.shell,...q.args],cwd:q.cwd,env:{...q.environment,TERM:"xterm-256color"},terminal:{cols:q.cols,rows:q.rows,data:(J,Y)=>q.onData(Y)}}),z=K.terminal,X=()=>{x(K.pid);try{z?.close()}catch{}};if(!z)throw X(),new M("pty_unavailable","Reason could not allocate a pseudo-terminal.");return{write:(J)=>z.write(J),resize:(J,Y)=>z.resize(J,Y),kill:X,exited:K.exited.then((J)=>typeof J==="number"?J:null,()=>null)}};function L(){let q=(()=>{try{return A().username}catch{return}})();return{PATH:process.env.PATH,HOME:process.env.HOME,SHELL:process.env.SHELL,LANG:"C.UTF-8",...q?{USER:q,LOGNAME:q}:{}}}async function P(){let[{executeLocalOperation:q,spawnCaptured:Q},{runLocalPtySession:K},{configureDesktopAccount:z},{configureWorkerSandbox:X}]=await Promise.all([import("./local-capabilities-4v5p6yp3.js"),import("./local-pty-session-2r99e4z9.js"),import("./desktop-account-a0tc6tgz.js"),import("./worker-sandbox-g70ryvcd.js")]);X();let T=process.argv.includes(O),J=($,j,F)=>Q($,j[0]==="-lic"?["-lc",...j.slice(1)]:j,F),Y=(process.geteuid?.()??0)!==0,H=new Map,Z=($)=>{try{process.send?.($)}catch{}};process.on("message",($)=>{let j=$;if(j?.t==="cancel"){H.get(j.id)?.abort();return}if(j?.t!=="op")return;if(!Y){Z({t:"done",id:j.id,completion:{status:"failed",error_code:"vm_hands_payload_account_unavailable"}});return}let F=j.claim.capability;if(F==="pty.start"&&!T){Z({t:"done",id:j.id,completion:{status:"failed",error_code:"capability_not_granted"}});return}let U=new AbortController;H.set(j.id,U);let V=F==="pty.start"?{runPtySession:(B)=>K(B,{spawnPty:C,environment:L(),loadProxy:()=>null})}:{worker:j.worker,...F==="exec.full"?{spawnFullControl:J}:{}};q(j.state,j.claim,{...V,signal:U.signal,emit:(B)=>{let{deliverySignal:N,...W}=B;Z({t:"event",id:j.id,event:W})}}).then((B)=>Z({t:"done",id:j.id,completion:B}),(B)=>Z({t:"done",id:j.id,completion:{status:"failed",error_code:B&&typeof B==="object"&&"code"in B&&typeof B.code==="string"?B.code:"vm_hands_op_failed"}})).finally(()=>H.delete(j.id))}),process.on("disconnect",()=>process.exit(0)),await new Promise(()=>{})}
3
3
  export{O as a,C as b,P as c};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{we as j}from"./vm-hands-entry-lite-mtp2h66e.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{ze as j}from"./vm-hands-entry-lite-samn6qm5.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 K,P as L};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{We as Zq}from"./vm-hands-entry-lite-tf5mepq5.js";import{Ze as Aq}from"./vm-hands-entry-lite-k3cq8g9w.js";import{Bf as L0,Ef as y0,Ff as T8,Gf as sq,If as $8,Lf as iq,Nf as nq,yf as H}from"./vm-hands-entry-lite-jzms4xs2.js";import{Wf as j0}from"./vm-hands-entry-lite-awwev9zg.js";import{kg as U0}from"./vm-hands-entry-lite-dhzcvvt2.js";import{Fh as d}from"./vm-hands-entry-lite-s64raarx.js";import{di as W0}from"./vm-hands-entry-lite-983czfdb.js";import{ki as M}from"./vm-hands-entry-lite-070nd0vy.js";import{execFile as tx,spawn as T0}from"child_process";import{randomBytes as ex}from"crypto";import{chmodSync as q1,existsSync as B0,lstatSync as x1,mkdirSync as X1,readFileSync as Q1,rmSync as P1,writeFileSync as o8}from"fs";import{connect as b1}from"net";import{join as _}from"path";var Uq="./desktop-wallpaper-0pjhgyfk.jpg";var Lq="./dock-browser-afp005mt.png";var yq="./dock-files-rywdm96b.png";var jq="./dock-terminal-s41cj1jp.png";var Tq=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
2
+ import{Ze as Zq}from"./vm-hands-entry-lite-z59ar4qz.js";import{af as Aq}from"./vm-hands-entry-lite-rasqv4xz.js";import{Bf as H,Ef as L0,Hf as y0,If as T8,Jf as sq,Lf as $8,Of as iq,Qf as nq}from"./vm-hands-entry-lite-dnx92ytp.js";import{Zf as j0}from"./vm-hands-entry-lite-kf5eeggb.js";import{ng as U0}from"./vm-hands-entry-lite-d17bx1yc.js";import{Ih as d}from"./vm-hands-entry-lite-0nb9zkz1.js";import{gi as W0}from"./vm-hands-entry-lite-cag8nazq.js";import{ni as M}from"./vm-hands-entry-lite-y4nntb2w.js";import{execFile as tx,spawn as T0}from"child_process";import{randomBytes as ex}from"crypto";import{chmodSync as q1,existsSync as B0,lstatSync as x1,mkdirSync as X1,readFileSync as Q1,rmSync as P1,writeFileSync as o8}from"fs";import{connect as b1}from"net";import{join as _}from"path";var Uq="./desktop-wallpaper-0pjhgyfk.jpg";var Lq="./dock-browser-afp005mt.png";var yq="./dock-files-rywdm96b.png";var jq="./dock-terminal-s41cj1jp.png";var Tq=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
3
3
  # The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
4
4
  # python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
5
5
  # Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
@@ -178,4 +178,4 @@ Gtk.main()
178
178
  `).flatMap((Q)=>{let P=Q.indexOf("=");return P>0?[[Q.slice(0,P),Q.slice(P+1)]]:[]})))}catch{return{}}}var N0=new Set;async function C1(q,x,X){let Q=await R1(),P=/^:(\d+)(?:\.\d+)?$/.exec(Q.DISPLAY??"")?.[1];if(!P||`:${P}`===B8||Q.WAYLAND_DISPLAY||Q.XDG_SESSION_TYPE==="wayland")return null;let b={display:`:${P}`,xauthority:Q.XAUTHORITY??_(q,".Xauthority"),rfbSocket:_(x,`rfb-${P}.sock`)},J=`${b.display} ${b.xauthority}`;if(N0.has(J)||!await s({path:`/tmp/.X11-unix/X${P}`},!1))return null;let y={HOME:q,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:b.display,XAUTHORITY:b.xauthority};if(await R0(X,b,x,`x11vnc-${P}.log`,y))return{...b,sound:null};return N0.add(J),process.stderr.write(`Reason worker: your screen ${b.display} could not be served; using the virtual desktop
179
179
  `),null}function S1(q,x){let X=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,Q=[["terminal","xterm"],["files","pcmanfm"]].filter(([,b])=>!B0(`/usr/bin/${b}`)).map(([b])=>b),P=Rq({root:q,display:x,screen:t8,browserExec:X,absent:Q});for(let b of["","openbox","tint2","picom"])D8(_(q,b));for(let[b,J]of Object.entries(P.files))o8(_(q,b),J,{mode:384});for(let[b,J]of Object.entries(Dq))o8(_(q,`ara-${b}`),Q1(J),{mode:384});return{root:q,openboxConfig:_(q,"openbox","rc.xml"),start:P.start}}async function Z1(q,x){let X=[`ROOT=${JSON.stringify(q.root)}`,...q.start,"openbox --reconfigure >/dev/null 2>&1 || true"].join(`
180
180
  `);await new Promise((Q)=>{let P=T0("/bin/sh",["-c",X],{stdio:"ignore",env:{...x,PATH:"/usr/bin:/bin"}}),b=setTimeout(()=>{P.kill(),Q()},R8);P.once("error",()=>{clearTimeout(b),Q()}),P.once("exit",()=>{clearTimeout(b),Q()})})}async function oX(q,x={}){let X=x.now??Date.now,Q=y1(q.payload,X());if(q.signal.throwIfAborted(),!Q.video)throw new M("display_video_required","Reason desktops stream as video now; this request came without it.");let P=x.platform??process.platform;if(P!=="linux"&&P!=="darwin")throw new M("display_video_unsupported","This machine does not serve desktop video.");let b=Q.video,J=(x.video?.desktop??(P==="darwin"?async()=>oq:B1))();return await A1(q.signal,Q,x,X,(y)=>Q0(y,{request:b,desktop:J,...Q.viewer?{viewer:Q.viewer}:{},viewerSameNetwork:Q.viewer_same_network===!0},x.video),(y)=>T8({type:"error",code:y}))}function A1(q,x,X,Q,P,b){let J=Q();return new Promise((y,C)=>{let W=null,j=!1,R=!1,Z,B,Y,w=!1,N=null,D=(A)=>{if(R)return;if(N)A=N;R=!0,clearTimeout(Z),clearTimeout(B),q.removeEventListener("abort",F),Y?.close();try{W?.close(1000,"display_session_over")}catch{}if("error"in A){C(A.error);return}y({reason:A.reason,...Y?.summary(),duration_ms:Math.max(0,Q()-J)})},G=()=>D({error:new M("display_relay_unavailable","Reason could not reach the desktop relay.")}),F=()=>{let A=q.reason;D({error:A instanceof M?A:new M("cancelled","Reason closed the desktop session.")})},O=()=>{if(!N||!W)return;let A=N.error;try{W.send(b(A instanceof M?A.code:"display_unavailable"))}catch{}D(N)};if(Y=P({get done(){return R||N!==null},get open(){return j&&!R&&N===null},get bufferedAmount(){return W?.bufferedAmount??0},send(A){if(R||N||!j||!W)return;try{W.send(A)}catch{D({reason:"relay_closed"})}},end:(A)=>{if(R||N)return;if(!("error"in A)){D(A);return}if(N=A,w&&j)O()}}),R){Y.close();return}if(q.aborted){F();return}q.addEventListener("abort",F,{once:!0}),Z=setTimeout(()=>D({reason:"session_expired"}),Math.max(1,Date.parse(x.expires_at)-Q())),B=setTimeout(()=>D({reason:"viewer_absent"}),X.viewerWaitMs??N1);try{W=(X.connect??j0)(x.relay_url,(X.loadProxy??U0)()?.url)}catch{G();return}W.binaryType="arraybuffer",W.onopen=()=>{if(R||!W)return;j=!0,Y?.opened()},W.onmessage=(A)=>{if(R)return;let f=A.data,I=f instanceof ArrayBuffer?new Uint8Array(f):ArrayBuffer.isView(f)?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):null;if(!I||I.byteLength===0)return;if(clearTimeout(B),w=!0,N){O();return}Y?.received(I)},W.onclose=()=>{if(R)return;if(!j){G();return}D({reason:"relay_closed"})},W.onerror=()=>{if(R||j)return;G()}})}
181
- export{_8 as xe,f1 as ye,p1 as ze,r as Ae,j8 as Be,HX as Ce,J0 as De,Cq as Ee,zq as Fe,k as Ge,UX as He,LX as Ie,yX as Je,J1 as Ke,B8 as Le,y1 as Me,j1 as Ne,nX as Oe,D8 as Pe,B1 as Qe,oX as Re};
181
+ export{_8 as Ae,f1 as Be,p1 as Ce,r as De,j8 as Ee,HX as Fe,J0 as Ge,Cq as He,zq as Ie,k as Je,UX as Ke,LX as Le,yX as Me,J1 as Ne,B8 as Oe,y1 as Pe,j1 as Qe,nX as Re,D8 as Se,B1 as Te,oX as Ue};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{L as f}from"./vm-hands-entry-lite-zgs6j8wj.js";import{we as $}from"./vm-hands-entry-lite-mtp2h66e.js";import{Ah as T,nh as v,qh as K,th as U,uh as y}from"./vm-hands-entry-lite-mm72ht4e.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{L as f}from"./vm-hands-entry-lite-hh0002ye.js";import{ze as $}from"./vm-hands-entry-lite-samn6qm5.js";import{Dh as T,qh as v,th as K,wh as U,xh as y}from"./vm-hands-entry-lite-png3h0cm.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 z,M as A,s0 as B,P as C,o0 as D,X as E,J0 as F,H1 as G,G1 as H,J1 as I,A0 as J};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{kg as m}from"./vm-hands-entry-lite-dhzcvvt2.js";import{tg as w}from"./vm-hands-entry-lite-cnmd8nft.js";import{Gh as h}from"./vm-hands-entry-lite-s64raarx.js";import{Th as x}from"./vm-hands-entry-lite-9rr6gh58.js";import{ki as Q}from"./vm-hands-entry-lite-070nd0vy.js";import{existsSync as B,realpathSync as k,statSync as s}from"fs";import{platform as p}from"os";import{isAbsolute as y,sep as d}from"path";var r=43200000,A=w,l=4,u=/^[A-Za-z0-9._:-]{1,160}$/,a=1000;function v(z){return Boolean(z)&&typeof z==="object"&&!Array.isArray(z)}function q(z,H){if(typeof z!=="number"||!Number.isFinite(z)||z<=0)return H;return Math.min(a,Math.max(1,Math.floor(z)))}function n(z,H=Date.now()){let V=["relay_url","session_id","expires_at"],J=new Set([...V,"cols","rows","cwd","workspace"]);if(!v(z)||V.some((L)=>!(L in z))||Object.keys(z).some((L)=>!J.has(L)))throw new Q("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:j,session_id:Y,expires_at:C}=z;if(typeof j!=="string")throw new Q("invalid_pty_request","Reason terminal relay URL is missing.");let D;try{D=new URL(j)}catch{throw new Q("invalid_pty_request","Reason terminal relay URL is invalid.")}if(D.protocol!=="wss:"&&D.protocol!=="ws:"||D.username||D.password)throw new Q("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof Y!=="string"||!u.test(Y))throw new Q("invalid_pty_request","Reason terminal session identity is invalid.");let R=typeof C==="string"?Date.parse(C):Number.NaN;if(!Number.isFinite(R)||R<=H)throw new Q("invalid_pty_request","Reason terminal session has already expired.");if(z.cwd!==void 0&&typeof z.cwd!=="string")throw new Q("invalid_pty_request","Reason terminal working directory is invalid.");let Z=z.workspace===void 0?void 0:x(z.workspace);if(Z===null||Z&&z.cwd!==void 0)throw new Q("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:j,session_id:Y,expires_at:new Date(Math.min(R,H+r)).toISOString(),cols:q(z.cols,80),rows:q(z.rows,24),...z.cwd===void 0?{}:{cwd:z.cwd},...Z?{workspace:Z}:{}}}function o(z,H){return H===z||H.startsWith(z+d)}function U(z,H){if(H===void 0)return z;if(!y(H))throw new Q("pty_cwd_invalid","Reason terminal working directory must be absolute.");let V;try{V=k(H)}catch{throw new Q("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!o(z,V))throw new Q("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!s(V).isDirectory())throw new Q("pty_cwd_invalid","Reason terminal working directory is not a directory.");return V}function t(z=process.env){let H=z.SHELL;if(H&&y(H)&&B(H))return H;for(let V of p()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(B(V))return V;return"/bin/sh"}function e(){let z=globalThis.Bun;if(!z)throw new Q("pty_unavailable","Reason terminals require the Bun runtime.");return z.spawn}function Dz(){return typeof globalThis.Bun<"u"}var zz=(z)=>{let H=e()({cmd:[z.shell,"-i","-l"],cwd:z.cwd,env:{...z.environment,TERM:"xterm-256color"},terminal:{cols:z.cols,rows:z.rows,data:(J,j)=>{z.onData(j)}}}),V=H.terminal;if(!V){try{H.kill()}catch{}throw new Q("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(J)=>V.write(J),resize:(J,j)=>V.resize(J,j),kill:()=>{try{H.kill()}catch{}},exited:H.exited.then((J)=>typeof J==="number"?J:null,()=>null)}},Hz=(z,H)=>{return H===void 0?new WebSocket(z):new WebSocket(z,{proxy:H})},S=new Set;function Jz(z){if(S.size>=l||S.has(z))return null;S.add(z);let H=!1;return()=>{if(H)return;H=!0,S.delete(z)}}async function Kz(z,H={}){let V=H.now??Date.now,J=n(z.payload,V()),j=Jz(z.operationId);if(!j)throw new Q("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let Y=V(),C,D,R;try{let Z=J.workspace?h(z.root,J.workspace):void 0;C=Z?U(B(Z.boundary)?k(Z.boundary):Z.boundary,Z.path):U(z.root,J.cwd),D=H.environment??process.env,R=H.shellPath??t(D)}catch(Z){throw j(),Z}return await new Promise((Z,L)=>{let X=null,W=null,M=!1,f=!1,K=!1,T=null,_=0,b=0,O=[],P=0,g=null,$=(N)=>{if(K)return;if(K=!0,g)clearTimeout(g);z.signal.removeEventListener("abort",I);try{X?.kill()}catch{}try{W?.close(1000,"pty_session_over")}catch{}if(j(),N.kind==="rejected"){L(N.error);return}let G={reason:N.reason,exit_code:T,output_bytes:_,input_bytes:b,duration_ms:Math.max(0,V()-Y)};z.emitEvent("pty.stopped",{...G}).catch(()=>{return}),Z({...G})},I=()=>{let N=z.signal.reason;$({kind:"rejected",error:N instanceof Q?N:new Q("cancelled","Reason closed the terminal session.")})};if(z.signal.aborted){I();return}z.signal.addEventListener("abort",I,{once:!0}),g=setTimeout(()=>$({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(J.expires_at)-V()));let i=(N)=>{if(_+=N.byteLength,!M||!W){if(O.push(N),P+=N.byteLength,P>A)$({kind:"resolved",reason:"output_backpressure"});return}try{W.send(N)}catch{$({kind:"resolved",reason:"relay_closed"});return}if(W.bufferedAmount>A)$({kind:"resolved",reason:"output_backpressure"})};try{X=(H.spawnPty??zz)({shell:R,args:["-i","-l"],cwd:C,cols:J.cols,rows:J.rows,environment:D,onData:(N)=>{if(!K)i(N)}})}catch(N){$({kind:"rejected",error:N instanceof Q?N:new Q("pty_spawn_failed","Reason could not start the terminal shell.")});return}X.exited.then((N)=>{if(K)return;if(T=N,M&&W)try{W.send(JSON.stringify({t:"exit",code:N}))}catch{}$({kind:"resolved",reason:"shell_exited"})});let c=(H.loadProxy??m)()?.url;try{W=(H.connect??Hz)(J.relay_url,c)}catch{$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}W.binaryType="arraybuffer",W.onopen=()=>{if(K||!W)return;M=!0;try{W.send(JSON.stringify({t:"open",cols:J.cols,rows:J.rows}));for(let N of O.splice(0))W.send(N);P=0}catch{$({kind:"resolved",reason:"relay_closed"});return}f=!0,z.emitEvent("pty.ready",{session_id:J.session_id,cols:J.cols,rows:J.rows}).catch(()=>{return})},W.onmessage=(N)=>{if(K||!X)return;let G=N.data;if(typeof G==="string"){let F;try{F=JSON.parse(G)}catch{return}if(!v(F))return;if(F.t==="resize"){try{X.resize(q(F.cols,J.cols),q(F.rows,J.rows))}catch{}return}if(F.t==="close")$({kind:"resolved",reason:"client_closed"});return}let E=G instanceof ArrayBuffer?new Uint8Array(G):ArrayBuffer.isView(G)?new Uint8Array(G.buffer,G.byteOffset,G.byteLength):null;if(!E||E.byteLength===0)return;b+=E.byteLength;try{X.write(E)}catch{}},W.onclose=()=>{if(K)return;if(!f){$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}$({kind:"resolved",reason:"relay_closed"})},W.onerror=()=>{if(K||f)return;$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
3
- export{r as Of,A as Pf,l as Qf,n as Rf,U as Sf,t as Tf,Dz as Uf,zz as Vf,Hz as Wf,Kz as Xf};
2
+ import{ng as m}from"./vm-hands-entry-lite-d17bx1yc.js";import{wg as w}from"./vm-hands-entry-lite-bbezym6j.js";import{Jh as h}from"./vm-hands-entry-lite-0nb9zkz1.js";import{Wh as x}from"./vm-hands-entry-lite-ytmcecfr.js";import{ni as Q}from"./vm-hands-entry-lite-y4nntb2w.js";import{existsSync as B,realpathSync as k,statSync as s}from"fs";import{platform as p}from"os";import{isAbsolute as y,sep as d}from"path";var r=43200000,A=w,l=4,u=/^[A-Za-z0-9._:-]{1,160}$/,a=1000;function v(z){return Boolean(z)&&typeof z==="object"&&!Array.isArray(z)}function q(z,H){if(typeof z!=="number"||!Number.isFinite(z)||z<=0)return H;return Math.min(a,Math.max(1,Math.floor(z)))}function n(z,H=Date.now()){let V=["relay_url","session_id","expires_at"],J=new Set([...V,"cols","rows","cwd","workspace"]);if(!v(z)||V.some((L)=>!(L in z))||Object.keys(z).some((L)=>!J.has(L)))throw new Q("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:j,session_id:Y,expires_at:C}=z;if(typeof j!=="string")throw new Q("invalid_pty_request","Reason terminal relay URL is missing.");let D;try{D=new URL(j)}catch{throw new Q("invalid_pty_request","Reason terminal relay URL is invalid.")}if(D.protocol!=="wss:"&&D.protocol!=="ws:"||D.username||D.password)throw new Q("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof Y!=="string"||!u.test(Y))throw new Q("invalid_pty_request","Reason terminal session identity is invalid.");let R=typeof C==="string"?Date.parse(C):Number.NaN;if(!Number.isFinite(R)||R<=H)throw new Q("invalid_pty_request","Reason terminal session has already expired.");if(z.cwd!==void 0&&typeof z.cwd!=="string")throw new Q("invalid_pty_request","Reason terminal working directory is invalid.");let Z=z.workspace===void 0?void 0:x(z.workspace);if(Z===null||Z&&z.cwd!==void 0)throw new Q("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:j,session_id:Y,expires_at:new Date(Math.min(R,H+r)).toISOString(),cols:q(z.cols,80),rows:q(z.rows,24),...z.cwd===void 0?{}:{cwd:z.cwd},...Z?{workspace:Z}:{}}}function o(z,H){return H===z||H.startsWith(z+d)}function U(z,H){if(H===void 0)return z;if(!y(H))throw new Q("pty_cwd_invalid","Reason terminal working directory must be absolute.");let V;try{V=k(H)}catch{throw new Q("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!o(z,V))throw new Q("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!s(V).isDirectory())throw new Q("pty_cwd_invalid","Reason terminal working directory is not a directory.");return V}function t(z=process.env){let H=z.SHELL;if(H&&y(H)&&B(H))return H;for(let V of p()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(B(V))return V;return"/bin/sh"}function e(){let z=globalThis.Bun;if(!z)throw new Q("pty_unavailable","Reason terminals require the Bun runtime.");return z.spawn}function Dz(){return typeof globalThis.Bun<"u"}var zz=(z)=>{let H=e()({cmd:[z.shell,"-i","-l"],cwd:z.cwd,env:{...z.environment,TERM:"xterm-256color"},terminal:{cols:z.cols,rows:z.rows,data:(J,j)=>{z.onData(j)}}}),V=H.terminal;if(!V){try{H.kill()}catch{}throw new Q("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(J)=>V.write(J),resize:(J,j)=>V.resize(J,j),kill:()=>{try{H.kill()}catch{}},exited:H.exited.then((J)=>typeof J==="number"?J:null,()=>null)}},Hz=(z,H)=>{return H===void 0?new WebSocket(z):new WebSocket(z,{proxy:H})},S=new Set;function Jz(z){if(S.size>=l||S.has(z))return null;S.add(z);let H=!1;return()=>{if(H)return;H=!0,S.delete(z)}}async function Kz(z,H={}){let V=H.now??Date.now,J=n(z.payload,V()),j=Jz(z.operationId);if(!j)throw new Q("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let Y=V(),C,D,R;try{let Z=J.workspace?h(z.root,J.workspace):void 0;C=Z?U(B(Z.boundary)?k(Z.boundary):Z.boundary,Z.path):U(z.root,J.cwd),D=H.environment??process.env,R=H.shellPath??t(D)}catch(Z){throw j(),Z}return await new Promise((Z,L)=>{let X=null,W=null,M=!1,f=!1,K=!1,T=null,_=0,b=0,O=[],P=0,g=null,$=(N)=>{if(K)return;if(K=!0,g)clearTimeout(g);z.signal.removeEventListener("abort",I);try{X?.kill()}catch{}try{W?.close(1000,"pty_session_over")}catch{}if(j(),N.kind==="rejected"){L(N.error);return}let G={reason:N.reason,exit_code:T,output_bytes:_,input_bytes:b,duration_ms:Math.max(0,V()-Y)};z.emitEvent("pty.stopped",{...G}).catch(()=>{return}),Z({...G})},I=()=>{let N=z.signal.reason;$({kind:"rejected",error:N instanceof Q?N:new Q("cancelled","Reason closed the terminal session.")})};if(z.signal.aborted){I();return}z.signal.addEventListener("abort",I,{once:!0}),g=setTimeout(()=>$({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(J.expires_at)-V()));let i=(N)=>{if(_+=N.byteLength,!M||!W){if(O.push(N),P+=N.byteLength,P>A)$({kind:"resolved",reason:"output_backpressure"});return}try{W.send(N)}catch{$({kind:"resolved",reason:"relay_closed"});return}if(W.bufferedAmount>A)$({kind:"resolved",reason:"output_backpressure"})};try{X=(H.spawnPty??zz)({shell:R,args:["-i","-l"],cwd:C,cols:J.cols,rows:J.rows,environment:D,onData:(N)=>{if(!K)i(N)}})}catch(N){$({kind:"rejected",error:N instanceof Q?N:new Q("pty_spawn_failed","Reason could not start the terminal shell.")});return}X.exited.then((N)=>{if(K)return;if(T=N,M&&W)try{W.send(JSON.stringify({t:"exit",code:N}))}catch{}$({kind:"resolved",reason:"shell_exited"})});let c=(H.loadProxy??m)()?.url;try{W=(H.connect??Hz)(J.relay_url,c)}catch{$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}W.binaryType="arraybuffer",W.onopen=()=>{if(K||!W)return;M=!0;try{W.send(JSON.stringify({t:"open",cols:J.cols,rows:J.rows}));for(let N of O.splice(0))W.send(N);P=0}catch{$({kind:"resolved",reason:"relay_closed"});return}f=!0,z.emitEvent("pty.ready",{session_id:J.session_id,cols:J.cols,rows:J.rows}).catch(()=>{return})},W.onmessage=(N)=>{if(K||!X)return;let G=N.data;if(typeof G==="string"){let F;try{F=JSON.parse(G)}catch{return}if(!v(F))return;if(F.t==="resize"){try{X.resize(q(F.cols,J.cols),q(F.rows,J.rows))}catch{}return}if(F.t==="close")$({kind:"resolved",reason:"client_closed"});return}let E=G instanceof ArrayBuffer?new Uint8Array(G):ArrayBuffer.isView(G)?new Uint8Array(G.buffer,G.byteOffset,G.byteLength):null;if(!E||E.byteLength===0)return;b+=E.byteLength;try{X.write(E)}catch{}},W.onclose=()=>{if(K)return;if(!f){$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}$({kind:"resolved",reason:"relay_closed"})},W.onerror=()=>{if(K||f)return;$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
3
+ export{r as Rf,A as Sf,l as Tf,n as Uf,U as Vf,t as Wf,Dz as Xf,zz as Yf,Hz as Zf,Kz as _f};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Rb as bQ,Sb as kQ,Tb as G4,Ub as z4,Vb as V8}from"./vm-hands-entry-lite-h01d2fbm.js";import{$b as s9,Zb as NQ,_b as Y8,ac as _0,bc as L9,cc as n0,jc as K0}from"./vm-hands-entry-lite-5n6vc7je.js";import{oc as b0}from"./vm-hands-entry-lite-t5h3g60g.js";import{Qd as w9,Rd as o0,Sd as W8,Td as g0,Xd as C0,id as e$,ld as $Q}from"./vm-hands-entry-lite-9k57wmkv.js";import{we as x}from"./vm-hands-entry-lite-mtp2h66e.js";import{Ve as J4}from"./vm-hands-entry-lite-tf5mepq5.js";import{tf as HZ}from"./vm-hands-entry-lite-4fcs46fz.js";import{dg as yQ,jg as i9,kg as f8}from"./vm-hands-entry-lite-dhzcvvt2.js";import{Bg as XQ,Dg as d9,Eg as s$,Fg as n$,Gg as R8,Jg as p9,Sg as I8,Tg as S0,Ug as O0,Vg as l9,ah as w8,bh as JQ,ch as i$,mg as TZ,pg as B9,yg as QQ,zg as ZQ}from"./vm-hands-entry-lite-cnmd8nft.js";import{wh as vQ,xh as y8}from"./vm-hands-entry-lite-mm72ht4e.js";import{Fh as N8,Gh as u9,Jh as X4}from"./vm-hands-entry-lite-s64raarx.js";import{Kh as B8,Lh as i0,Mh as L8,Nh as a0,Oh as H9,Ph as J8,Qh as e8,Rh as s0,Sh as p0,Th as u$,ci as W$}from"./vm-hands-entry-lite-9rr6gh58.js";import{ii as Y4}from"./vm-hands-entry-lite-983czfdb.js";import{ki as C}from"./vm-hands-entry-lite-070nd0vy.js";import{li as P1,qi as KZ}from"./vm-hands-entry-lite-px64jhhn.js";var v={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000,window:8};function h9($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function P0($,Q,Z=Number.MAX_SAFE_INTEGER){return typeof $==="number"&&Number.isSafeInteger($)&&$>=Q&&$<=Z}function E$($){return typeof $==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test($)}function S$($,Q){let Z=Buffer.from($,"latin1");return Buffer.concat([Buffer.from([Z.length]),Z,Q])}function I0($){if(!h9($)||Object.keys($).length!==12||![$.organizationId,$.userId,$.runId,$.deviceId,$.rootId,$.jobId,$.fenceId].every(E$)||!P0($.attachmentRevision,0)||!P0($.grantRevision,1)||!P0($.generation,1)||!P0($.port,1024,65535)||!P0($.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...$})}function c0($,Q){return Object.keys($).every((Z)=>$[Z]===Q[Z])}function 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 R$($){return Array.isArray($)&&$.length<=64&&$.every((Q)=>Array.isArray(Q)&&Q.length===2&&typeof Q[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(Q[0])&&typeof Q[1]==="string"&&Q[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(Q[1]))}function 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 w$($){if(Array.isArray($))return Buffer.concat($);if(typeof $==="string")return Buffer.from($,"utf8");if($ instanceof ArrayBuffer)return Buffer.from($);return $}function b$($){if(Buffer.byteLength($)>v.upload*1.4+300000)throw Error("preview_frame_too_large");let Q=JSON.parse($);if(!h9(Q))throw Error("preview_frame_invalid");if(Q.type==="hello")return{type:"hello",binding:I0(Q.binding),...P0(Q.messages,v.chunk,v.upload)?{messages:Q.messages}:{},...P0(Q.window,1,v.window)?{window:Q.window}:{},...Q.bytes===!0?{bytes:!0}:{}};if(Q.type==="refused"&&typeof Q.reason==="string"&&/^[a-z_]{1,32}$/.test(Q.reason))return{type:"refused",binding:I0(Q.binding),reason:Q.reason};if(!E$(Q.id))throw Error("preview_frame_invalid");if(Q.type==="end"||Q.type==="cancel"||Q.type==="credit")return{type:Q.type,id:Q.id};if(Q.type==="ws"&&typeof Q.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(Q.protocol))return{type:"ws",id:Q.id,protocol:Q.protocol};if(Q.type==="data"&&typeof Q.data==="string"&&typeof Q.binary==="boolean")return 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)&&R$(Q.headers))return{type:"head",id:Q.id,status:Q.status,headers:Q.headers};if(Q.type==="request"&&typeof Q.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(Q.method)&&typeof Q.path==="string"&&R$(Q.headers)&&typeof Q.body==="string"&&typeof Q.upgrade==="boolean")return 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 D8($){let Q=[...$],Z=new Set(Q.filter(([J])=>J.toLowerCase()==="connection").flatMap(([,J])=>J.toLowerCase().split(",").map((Y)=>Y.trim()))),X=new Set(["authorization","proxy-authorization","cookie","set-cookie","host","origin","referer","connection","upgrade","keep-alive","transfer-encoding","te","trailer","content-length","forwarded","alt-svc","service-worker-allowed","clear-site-data","refresh"]);return Q.filter(([J])=>!X.has(J.toLowerCase())&&!Z.has(J.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(J))}async function _8($){let Q;try{return await Promise.race([Promise.resolve().then($).then((Z)=>Z===!0||(Z===!1?!1:void 0),()=>{return}),new Promise((Z)=>{Q=setTimeout(()=>Z(void 0),v.authorizationMs)})])}finally{clearTimeout(Q)}}async function T9($){return await _8($)===!0}function v9($,Q){let Z=new URL($);if(Z.username||Z.password||Z.search||Z.hash||!(Z.protocol==="wss:"||Z.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(Z.hostname))||!new RegExp(`^/${Q}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(Z.pathname))throw Error("preview_relay_invalid");return Z.href}function k$($){if(!h9($)||Object.keys($).length!==2||typeof $.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:I0($.binding),deviceRelayUrl:v9($.deviceRelayUrl,"device")}}function f$($){if(!h9($)||Object.keys($).length!==1||!("binding"in $))throw Error("preview_close_invalid");return{binding:I0($.binding)}}import{request as D4}from"http";import{pipeline as _4}from"stream";import{constants as A8,createBrotliCompress as A4,createGzip as x4}from"zlib";import{WebSocket as O9}from"ws";import{randomBytes as q4,timingSafeEqual as T4}from"crypto";import{createServer as O4}from"net";var g$="x-preview-connection";async function m$($,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{Rb as bQ,Sb as kQ,Tb as G4,Ub as z4,Vb as V8}from"./vm-hands-entry-lite-h01d2fbm.js";import{$b as s9,Zb as NQ,_b as Y8,ac as _0,bc as L9,cc as n0,jc as K0}from"./vm-hands-entry-lite-6cj7s7rc.js";import{oc as b0}from"./vm-hands-entry-lite-t5h3g60g.js";import{Sd as w9,Td as o0,Ud as W8,Vd as g0,Zd as C0,kd as e$,nd as $Q}from"./vm-hands-entry-lite-723q0mmr.js";import{ze as x}from"./vm-hands-entry-lite-samn6qm5.js";import{Ye as J4}from"./vm-hands-entry-lite-z59ar4qz.js";import{wf as HZ}from"./vm-hands-entry-lite-efvwgjhe.js";import{gg as yQ,mg as i9,ng as f8}from"./vm-hands-entry-lite-d17bx1yc.js";import{Bg as QQ,Cg as ZQ,Eg as XQ,Gg as d9,Hg as s$,Ig as n$,Jg as R8,Mg as p9,Vg as I8,Wg as S0,Xg as O0,Yg as l9,dh as w8,eh as JQ,fh as i$,pg as TZ,sg as B9}from"./vm-hands-entry-lite-bbezym6j.js";import{Ah as y8,zh as vQ}from"./vm-hands-entry-lite-png3h0cm.js";import{Ih as N8,Jh as u9,Mh as X4}from"./vm-hands-entry-lite-0nb9zkz1.js";import{Nh as B8,Oh as i0,Ph as L8,Qh as a0,Rh as H9,Sh as J8,Th as e8,Uh as s0,Vh as p0,Wh as u$,fi as W$}from"./vm-hands-entry-lite-ytmcecfr.js";import{li as Y4}from"./vm-hands-entry-lite-cag8nazq.js";import{ni as C}from"./vm-hands-entry-lite-y4nntb2w.js";import{oi as P1,ti as KZ}from"./vm-hands-entry-lite-9n6m4qgf.js";var v={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000,window:8};function h9($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function P0($,Q,Z=Number.MAX_SAFE_INTEGER){return typeof $==="number"&&Number.isSafeInteger($)&&$>=Q&&$<=Z}function E$($){return typeof $==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test($)}function S$($,Q){let Z=Buffer.from($,"latin1");return Buffer.concat([Buffer.from([Z.length]),Z,Q])}function I0($){if(!h9($)||Object.keys($).length!==12||![$.organizationId,$.userId,$.runId,$.deviceId,$.rootId,$.jobId,$.fenceId].every(E$)||!P0($.attachmentRevision,0)||!P0($.grantRevision,1)||!P0($.generation,1)||!P0($.port,1024,65535)||!P0($.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...$})}function c0($,Q){return Object.keys($).every((Z)=>$[Z]===Q[Z])}function 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 R$($){return Array.isArray($)&&$.length<=64&&$.every((Q)=>Array.isArray(Q)&&Q.length===2&&typeof Q[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(Q[0])&&typeof Q[1]==="string"&&Q[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(Q[1]))}function 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 w$($){if(Array.isArray($))return Buffer.concat($);if(typeof $==="string")return Buffer.from($,"utf8");if($ instanceof ArrayBuffer)return Buffer.from($);return $}function b$($){if(Buffer.byteLength($)>v.upload*1.4+300000)throw Error("preview_frame_too_large");let Q=JSON.parse($);if(!h9(Q))throw Error("preview_frame_invalid");if(Q.type==="hello")return{type:"hello",binding:I0(Q.binding),...P0(Q.messages,v.chunk,v.upload)?{messages:Q.messages}:{},...P0(Q.window,1,v.window)?{window:Q.window}:{},...Q.bytes===!0?{bytes:!0}:{}};if(Q.type==="refused"&&typeof Q.reason==="string"&&/^[a-z_]{1,32}$/.test(Q.reason))return{type:"refused",binding:I0(Q.binding),reason:Q.reason};if(!E$(Q.id))throw Error("preview_frame_invalid");if(Q.type==="end"||Q.type==="cancel"||Q.type==="credit")return{type:Q.type,id:Q.id};if(Q.type==="ws"&&typeof Q.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(Q.protocol))return{type:"ws",id:Q.id,protocol:Q.protocol};if(Q.type==="data"&&typeof Q.data==="string"&&typeof Q.binary==="boolean")return 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)&&R$(Q.headers))return{type:"head",id:Q.id,status:Q.status,headers:Q.headers};if(Q.type==="request"&&typeof Q.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(Q.method)&&typeof Q.path==="string"&&R$(Q.headers)&&typeof Q.body==="string"&&typeof Q.upgrade==="boolean")return 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 D8($){let Q=[...$],Z=new Set(Q.filter(([J])=>J.toLowerCase()==="connection").flatMap(([,J])=>J.toLowerCase().split(",").map((Y)=>Y.trim()))),X=new Set(["authorization","proxy-authorization","cookie","set-cookie","host","origin","referer","connection","upgrade","keep-alive","transfer-encoding","te","trailer","content-length","forwarded","alt-svc","service-worker-allowed","clear-site-data","refresh"]);return Q.filter(([J])=>!X.has(J.toLowerCase())&&!Z.has(J.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(J))}async function _8($){let Q;try{return await Promise.race([Promise.resolve().then($).then((Z)=>Z===!0||(Z===!1?!1:void 0),()=>{return}),new Promise((Z)=>{Q=setTimeout(()=>Z(void 0),v.authorizationMs)})])}finally{clearTimeout(Q)}}async function T9($){return await _8($)===!0}function v9($,Q){let Z=new URL($);if(Z.username||Z.password||Z.search||Z.hash||!(Z.protocol==="wss:"||Z.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(Z.hostname))||!new RegExp(`^/${Q}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(Z.pathname))throw Error("preview_relay_invalid");return Z.href}function k$($){if(!h9($)||Object.keys($).length!==2||typeof $.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:I0($.binding),deviceRelayUrl:v9($.deviceRelayUrl,"device")}}function f$($){if(!h9($)||Object.keys($).length!==1||!("binding"in $))throw Error("preview_close_invalid");return{binding:I0($.binding)}}import{request as D4}from"http";import{pipeline as _4}from"stream";import{constants as A8,createBrotliCompress as A4,createGzip as x4}from"zlib";import{WebSocket as O9}from"ws";import{randomBytes as q4,timingSafeEqual as T4}from"crypto";import{createServer as O4}from"net";var g$="x-preview-connection";async function m$($,Q){if(Q.aborted)throw Error("preview_closed");let Z=q4(32).toString("base64url"),X=new Set,J=!1,Y=O4((G)=>{if(J||Q.aborted||X.size>=v.streams*2)return G.destroy();X.add(G);let F=new AbortController;G.once("close",()=>{X.delete(G),F.abort()}),G.on("error",()=>G.destroy()),G.setTimeout(2000,()=>G.destroy());let B=Buffer.alloc(0),H=(L)=>{B=Buffer.concat([B,L]);let W=B.indexOf(`\r
3
3
  \r
4
4
  `);if(W<0){if(B.length>16384)G.destroy();return}if(G.pause(),G.off("data",H),W>16384||B.length>v.upload+16384)return G.destroy();z(B,W).catch(()=>G.destroy())};G.on("data",H);async function z(L,W){let U=L.subarray(0,W).toString("latin1").split(`\r
5
5
  `),j=/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) (\S+) HTTP\/1\.1$/.exec(U.shift()??"");if(!j)throw Error("preview_request_invalid");q9(j[2]);let O=!1,q=0,A=[];for(let T of U){let S=/^([a-zA-Z0-9-]+):[ \t]*([^\x00-\x08\x0a-\x1f\x7f]*)$/.exec(T);if(!S)throw Error("preview_header_invalid");if(S[1].toLowerCase()===g$){q++;let 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 rQ extends Error{code;constructor($){super($==="hands_repl_private_profile_attribute_denied"?"Private browser attribute read denied.":$);this.code=$;this.name="HandsReplBrowserDispatcherError"}}var tQ=new Set(["__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","__proto__","constructor","prototype"]),iQ=/^hands_[A-Za-z0-9_-]{8,128}$/,K1=2048,eQ=32,$Z=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))}},QZ={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 rQ($)}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>eQ||++Z.nodes>$Z)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(tQ.has(X))I("hands_repl_invalid_json");J9(J,Q+1,Z)}}function h8($){return typeof $==="string"&&Object.hasOwn(QZ,$)}function U1($){if(!$.endsWith("[]"))return null;let Q=$.slice(0,-2);return h8(Q)?Q:null}function aQ($){return z0($)&&Object.keys($).length===2&&$.$handsRepl==="bytes"&&typeof $.base64==="string"}function W1($){return z0($)&&Object.keys($).length===1&&$.$handsRepl==="undefined"}function oQ($){return z0($)&&Object.keys($).length===2&&$.$handsRepl==="routeFulfill"&&"options"in $}function k0($){return!!$&&typeof $==="object"}function r9(){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 ZZ($){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(iQ.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"||!iQ.test(z.id)||!h8(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>eQ)I("hands_repl_json_too_complex");if(z===void 0)return r9();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 r9();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 r9();if(!h8(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(aQ(z))return X9.from(z.base64,"base64");if(W1(z))return;if(oQ(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=aQ(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(tQ.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>$Z||!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=QZ[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 r9();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(!oQ(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 zZ}from"net";import{Resolver as L1}from"dns/promises";import{isIP as e9}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 v8($){if(e9($)!==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=v8(Q);if(X===null)return!1;let J=Z===0?0:4294967295<<32-Z>>>0;return($&J)>>>0===(X&J)>>>0}function XZ($){let Q=v8($);if(Q===null)return!0;return N1.some(([Z,X])=>M1(Q,Z,X))}function j1($){if(e9($)!==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=v8(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 XZ(C1(X,J));return!1}function JZ($){return $.replace(/^\[|\]$/g,"")}function t9($){let Q=JZ($.trim()),Z=e9(Q);if(Z===4)return XZ(Q);if(Z===6)return q1(Q);return!0}function YZ($){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 GZ=5000;function T1($){return async(Q,Z)=>{if(Z?.aborted)throw Error("aborted");let X=new L1({timeout:GZ,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(YZ(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=JZ($);if(e9(X))return t9(X)?{ok:!1,reason:"non_public_ip"}:{ok:!0,addresses:[X]};let J;try{J=await D1(X,Q,GZ,Z)}catch(Y){return{ok:!1,reason:Z?.aborted?Z.reason instanceof Error&&Z.reason.name==="TimeoutError"?"dns_timeout":"aborted":YZ(Y)}}if(J.length===0)return{ok:!1,reason:"dns_empty"};if(J.some(t9))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 c8($){return $.length<=253&&_1.test($.toLowerCase())}function A1($,Q){let Z=$.trim().toLowerCase();if(!c8(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 d8($,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(".")&&!zZ(X)||Boolean(zZ(X)&&t9(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)||d8(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 VZ from"child_process";import{accessSync as I1,constants as R1,readFileSync as E1,statSync as UZ}from"fs";import{createRequire as WZ}from"module";import{homedir as FZ}from"os";import{dirname as S1,isAbsolute as p8,join as Y9,resolve as w1}from"path";var $8=Object.freeze({schemaVersion:1,driver:"playwright-core",driverVersion:HZ.dependencies["playwright-core"],browser:"chromium"}),BZ=["/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"],l8=["/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/google-chrome","/usr/bin/google-chrome-stable"];function R9($){try{return I1($,R1.X_OK),p8($)&&UZ($).isFile()}catch{return!1}}function u8($,Q=process.platform){let Z=Q==="darwin"?BZ:Q==="linux"?l8: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=[];VZ.spawn=new Proxy(VZ.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 Q8($){if(b1(),$!==void 0){if(!p8($))throw Error("hands_browser_driver_path_must_be_absolute");let X=Y9($,"package.json"),J=JSON.parse(E1(X,"utf8"));if(J.name!==$8.driver)throw Error("hands_browser_wrong_driver");let Y=WZ(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-g4t2q0ep.js"),import("./package-s8sef5wh.js").then((m)=>P1(m.default,1))]);return{version:Z.default.version,chromium:Q.chromium}}var k1=($,Q=$8.driverVersion)=>({status:"unavailable",reason:$,expectedDriverVersion:Q}),f1=($)=>$.loadDriver?.()??Q8($.driverModuleDirectory),g1={"1.60.0":"1223"};function BX(){let $=process.platform,Q=g1[$8.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(WZ(import.meta.url).resolve("playwright-core/package.json")),".local-browsers"):X?w1(Z("INIT_CWD")||process.cwd(),X):Y9($==="darwin"?Y9(FZ(),"Library","Caches"):process.env.XDG_CACHE_HOME||Y9(FZ(),".cache"),"ms-playwright");return UZ(Y9(J,`chromium-${Q}`,"INSTALLATION_COMPLETE")).isFile()}catch{return!1}}async function G9($={}){return LZ($,$8.driverVersion)}async function s8($,Q={}){if($.driverVersion!=="1.61.1"||!p8($.driverModuleDirectory))throw Error("hands_browser_invalid_managed_compatibility");return LZ({...Q,driverModuleDirectory:$.driverModuleDirectory,allowSystemBrowser:!0},$.driverVersion)}async function LZ($,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?u8($.systemCandidates,X):null;return V?Y(V,"system"):Z("executable_missing")}var a1=["/usr/local/bin/chromium",...l8];function o1($,Q=OZ()){return u8($??(Q==="linux"?a1:void 0),Q)}async function r1(){try{return(await Q8()).chromium}catch{return l1(import.meta.url)("playwright-core").chromium}}var t1=1048576,e1=105000,$7=20000,jZ=5000,Q7=2000,Z7=1000,X7=30000,CZ=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 rQ extends Error{code;constructor($){super($==="hands_repl_private_profile_attribute_denied"?"Private browser attribute read denied.":$);this.code=$;this.name="HandsReplBrowserDispatcherError"}}var tQ=new Set(["__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","__proto__","constructor","prototype"]),iQ=/^hands_[A-Za-z0-9_-]{8,128}$/,K1=2048,eQ=32,$Z=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))}},QZ={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 rQ($)}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>eQ||++Z.nodes>$Z)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(tQ.has(X))I("hands_repl_invalid_json");J9(J,Q+1,Z)}}function h8($){return typeof $==="string"&&Object.hasOwn(QZ,$)}function U1($){if(!$.endsWith("[]"))return null;let Q=$.slice(0,-2);return h8(Q)?Q:null}function aQ($){return z0($)&&Object.keys($).length===2&&$.$handsRepl==="bytes"&&typeof $.base64==="string"}function W1($){return z0($)&&Object.keys($).length===1&&$.$handsRepl==="undefined"}function oQ($){return z0($)&&Object.keys($).length===2&&$.$handsRepl==="routeFulfill"&&"options"in $}function k0($){return!!$&&typeof $==="object"}function r9(){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 ZZ($){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(iQ.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"||!iQ.test(z.id)||!h8(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>eQ)I("hands_repl_json_too_complex");if(z===void 0)return r9();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 r9();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 r9();if(!h8(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(aQ(z))return X9.from(z.base64,"base64");if(W1(z))return;if(oQ(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=aQ(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(tQ.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>$Z||!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=QZ[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 r9();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(!oQ(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 zZ}from"net";import{Resolver as L1}from"dns/promises";import{isIP as e9}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 v8($){if(e9($)!==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=v8(Q);if(X===null)return!1;let J=Z===0?0:4294967295<<32-Z>>>0;return($&J)>>>0===(X&J)>>>0}function XZ($){let Q=v8($);if(Q===null)return!0;return N1.some(([Z,X])=>M1(Q,Z,X))}function j1($){if(e9($)!==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=v8(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 XZ(C1(X,J));return!1}function JZ($){return $.replace(/^\[|\]$/g,"")}function t9($){let Q=JZ($.trim()),Z=e9(Q);if(Z===4)return XZ(Q);if(Z===6)return q1(Q);return!0}function YZ($){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 GZ=5000;function T1($){return async(Q,Z)=>{if(Z?.aborted)throw Error("aborted");let X=new L1({timeout:GZ,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(YZ(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=JZ($);if(e9(X))return t9(X)?{ok:!1,reason:"non_public_ip"}:{ok:!0,addresses:[X]};let J;try{J=await D1(X,Q,GZ,Z)}catch(Y){return{ok:!1,reason:Z?.aborted?Z.reason instanceof Error&&Z.reason.name==="TimeoutError"?"dns_timeout":"aborted":YZ(Y)}}if(J.length===0)return{ok:!1,reason:"dns_empty"};if(J.some(t9))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 c8($){return $.length<=253&&_1.test($.toLowerCase())}function A1($,Q){let Z=$.trim().toLowerCase();if(!c8(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 d8($,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(".")&&!zZ(X)||Boolean(zZ(X)&&t9(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)||d8(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 VZ from"child_process";import{accessSync as I1,constants as R1,readFileSync as E1,statSync as UZ}from"fs";import{createRequire as WZ}from"module";import{homedir as FZ}from"os";import{dirname as S1,isAbsolute as p8,join as Y9,resolve as w1}from"path";var $8=Object.freeze({schemaVersion:1,driver:"playwright-core",driverVersion:HZ.dependencies["playwright-core"],browser:"chromium"}),BZ=["/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"],l8=["/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/google-chrome","/usr/bin/google-chrome-stable"];function R9($){try{return I1($,R1.X_OK),p8($)&&UZ($).isFile()}catch{return!1}}function u8($,Q=process.platform){let Z=Q==="darwin"?BZ:Q==="linux"?l8: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=[];VZ.spawn=new Proxy(VZ.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 Q8($){if(b1(),$!==void 0){if(!p8($))throw Error("hands_browser_driver_path_must_be_absolute");let X=Y9($,"package.json"),J=JSON.parse(E1(X,"utf8"));if(J.name!==$8.driver)throw Error("hands_browser_wrong_driver");let Y=WZ(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-n922jg9n.js"),import("./package-65d4a80w.js").then((m)=>P1(m.default,1))]);return{version:Z.default.version,chromium:Q.chromium}}var k1=($,Q=$8.driverVersion)=>({status:"unavailable",reason:$,expectedDriverVersion:Q}),f1=($)=>$.loadDriver?.()??Q8($.driverModuleDirectory),g1={"1.60.0":"1223"};function BX(){let $=process.platform,Q=g1[$8.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(WZ(import.meta.url).resolve("playwright-core/package.json")),".local-browsers"):X?w1(Z("INIT_CWD")||process.cwd(),X):Y9($==="darwin"?Y9(FZ(),"Library","Caches"):process.env.XDG_CACHE_HOME||Y9(FZ(),".cache"),"ms-playwright");return UZ(Y9(J,`chromium-${Q}`,"INSTALLATION_COMPLETE")).isFile()}catch{return!1}}async function G9($={}){return LZ($,$8.driverVersion)}async function s8($,Q={}){if($.driverVersion!=="1.61.1"||!p8($.driverModuleDirectory))throw Error("hands_browser_invalid_managed_compatibility");return LZ({...Q,driverModuleDirectory:$.driverModuleDirectory,allowSystemBrowser:!0},$.driverVersion)}async function LZ($,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?u8($.systemCandidates,X):null;return V?Y(V,"system"):Z("executable_missing")}var a1=["/usr/local/bin/chromium",...l8];function o1($,Q=OZ()){return u8($??(Q==="linux"?a1:void 0),Q)}async function r1(){try{return(await Q8()).chromium}catch{return l1(import.meta.url)("playwright-core").chromium}}var t1=1048576,e1=105000,$7=20000,jZ=5000,Q7=2000,Z7=1000,X7=30000,CZ=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"&&d8(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 DZ($,Q=OZ(),Z){if(Z){let J=await s8(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 qZ($,Q){if(!$)throw Error("hands_repl_workspace_required");let Z=i8($),X=z9($),J=a8(X,z9(X,Q)),K=J!==".."&&!J.startsWith(`..${o8}`)&&!MZ(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=a8(Z,W);return U!==""&&U!==".."&&!U.startsWith(`..${o8}`)&&!MZ(U)},G=i8(K);if(b0(G))throw Error("hands_repl_protected_path");if(!V(K)||!V(G))throw Error("hands_repl_file_outside_workspace");let F=a8(Z,K).split(o8),B=[Z,...F.map((W,U)=>z9(Z,...F.slice(0,U+1)))],H=B.map((W)=>NZ(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,n8.O_RDONLY|n8.O_NOFOLLOW|n8.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=NZ(B[q]);if(A.dev!==H[q].dev||A.ino!==H[q].ino||A.isSymbolicLink())throw Error("hands_repl_file_changed")}if(!V(i8(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 Z8($){try{d1($)}catch{}}async function _Z($){if($.managedBrowser&&$.driverModuleDirectory!==void 0)throw Error("hands_browser_ambiguous_driver_configuration");let Q=$.launch||$.targetContext?null:$.managedBrowser?await s8($.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 Q8($.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 y=await b();return await D.preparePage(y),y}}let k=M.pages()[0]??await M.newPage();await D?.preparePage(k),U();let f=async(b=k)=>{let y=b;if(typeof y.ariaSnapshot==="function")return y.ariaSnapshot({timeout:1e4});return k.locator("body").innerText({timeout:1e4})},_=async(b,y={})=>{let d=y&&typeof y==="object"&&!Array.isArray(y)?y:{},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 q0=qZ($.workspaceRoot,b);u=q0.buffer,G0=q0.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 N0=String(d.label??"").replace(/[\r\n>]+/g," ").trim().slice(0,120),H0=Number(d.maxWidth)||1024,U0=Number(d.quality)||72,y0=$.targetContext?await N.newPage():await M.newPage();try{let q0=`data:${G0};base64,${u.toString("base64")}`;for(let r=0;r<5;r+=1){let M0=await y0.evaluate(async(W0)=>{let j0=new Image;j0.src=W0.url,await j0.decode();let h0=Math.min(1,W0.maxWidth/j0.naturalWidth),Y0=document.createElement("canvas");Y0.width=Math.max(1,Math.round(j0.naturalWidth*h0)),Y0.height=Math.max(1,Math.round(j0.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(j0,0,0,Y0.width,Y0.height),{data:Y0.toDataURL("image/jpeg",W0.q/100).split(",")[1]??"",width:Y0.width,height:Y0.height,sourceWidth:j0.naturalWidth,sourceHeight:j0.naturalHeight}},{url:q0,maxWidth:H0,q:U0}),r0=Buffer.from(M0.data,"base64");if(r0.length<=CZ){let W0=N0||"image";return`<<<ARA_VIEW_IMAGE ${M0.data} image/jpeg ${W0}>>>
309
309
  Viewing ${W0} (${M0.sourceWidth}x${M0.sourceHeight} source, sent at ${M0.width}x${M0.height}, ${Math.round(r0.length/1024)}KB).`}if(H0>640)H0=Math.round(H0*0.75);else U0=Math.max(30,U0-15)}throw Error(`view(): could not reduce the image under ${Math.round(CZ/1024)}KB`)}finally{await y0.close().catch(()=>{return})}},m=ZZ({browser:$.targetContext?.browser()??N,context:M,page:k,a11y:f,view:_,readWorkspaceFile:(b)=>qZ($.workspaceRoot,b),privateProfile:$.privateProfile,beforeNavigation:$.beforeNavigation,recording:$.recording,screenshotExport:$.screenshotExport,actionRecorder:()=>{let b=J,y=Y;return(d,u)=>{if(b.length<TZ)b.push(d);if(u)y.page=u}}}),c=async(b)=>{U();let y=q(await N.newContext({serviceWorkers:"block",acceptDownloads:!1}),"context");try{await y.route("**/*",(u)=>u.abort()),U(),await y.routeWebSocket("**/*",(u)=>u.close({code:1008,reason:"Reason evaluator network denied"})),U(),await y.exposeBinding("__araHandsRpc",async(u,G0)=>$.onBrowserOperation?$.onBrowserOperation(b,()=>m.dispatch(G0)):m.dispatch(G0)),U();let d=await y.newPage();return U(),await d.goto("data:text/html,<title>Reason Hands evaluator</title>"),U(),await d.evaluate(`(${sQ})(${JSON.stringify(m.roots)})`),{context:y,page:d,runId:b}}catch(d){throw await j(y).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")),jZ)})])}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(`(${nQ})(${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 y=await($.onBrowserOperation?$.onBrowserOperation(M,b):b());return k.automaticProgressImage=!0,`${l}