@reason-machines/cli-linux-arm64-musl 0.2.282 → 0.2.283

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 (61) hide show
  1. package/bin/ara +1 -1
  2. package/bin/vm-hands/connect-cli-55e1yksk.js +2 -0
  3. package/bin/vm-hands/{custom-endpoint-device-92914wyp.js → custom-endpoint-device-7kd3qh6r.js} +1 -1
  4. package/bin/vm-hands/desktop-account-5kmddfvt.js +2 -0
  5. package/bin/vm-hands/{device-workspace-zk5xwd10.js → device-workspace-te28d7t5.js} +1 -1
  6. package/bin/vm-hands/{hands-worker-source-da93x0qx.js → hands-worker-source-6ts5hhas.js} +1 -1
  7. package/bin/vm-hands/{index-w9nq2f0p.js → index-9aw1gjs5.js} +1 -1
  8. package/bin/vm-hands/local-automation-04rec2qb.js +2 -0
  9. package/bin/vm-hands/local-capabilities-2bd5ev5m.js +2 -0
  10. package/bin/vm-hands/local-desktop-users-nxyv3mk1.js +2 -0
  11. package/bin/vm-hands/local-display-mac-rp51a8w7.js +2 -0
  12. package/bin/vm-hands/local-display-session-zvj3ntsc.js +2 -0
  13. package/bin/vm-hands/{network-contract-41qanjhp.js → network-contract-wkc0ycet.js} +1 -1
  14. package/bin/vm-hands/package-56yg8k4a.js +2 -0
  15. package/bin/vm-hands/permissions-qnq69hfd.js +2 -0
  16. package/bin/vm-hands/{reason-hands-protocol-51gs8j7v.js → reason-hands-protocol-2gkb9qeb.js} +1 -1
  17. package/bin/vm-hands/{status-sj500a30.js → status-mbjv1h54.js} +2 -2
  18. package/bin/vm-hands/version-vs0sn7wr.js +2 -0
  19. package/bin/vm-hands/{vm-hands-entry-lite-z2np2gzv.js → vm-hands-entry-lite-0etm5tzc.js} +2 -2
  20. package/bin/vm-hands/{vm-hands-entry-lite-1nnj48qj.js → vm-hands-entry-lite-2yne3ped.js} +2 -2
  21. package/bin/vm-hands/{vm-hands-entry-lite-fraghb8k.js → vm-hands-entry-lite-4fnbmmp6.js} +1 -1
  22. package/bin/vm-hands/{vm-hands-entry-lite-ptmqg51y.js → vm-hands-entry-lite-53jm8bj7.js} +2 -2
  23. package/bin/vm-hands/{vm-hands-entry-lite-s2xydt0n.js → vm-hands-entry-lite-5vrdj7jm.js} +2 -2
  24. package/bin/vm-hands/{vm-hands-entry-lite-bw9verbt.js → vm-hands-entry-lite-7s23wnph.js} +2 -2
  25. package/bin/vm-hands/{vm-hands-entry-lite-c2nrar90.js → vm-hands-entry-lite-8kqg77ym.js} +1 -1
  26. package/bin/vm-hands/{vm-hands-entry-lite-1fznjm91.js → vm-hands-entry-lite-9jdxjw46.js} +2 -2
  27. package/bin/vm-hands/vm-hands-entry-lite-bjhw87nc.js +343 -0
  28. package/bin/vm-hands/{vm-hands-entry-lite-54n8tmj1.js → vm-hands-entry-lite-d2wgjdc5.js} +24 -23
  29. package/bin/vm-hands/{vm-hands-entry-lite-65pbrs1x.js → vm-hands-entry-lite-h2xpqaxn.js} +1 -1
  30. package/bin/vm-hands/{vm-hands-entry-lite-bfwf82rw.js → vm-hands-entry-lite-k1wbh9dq.js} +2 -2
  31. package/bin/vm-hands/{vm-hands-entry-lite-84aq8d12.js → vm-hands-entry-lite-kxbpf40y.js} +1 -1
  32. package/bin/vm-hands/{vm-hands-entry-lite-sv6xwe0h.js → vm-hands-entry-lite-m5pmd2cz.js} +2 -2
  33. package/bin/vm-hands/{vm-hands-entry-lite-s5qn1k80.js → vm-hands-entry-lite-qbk0wxrz.js} +2 -2
  34. package/bin/vm-hands/{vm-hands-entry-lite-25t4e0vk.js → vm-hands-entry-lite-rnykqcys.js} +3 -3
  35. package/bin/vm-hands/{vm-hands-entry-lite-7gh1rbn7.js → vm-hands-entry-lite-ss2w3h3d.js} +1 -1
  36. package/bin/vm-hands/{vm-hands-entry-lite-9pmag2qk.js → vm-hands-entry-lite-vvmq0mtv.js} +2 -2
  37. package/bin/vm-hands/{vm-hands-entry-lite-ffg7rf02.js → vm-hands-entry-lite-wffqkcjq.js} +1 -1
  38. package/bin/vm-hands/{vm-hands-entry-lite-1hwdab4e.js → vm-hands-entry-lite-whcnpjdx.js} +1 -1
  39. package/bin/vm-hands/{vm-hands-entry-lite-am0fatcw.js → vm-hands-entry-lite-y3k1pyx7.js} +2 -2
  40. package/bin/vm-hands/{vm-hands-entry-lite-anaydk9m.js → vm-hands-entry-lite-y9k070mt.js} +2 -2
  41. package/bin/vm-hands/{vm-hands-entry-lite-bwt3y6wz.js → vm-hands-entry-lite-yf8h8gmh.js} +1 -1
  42. package/bin/vm-hands/{vm-hands-entry-lite-gqncr2j0.js → vm-hands-entry-lite-yh7n4svm.js} +2 -2
  43. package/bin/vm-hands/{vm-hands-entry-lite-k4c504n7.js → vm-hands-entry-lite-yvmzze06.js} +1 -1
  44. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  45. package/bin/vm-hands/{vm-hands-executor-p7kq9n00.js → vm-hands-executor-h8hm44fp.js} +1 -1
  46. package/bin/vm-hands/{vm-hands-op-runner-350k7hem.js → vm-hands-op-runner-e2p1qwmv.js} +1 -1
  47. package/bin/vm-hands/{vm-hands-runtime-st3eagc2.js → vm-hands-runtime-pdvbqbpj.js} +3 -3
  48. package/bin/vm-hands/worker-sandbox-4c9302zr.js +2 -0
  49. package/package.json +1 -1
  50. package/bin/vm-hands/connect-cli-26easn4y.js +0 -2
  51. package/bin/vm-hands/desktop-account-vsrtgkk9.js +0 -2
  52. package/bin/vm-hands/local-automation-hk8bgn7w.js +0 -2
  53. package/bin/vm-hands/local-capabilities-j6cmcwdc.js +0 -2
  54. package/bin/vm-hands/local-desktop-users-3j79jbyp.js +0 -2
  55. package/bin/vm-hands/local-display-mac-j1v3mcgx.js +0 -2
  56. package/bin/vm-hands/local-display-session-4402sa84.js +0 -2
  57. package/bin/vm-hands/package-rx9y4bwe.js +0 -2
  58. package/bin/vm-hands/permissions-avhf90my.js +0 -2
  59. package/bin/vm-hands/version-zanrbm0q.js +0 -2
  60. package/bin/vm-hands/vm-hands-entry-lite-21zpypby.js +0 -343
  61. package/bin/vm-hands/worker-sandbox-nnce49w0.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Jd as UJ,_c as CJ,gd as qJ}from"./vm-hands-entry-lite-gqncr2j0.js";import{createHash as v,randomBytes as t}from"crypto";import{closeSync as QJ,fsyncSync as FJ,mkdirSync as kJ,openSync as WJ,renameSync as SJ,rmSync as gJ,statSync as BJ,writeSync as PJ,constants as S}from"fs";import{join as V}from"path";var HJ=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 e(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:G}=J;if(!z||typeof z!=="object"||Array.isArray(z)||!G||typeof G!=="object"||Array.isArray(G)||!Z.deviceId||!Z.rootId||z.run_id!==Z.runId||z.device_id!==Z.deviceId||G.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 NJ(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:e(J)?J.environment_sealed:null}}class W extends Error{code;constructor(J,Z){super(Z);this.code=J}}var g=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),y=(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 aJ(J){let Z=await crypto.subtle.importKey("pkcs8",y(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),z=y(J.device_key.spki),G=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),N=new Uint8Array(await crypto.subtle.exportKey("spki",G.publicKey)),D=v("sha256").update(z).digest("base64url");return{signing:{privateKey:Z},agreement:G,signingSpki:z,agreementSpki:N,fingerprint:D}}class VJ{init;keys;hooks;options;state="identity_free";lastBrainGeneration=0;bound=null;servedRun=!1;verifiedSinceRun=!1;envDirectory=null;constructor(J,Z,z,G){this.init=J;this.keys=Z;this.hooks=z;this.options=G;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(){return this.state}get boundRunId(){return this.state==="bound"?this.bound?.runId??null:null}canSpawn(J){return this.state==="bound"&&this.bound?.runId===J&&this.bound.envInstalled}async registerFrame(J){if(this.state!=="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:HJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:g(this.keys.signingSpki),env_public_key:g(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:g(t(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:g(z)}}async helloFrame(J,Z){if(this.state==="identity_free")throw new W("vm_hands_not_registered","hello before register");let z=String((this.options.now??Date.now)()),G=g(t(32)),N=UJ({method:"GET",pathAndQuery:CJ,timestamp:z,nonce:G,challenge:J,bodySha256:v("sha256").update("").digest("hex")}),D=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(N)));return{t:"hello",timestamp:z,nonce:G,signature:g(vJ(D)),...Z?{vm_hands_previous_connection:Z}:{}}}registered(){if(this.state!=="identity_free")throw new W("vm_hands_register_unexpected","registered twice");this.state="registered"}async bind(J){if(this.state!=="registered")throw new W("vm_hands_not_registered","bind before register or while bound");if(J.kind!=="vm_hands.bind"||J.v!==1)throw new W("vm_hands_bind_invalid","bad bind");for(let G of[J.bind_id,J.attempt_id,J.run_id,J.session_id,J.fence_id])if(!d.test(G))throw new W("vm_hands_bind_invalid","bad id");if(!Number.isSafeInteger(J.brain_generation)||J.brain_generation<=this.lastBrainGeneration)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(v("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");this.lastBrainGeneration=J.brain_generation;let z=null;try{if(this.servedRun&&!this.verifiedSinceRun)await this.hooks.killAndVerifyPayload();this.verifiedSinceRun=!1;let{launchId:G,applied:N,readyData:D}=await this.hooks.startExecutor({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}),B=this.hooks.restatLayout(),M=null;if(J.env){let A=J.claim?.owner??{},x=jJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof A.device_id==="string"?A.device_id:"",rootId:J.claim?.root_id??""});M=this.hooks.installEnvironment(x),z=this.writeJobEnvRootOnly(J.bind_id,x)}return this.servedRun=!0,this.bound={bindId:J.bind_id,runId:J.run_id,sessionId:J.session_id,brainGeneration:J.brain_generation,policyDigest:J.policy.policy_digest,launchId:G,envInstalled:M!==null,rootId:J.claim?.root_id??""},this.state="bound",{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:G,snapshot_revision:M,layout:B,...D?{ready_data:D}:{},policy_digest:v("sha256").update(R({hands_confinement:N.hands_confinement??null,browser_egress:N.browser_egress??null})).digest("hex")}}catch(G){if(this.servedRun=!0,z)this.shred();let N=G&&typeof G==="object"&&"code"in G&&typeof G.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(G.code)?G.code:"vm_hands_bind_failed";throw G instanceof W?G:new W(N,"executor refused the bind")}}async deliverEnvironment(J){let Z=this.bound;if(this.state!=="bound"||!Z)throw new W("vm_hands_not_bound","environment delivered while not bound");if(J.attemptId!==Z.bindId)throw new W("vm_hands_env_invalid","environment for another attempt");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 G=jJ(await this.openSealed(J.sealed,z),{runId:Z.runId,deviceId:J.deviceId,rootId:Z.rootId,snapshotId:J.snapshotId}),N=this.hooks.installEnvironment(G);return Z.envInstalled=!0,this.shred(),this.writeJobEnvRootOnly(`${Z.bindId}-r${N}`,G),{snapshot_id:J.snapshotId,installed_revision:N,installed:!0}}async attestFrame(J,Z){if(this.state==="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");let z=await this.hooks.runProbe({nonce:Z,script:J});try{await this.hooks.killAndVerifyPayload(),this.verifiedSinceRun=!0}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:v("sha256").update(J).digest("hex")}}executorExited(){return this.hooks.executorExited?.()??new Promise(()=>{})}async boundRefused(){await this.unbind()}async unbind(){let J=this.bound?.bindId??null;return this.state="unbinding",this.bound=null,await this.hooks.killAndVerifyPayload(),this.verifiedSinceRun=!0,this.shred(),this.state="registered",{bind_id:J,killed_verified:!0,shredded:!0,srt_fallbacks:this.hooks.takeSrtFallbacks?.()??null}}async openSealed(J,Z){let z=()=>{throw new W("vm_hands_env_invalid","env did not decrypt")},G=await crypto.subtle.importKey("spki",y(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(z),N=await crypto.subtle.deriveKey({name:"ECDH",public:G},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),D=await crypto.subtle.decrypt({name:"AES-GCM",iv:y(J.iv),additionalData:new TextEncoder().encode(Z)},N,y(J.ct)).catch(z),B=JSON.parse(new TextDecoder().decode(D));if(!B||typeof B!=="object"||Array.isArray(B))throw new W("vm_hands_env_invalid","env not an object");return B}writeJobEnvRootOnly(J,Z){let z=V(this.options.envRoot,`bind-${J}`);kJ(z,{mode:448});let G=BJ(z);if(!G.isDirectory()||(G.mode&63)!==0||G.uid!==(process.getuid?.()??-1))throw new W("vm_hands_env_dir_unsafe","env directory is not root's 0700");let N=Z.variables&&typeof Z.variables==="object"?Z.variables:{},D=Object.entries(N).filter(([A,x])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(A)&&typeof x==="string").map(([A,x])=>`export ${A}='${String(x).replaceAll("'","'\\''")}'`).join(`
2
+ import{Ld as UJ,ad as CJ,id as qJ}from"./vm-hands-entry-lite-yh7n4svm.js";import{createHash as v,randomBytes as t}from"crypto";import{closeSync as QJ,fsyncSync as FJ,mkdirSync as kJ,openSync as WJ,renameSync as SJ,rmSync as gJ,statSync as BJ,writeSync as PJ,constants as S}from"fs";import{join as V}from"path";var HJ=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 e(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:G}=J;if(!z||typeof z!=="object"||Array.isArray(z)||!G||typeof G!=="object"||Array.isArray(G)||!Z.deviceId||!Z.rootId||z.run_id!==Z.runId||z.device_id!==Z.deviceId||G.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 NJ(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:e(J)?J.environment_sealed:null}}class W extends Error{code;constructor(J,Z){super(Z);this.code=J}}var g=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),y=(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 aJ(J){let Z=await crypto.subtle.importKey("pkcs8",y(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),z=y(J.device_key.spki),G=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),N=new Uint8Array(await crypto.subtle.exportKey("spki",G.publicKey)),D=v("sha256").update(z).digest("base64url");return{signing:{privateKey:Z},agreement:G,signingSpki:z,agreementSpki:N,fingerprint:D}}class VJ{init;keys;hooks;options;state="identity_free";lastBrainGeneration=0;bound=null;servedRun=!1;verifiedSinceRun=!1;envDirectory=null;constructor(J,Z,z,G){this.init=J;this.keys=Z;this.hooks=z;this.options=G;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(){return this.state}get boundRunId(){return this.state==="bound"?this.bound?.runId??null:null}canSpawn(J){return this.state==="bound"&&this.bound?.runId===J&&this.bound.envInstalled}async registerFrame(J){if(this.state!=="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:HJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:g(this.keys.signingSpki),env_public_key:g(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:g(t(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:g(z)}}async helloFrame(J,Z){if(this.state==="identity_free")throw new W("vm_hands_not_registered","hello before register");let z=String((this.options.now??Date.now)()),G=g(t(32)),N=UJ({method:"GET",pathAndQuery:CJ,timestamp:z,nonce:G,challenge:J,bodySha256:v("sha256").update("").digest("hex")}),D=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(N)));return{t:"hello",timestamp:z,nonce:G,signature:g(vJ(D)),...Z?{vm_hands_previous_connection:Z}:{}}}registered(){if(this.state!=="identity_free")throw new W("vm_hands_register_unexpected","registered twice");this.state="registered"}async bind(J){if(this.state!=="registered")throw new W("vm_hands_not_registered","bind before register or while bound");if(J.kind!=="vm_hands.bind"||J.v!==1)throw new W("vm_hands_bind_invalid","bad bind");for(let G of[J.bind_id,J.attempt_id,J.run_id,J.session_id,J.fence_id])if(!d.test(G))throw new W("vm_hands_bind_invalid","bad id");if(!Number.isSafeInteger(J.brain_generation)||J.brain_generation<=this.lastBrainGeneration)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(v("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");this.lastBrainGeneration=J.brain_generation;let z=null;try{if(this.servedRun&&!this.verifiedSinceRun)await this.hooks.killAndVerifyPayload();this.verifiedSinceRun=!1;let{launchId:G,applied:N,readyData:D}=await this.hooks.startExecutor({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}),B=this.hooks.restatLayout(),M=null;if(J.env){let A=J.claim?.owner??{},x=jJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof A.device_id==="string"?A.device_id:"",rootId:J.claim?.root_id??""});M=this.hooks.installEnvironment(x),z=this.writeJobEnvRootOnly(J.bind_id,x)}return this.servedRun=!0,this.bound={bindId:J.bind_id,runId:J.run_id,sessionId:J.session_id,brainGeneration:J.brain_generation,policyDigest:J.policy.policy_digest,launchId:G,envInstalled:M!==null,rootId:J.claim?.root_id??""},this.state="bound",{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:G,snapshot_revision:M,layout:B,...D?{ready_data:D}:{},policy_digest:v("sha256").update(R({hands_confinement:N.hands_confinement??null,browser_egress:N.browser_egress??null})).digest("hex")}}catch(G){if(this.servedRun=!0,z)this.shred();let N=G&&typeof G==="object"&&"code"in G&&typeof G.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(G.code)?G.code:"vm_hands_bind_failed";throw G instanceof W?G:new W(N,"executor refused the bind")}}async deliverEnvironment(J){let Z=this.bound;if(this.state!=="bound"||!Z)throw new W("vm_hands_not_bound","environment delivered while not bound");if(J.attemptId!==Z.bindId)throw new W("vm_hands_env_invalid","environment for another attempt");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 G=jJ(await this.openSealed(J.sealed,z),{runId:Z.runId,deviceId:J.deviceId,rootId:Z.rootId,snapshotId:J.snapshotId}),N=this.hooks.installEnvironment(G);return Z.envInstalled=!0,this.shred(),this.writeJobEnvRootOnly(`${Z.bindId}-r${N}`,G),{snapshot_id:J.snapshotId,installed_revision:N,installed:!0}}async attestFrame(J,Z){if(this.state==="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");let z=await this.hooks.runProbe({nonce:Z,script:J});try{await this.hooks.killAndVerifyPayload(),this.verifiedSinceRun=!0}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:v("sha256").update(J).digest("hex")}}executorExited(){return this.hooks.executorExited?.()??new Promise(()=>{})}async boundRefused(){await this.unbind()}async unbind(){let J=this.bound?.bindId??null;return this.state="unbinding",this.bound=null,await this.hooks.killAndVerifyPayload(),this.verifiedSinceRun=!0,this.shred(),this.state="registered",{bind_id:J,killed_verified:!0,shredded:!0,srt_fallbacks:this.hooks.takeSrtFallbacks?.()??null}}async openSealed(J,Z){let z=()=>{throw new W("vm_hands_env_invalid","env did not decrypt")},G=await crypto.subtle.importKey("spki",y(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(z),N=await crypto.subtle.deriveKey({name:"ECDH",public:G},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),D=await crypto.subtle.decrypt({name:"AES-GCM",iv:y(J.iv),additionalData:new TextEncoder().encode(Z)},N,y(J.ct)).catch(z),B=JSON.parse(new TextDecoder().decode(D));if(!B||typeof B!=="object"||Array.isArray(B))throw new W("vm_hands_env_invalid","env not an object");return B}writeJobEnvRootOnly(J,Z){let z=V(this.options.envRoot,`bind-${J}`);kJ(z,{mode:448});let G=BJ(z);if(!G.isDirectory()||(G.mode&63)!==0||G.uid!==(process.getuid?.()??-1))throw new W("vm_hands_env_dir_unsafe","env directory is not root's 0700");let N=Z.variables&&typeof Z.variables==="object"?Z.variables:{},D=Object.entries(N).filter(([A,x])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(A)&&typeof x==="string").map(([A,x])=>`export ${A}='${String(x).replaceAll("'","'\\''")}'`).join(`
3
3
  `)+`
4
4
  `,B=V(z,`.job.env.${t(8).toString("hex")}`),M=WJ(B,S.O_WRONLY|S.O_CREAT|S.O_EXCL|S.O_NOFOLLOW,384);try{PJ(M,D),FJ(M)}finally{QJ(M)}return SJ(B,V(z,"job.env")),this.envDirectory=z,V(z,"job.env")}shred(){let J=this.envDirectory;if(this.envDirectory=null,!J)return;try{let Z=V(J,"job.env"),z=BJ(Z).size,G=WJ(Z,S.O_WRONLY|S.O_NOFOLLOW);try{PJ(G,Buffer.alloc(z)),FJ(G)}finally{QJ(G)}}catch{}gJ(J,{recursive:!0,force:!0})}}function vJ(J){if(J.length!==64)throw new W("vm_hands_signature_invalid","unexpected ECDSA signature length");let Z=(N)=>{let D=0;while(D<N.length-1&&N[D]===0)D++;let B=N.subarray(D),M=B[0]&128?Uint8Array.of(0,...B):B;return Uint8Array.of(2,M.length,...M)},z=Z(J.subarray(0,32)),G=Z(J.subarray(32));return Uint8Array.of(48,z.length+G.length,...z,...G)}import{randomUUID as yJ}from"crypto";var RJ="/app/local-runtime/session?register=vm_hands_v1",fJ="/app/local-runtime",DJ=25000,bJ=20000,mJ=1e4,cJ=5000,pJ=new Set(["pty.start","jobs.control","preview.serve.v1","display.stream.v1"]),JJ=75000,lJ=1e4,u=20000;class h extends Error{}var dJ=64;async function AJ(J){let Z=[...J.modelOps];for(let z of Z)z.abort.abort();await Promise.race([Promise.all(Z.map((z)=>z.settled)),new Promise((z)=>setTimeout(z,cJ))])}async function f(J,Z){return await AJ(J),Z.unbind()}function o(J){for(let Z of J.outbox?.splice(0)??[])Z.reject(Error("vm_hands_attempt_ended"))}var LJ=15000,uJ=1e4;async function zZ(J){let Z=Date.now(),z={deviceId:null,connection:null,turn:null,lostAt:0,receipts:[],attest:"pending",attestWaiters:[],flush:null,modelOps:new Set},G=J.log??(()=>{}),N=async(D)=>{let B=z.turn;if(!B)return;z.turn=null,o(B);let M=await f(z,J.agent).catch(()=>null);if(M)z.receipts.push({turn:B,failure:"vm_hands_bind_lost",unbound:M});G("vm_hands.bound_dropped",{reason:D})};try{for(let D=0;!J.signal.aborted;D++){let B=await oJ(J,z).catch((A)=>{if(A instanceof W&&z.deviceId===null&&A.code==="vm_hands_no_session"&&Date.now()-Z<lJ)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(G("vm_hands.session_closed",{close_code:B.closeCode,reason:B.closeReason.slice(0,120),registered:z.deviceId!==null}),B.closeCode===4401||z.attest==="refused")return;if(J.signal.aborted)return;if(z.turn&&Date.now()-z.lostAt>=JJ)await N("reconnect_deadline");let M=B.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(D,5),2000):z.turn?Math.min(250*2**Math.min(D,5),5000,Math.max(0,z.lostAt+JJ-Date.now())):Math.min(500*2**D,30000);if(await new Promise((A)=>setTimeout(A,M)),z.turn&&Date.now()-z.lostAt>=JJ)await N("reconnect_deadline")}}finally{await N("session_ended")}}async function oJ(J,Z){let z=Z.deviceId,G=J.log??(()=>{}),N=z?`/app/local-runtime/session?device_id=${encodeURIComponent(z)}`:RJ,D=`${J.apiOrigin.replace(/^http/,"ws")}${N}`,B=new WebSocket(D),M=0,A="",x=new Map,i=[],b=null,MJ=new Promise(($)=>{B.onclose=(K)=>{M=K.code,A=K.reason;for(let Y of x.values())Y.reject(new h(`session closed ${K.code}`));for(let Y of Z.attestWaiters.splice(0))Y(!1);x.clear(),$()}});B.onmessage=($)=>{let K;try{K=JSON.parse(String($.data))}catch{B.close(4400);return}if(K.t==="res"){let Y=K;x.get(Y.id)?.resolve({status:Y.status,body:Y.body}),x.delete(Y.id);return}if(!b?.(K))i.push(K)};let m=($,K)=>new Promise((Y,F)=>{let P=i.findIndex((C)=>$.includes(C.t));if(P>=0){Y(i.splice(P,1)[0]);return}let U=setTimeout(()=>{b=null,F(new W("vm_hands_no_register",`no ${$.join("/")} in ${K} ms`))},K);b=(C)=>{if(!$.includes(C.t))return!1;return clearTimeout(U),b=null,Y(C),!0}}),c=($)=>B.send(JSON.stringify($)),w=($,K)=>new Promise((Y,F)=>{if(B.readyState!==WebSocket.OPEN){F(new h("session closed"));return}let P=yJ(),U=typeof K.wait_ms==="number"?K.wait_ms:0,C=setTimeout(()=>{if(!x.delete(P))return;F(new h(`no answer to ${$.split("/").pop()} in ${U+LJ} ms`)),B.close(4000,"request_timeout")},U+LJ);x.set(P,{reject:(X)=>{clearTimeout(C),F(X)},resolve:({status:X,body:Q})=>{clearTimeout(C);let j=null;try{j=Q?JSON.parse(Q):null}catch{}Y({status:X,json:j})}}),c({t:"req",id:P,path:`${fJ}${$}`,body:JSON.stringify(K)})}),ZJ=()=>B.close(1001,"stopping");J.signal.addEventListener("abort",ZJ,{once:!0});let r,p={turn:null},T=null,$J=!1,s=new Set,n=!1,l=!1;try{await new Promise((X,Q)=>{let j=setTimeout(()=>Q(Error("session open timeout")),uJ);B.onopen=()=>{clearTimeout(j),G("vm_hands.ws_open",{}),X()},B.onerror=()=>{clearTimeout(j),Q(Error("session socket error"))}});let $=await m(["challenge"],5000);G("vm_hands.challenge",{});let K=null,Y=null,F=null,P;if(z){c(await J.agent.helloFrame($.challenge,Z.connection));let X=await m(["ready"],1e4);if(typeof X.vm_hands_connection==="string")Z.connection=X.vm_hands_connection;if(P={device_id:z,...X.cadence?{cadence:X.cadence}:{}},typeof X.vm_hands_probe_script==="string"){if(F=X.vm_hands_probe_script,l=!0,J.agent.phase==="registered"&&!Z.turn)Z.attest="pending"}if(G("vm_hands.reconnected",{device_id:z}),Z.turn){let Q=X.vm_hands_bind;if(Q&&Q.operation_id===Z.turn.claim.operation_id&&Q.attempt_id===Z.turn.claim.attempt_id)K=Z.turn,G("vm_hands.bound_resumed",{operation_id:Q.operation_id});else{Y=Z.turn,Z.turn=null,o(Y);let j=await f(Z,J.agent).catch(()=>null);if(j)Z.receipts.push({turn:Y,failure:"vm_hands_bind_lost",unbound:j});G("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}}else{c(await J.agent.registerFrame($.challenge)),G("vm_hands.register_sent",{});let X=await m(["registered","register_refused"],1e4);if(X.t==="register_refused")throw new W(X.code,"register refused");J.agent.registered();let Q=X;if(P=Q,Z.deviceId=Q.device_id,typeof Q.vm_hands_connection==="string")Z.connection=Q.vm_hands_connection;if(typeof Q.vm_hands_probe_script==="string"){if(F=Q.vm_hands_probe_script,l=!0,J.agent.phase==="registered"&&!Z.turn)Z.attest="pending"}G("vm_hands.registered",{device_id:P.device_id})}let U=async()=>{let X=await w("/heartbeat",await J.heartbeat());if(X.status>=300)throw Error(`heartbeat ${X.status}`)};await U();let C=P.cadence?.presence_interval_ms??30000;if(r=setInterval(()=>{U().catch(()=>B.close())},C),F&&Z.attest!=="accepted"&&J.agent.phase==="registered"&&!Z.turn)IJ(F,$.challenge);try{if(await KJ(),K){let X=K;Z.flush=()=>zJ(X),Z.flush(),T=GJ(X).catch(async(Q)=>{await a(Q),B.close()}).finally(()=>{T=null})}while(!J.signal.aborted&&B.readyState===WebSocket.OPEN){let X=await w("/operations/claim",{wait_ms:Math.min(P.cadence?.claim_wait_ms??DJ,DJ)});if(X.status===204||!X.json)continue;if(X.status>=300)throw Error(`claim ${X.status}`);let Q=X.json;if(Q.capability==="hands.connect"){if(T){_({claim:Q,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}T=EJ(Q).catch(async(j)=>{await a(j),B.close()}).finally(()=>{T=null})}else _J(Q).catch(()=>{return})}}catch(X){await a(X)}}finally{if(r)clearInterval(r);if(J.signal.removeEventListener("abort",ZJ),Z.flush=null,B.close(),await MJ,await T,(J.agent.phase==="bound"||J.agent.phase==="unbinding")&&!Z.turn){let $=await f(Z,J.agent).catch(()=>null),K=p.turn;if($&&K)Z.receipts.push({turn:{...K,eventSeq:K.eventSeq+1},failure:"vm_hands_bind_lost",unbound:$});G("vm_hands.bound_dropped",{reason:"bound_after_loss"})}for(let $ of s)$.abort()}return{closeCode:M,closeReason:A};async function a($){if($J)return;if($J=!0,Z.turn&&$ instanceof h)Z.lostAt=Date.now();else{let K=Z.turn;if(Z.turn=null,K)o(K),J.onTurn?.(null);if(J.agent.phase==="bound"||J.agent.phase==="unbinding"){let Y=await f(Z,J.agent).catch(()=>null),F=p.turn;if(Y&&F)Z.receipts.push({turn:{...F,eventSeq:F.eventSeq+1},failure:"vm_hands_bind_lost",unbound:Y})}}G("vm_hands.session_lost",{error:$ instanceof Error?$.message:String($),bound_kept:Z.turn!==null})}function _($){let K=$.claim,Y={attempt_id:K.attempt_id,attempt_token:K.attempt_token},F=encodeURIComponent(K.operation_id);return{fence:Y,op:F,complete:(U,C={})=>w(`/operations/${F}/complete`,{...Y,status:U,...C}),emit:(U,C)=>{let X=($.chain??Promise.resolve()).catch(()=>{return}).then(()=>P(U,C));return $.chain=X,X}};async function P(U,C){let X=$.eventSeq,Q=(L)=>w(`/operations/${F}/events`,{...Y,event_seq_start:L,events:[{kind:U,payload:{sequence:L,capability:String(K.capability??"hands.connect"),data:C}}]}),j=X,E=await Q(j),I=E.status===409?E.json?.expected_event_seq:void 0;if(typeof I==="number"&&I===X+1)E={status:200,json:{duplicate:!0}};else if(typeof I==="number"&&I>=0&&I!==X)j=I,E=await Q(j);if(E.status<300)$.eventSeq=j+1;return E}}function xJ($){return(K,Y)=>new Promise((F,P)=>{if(Z.turn!==$){P(Error("vm_hands_attempt_ended"));return}if($.outbox??=[],$.outbox.length>=dJ){P(Error("vm_hands_outbox_full"));return}$.outbox.push({kind:K,data:Y,resolve:F,reject:P}),Z.flush?.()})}function zJ($){if(n)return;n=!0,(async()=>{try{while($.outbox?.length&&Z.turn===$&&B.readyState===WebSocket.OPEN){let K=$.outbox[0],Y;try{Y=await _($).emit(K.kind,K.data)}catch(F){if(F instanceof h)return;Y={status:500}}if($.outbox.shift(),Y.status<300)K.resolve();else K.reject(Error(`${K.kind} refused ${Y.status}`))}}finally{n=!1}})()}async function IJ($,K){try{let Y=await J.agent.attestFrame($,K);if(B.readyState!==WebSocket.OPEN)return;c(Y);let F=await m(["attested","attest_refused"],15000);Z.attest=F.t==="attested"?"accepted":"refused";for(let P of Z.attestWaiters.splice(0))P(Z.attest==="accepted");if(G("vm_hands.attest",{result:Z.attest,exit_code:Y.exit_code,...F.t==="attest_refused"?{code:String(F.code??"")}:{}}),Z.attest==="refused")B.close(4401,"attest_refused")}catch(Y){G("vm_hands.attest_failed",{code:Y instanceof W?Y.code:"probe_error"});for(let F of Z.attestWaiters.splice(0))F(!1);if(Z.attest!=="accepted")B.close(4000,"attest_unanswered")}}async function EJ($){let K=l&&Z.attest==="pending",Y=$.vm_hands_attest,F=Y;if(Z.attest==="refused"){G("vm_hands.claim_attest_refused",{said:typeof Y==="string"?Y.slice(0,16):typeof Y,local:Z.attest}),await _({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(F==="accepted"){if(!K&&Z.attest!=="accepted"){Z.attest="accepted";for(let L of Z.attestWaiters.splice(0))L(!0)}}else if(F!=="pending"||!K){G("vm_hands.claim_attest_refused",{said:typeof Y==="string"?Y.slice(0,16):typeof Y,local:Z.attest}),await _({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(Z.attest!=="accepted"){let L=Date.parse($.lease_until)-Date.now()-5000,H=Math.max(0,Math.min(u,Number.isFinite(L)?L:u));if(!await new Promise((q)=>{let O=setTimeout(()=>q(!1),H);Z.attestWaiters.push((k)=>{clearTimeout(O),q(k)})})){await _({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let P={claim:$,eventSeq:0},{complete:U,emit:C}=_(P),X;try{if($.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not hands.connect");X=!e($)}catch(L){G("vm_hands.bind_refused",{code:L instanceof W?L.code:"unexpected"}),await U("failed",{error_code:L instanceof W?L.code:"vm_hands_bind_invalid"});return}let Q;try{Q=await J.agent.bind(NJ($))}catch(L){G("vm_hands.bind_refused",{code:L instanceof W?L.code:"unexpected"}),await U("failed",{error_code:L instanceof W?L.code:"vm_hands_bind_failed"});return}let j={...Q.ready_data??J.readyData({launchId:Q.launch_id,claim:$})};if(X)delete j.environment_installed;p.turn={claim:$,launchId:Q.launch_id,readyData:j,eventSeq:P.eventSeq,ackSeq:-1};let E=await C("hands.ready",{...j,vm_hands:{layout:Q.layout,policy_digest:Q.policy_digest,launch_id:Q.launch_id}});if(p.turn=null,E.status>=300){await AJ(Z),await J.agent.boundRefused(),await U("failed",{error_code:String(E.json?.error??"vm_hands_probe_failed")});return}let I={claim:$,launchId:Q.launch_id,readyData:j,eventSeq:P.eventSeq,ackSeq:-1};Z.turn=I,Z.flush=()=>zJ(I),J.onTurn?.(xJ(I)),await GJ(I)}async function GJ($){let{fence:K,op:Y}=_($),F=null,P=null,U=J.agent.executorExited().then((C)=>{return P=C,null});J:for(;;){let C=await Promise.race([U,w(`/operations/${Y}/heartbeat`,{...K,control_ack_seq:$.ackSeq,wait_ms:bJ})]);if(!C){F="vm_hands_executor_exited",G("vm_hands.executor_exited",{reason:P});break}if(C.status>=300)break;let X=(C.json?.controls??[]).slice().sort((Q,j)=>Q.seq-j.seq);for(let Q of X){if(Q.seq<=$.ackSeq)continue;if(Q.kind==="operation.cancel"||Q.kind==="cancel"){$.ackSeq=Q.seq;break J}if(Q.kind===qJ)try{await wJ($,Q.payload??{})}catch(j){if(j instanceof h)throw j;F=j instanceof W?j.code:"environment_unavailable",G("vm_hands.environment_refused",{code:F});break J}$.ackSeq=Q.seq}}await OJ($,F)}async function _J($){let K=$,Y={claim:K,eventSeq:0},{complete:F,emit:P,fence:U,op:C}={..._(Y)},X=$.vm_hands_origin==="person"?"person":"model",Q=String($.capability??"");if(!J.executeOp){await F("failed",{error_code:"vm_hands_op_unsupported"});return}if($.vm_hands_attest==="accepted"&&Z.attest==="pending"&&!(l&&Z.attest==="pending")){Z.attest="accepted";for(let q of Z.attestWaiters.splice(0))q(!0)}if(Z.attest!=="accepted"){let q=Date.parse(String($.lease_until??""))-Date.now()-5000,O=Z.attest==="refused"?0:Math.max(0,Math.min(u,Number.isFinite(q)?q:u));if(!(O>0&&await new Promise((XJ)=>{let hJ=setTimeout(()=>XJ(!1),O);Z.attestWaiters.push((TJ)=>{clearTimeout(hJ),XJ(TJ)})}))){await F("failed",{error_code:"vm_hands_unattested"});return}}if(X==="model"&&(J.agent.phase!=="bound"||J.agent.boundRunId!==K.run_id)){await F("failed",{error_code:"vm_hands_not_bound"});return}if(pJ.has(Q)&&J.agent.phase!=="bound"){await F("failed",{error_code:"vm_hands_not_bound"});return}let j=new AbortController;s.add(j);let E,I=new Promise((q)=>{E=q}),L={abort:j,settled:I};if(X==="model")Z.modelOps.add(L);let H=-1,YJ=setInterval(()=>{w(`/operations/${C}/heartbeat`,{...U,control_ack_seq:H,wait_ms:0}).then((q)=>{if(q.status>=300){j.abort();return}let O=q.json?.controls??[];for(let k of O)if(H=Math.max(H,k.seq),k.kind==="operation.cancel"||k.kind==="cancel")j.abort()},()=>j.abort())},mJ);try{let q=await J.executeOp({kind:X,claim:$,signal:j.signal,emit:async(O)=>{await P(O.kind,O.data??{})}});await F(q.status,{...q.result?{result:q.result}:{},...q.error_code!==void 0?{error_code:q.error_code}:{}}),G("vm_hands.op",{capability:Q,kind:X,status:q.status,code:q.error_code??null})}finally{clearInterval(YJ),s.delete(j),Z.modelOps.delete(L),E()}}async function OJ($,K){if(Z.turn===$)Z.turn=null;J.onTurn?.(null),o($);let Y=await f(Z,J.agent);Z.receipts.push({turn:$,failure:K,unbound:Y}),await KJ()}async function KJ(){while(Z.receipts.length){let{turn:$,failure:K,unbound:Y}=Z.receipts[0],{complete:F,emit:P}=_($);try{if(await P("hands.stopped",{...$.readyData,reason_code:K?"failed":"cancelled",killed_verified:Y.killed_verified,shredded:Y.shredded,...Y.srt_fallbacks?{vm_hands_srt_fallbacks:Y.srt_fallbacks}:{}}),K)await F("failed",{error_code:K});else await F("cancelled",{error_code:"driver_stopped"})}catch(U){if(U instanceof h)return}Z.receipts.shift()}}async function wJ($,K){let{fence:Y,op:F}=_($),P=K.snapshot_id;if(K.version!==1||typeof P!=="string"||Object.keys(K).length!==2)throw new W("vm_hands_env_invalid","invalid environment delivery");let U=await w(`/operations/${F}/environment`,{...Y,snapshot_id:P}),C=U.json?.environment_sealed;if(U.status!==200||!C||U.json?.payload!==void 0)throw new W("vm_hands_env_invalid","environment not delivered sealed");let X=await J.agent.deliverEnvironment({attemptId:$.claim.attempt_id,snapshotId:P,deviceId:Z.deviceId??"",sealed:C});if((await w(`/operations/${F}/environment-ack`,{...Y,...X})).status>=300)throw new W("vm_hands_env_ack_refused","environment ack refused")}}
5
5
  export{aJ as u,VJ as v,zZ as w};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{jh as m}from"./vm-hands-entry-lite-84aq8d12.js";var E=["Click browser element","Double click browser element","Type text","Clear browser field","Press key","Scroll browser element into view","Drag on computer","Select browser option","Check browser control","Uncheck browser control","Hover browser element","Focus browser element","Open browser page","Reload browser page","Go back in browser","Go forward in browser","Take browser screenshot"],VA=32;function R(x){if(!Array.isArray(x)||x.length>32||!x.every((A)=>typeof A==="string"&&E.includes(A)))return;return x.slice()}var $A="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",JA=262144;function Y(x){if(!x||typeof x!=="object"||Array.isArray(x))return!1;let A=x,B=Object.keys(A);return B.length===2&&B.includes("template")&&B.includes("quoteDepth")&&typeof A.template==="string"&&A.template.length<=262144&&!A.template.includes("\x00")&&A.template.split("__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__").length===2&&(A.quoteDepth===1||A.quoteDepth===2||A.quoteDepth===3)}var X=2,P=33554432,K=200000,D=4000000,Q=240000,DA=`
2
+ import{lh as m}from"./vm-hands-entry-lite-kxbpf40y.js";var E=["Click browser element","Double click browser element","Type text","Clear browser field","Press key","Scroll browser element into view","Drag on computer","Select browser option","Check browser control","Uncheck browser control","Hover browser element","Focus browser element","Open browser page","Reload browser page","Go back in browser","Go forward in browser","Take browser screenshot"],VA=32;function R(x){if(!Array.isArray(x)||x.length>32||!x.every((A)=>typeof A==="string"&&E.includes(A)))return;return x.slice()}var $A="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",JA=262144;function Y(x){if(!x||typeof x!=="object"||Array.isArray(x))return!1;let A=x,B=Object.keys(A);return B.length===2&&B.includes("template")&&B.includes("quoteDepth")&&typeof A.template==="string"&&A.template.length<=262144&&!A.template.includes("\x00")&&A.template.split("__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__").length===2&&(A.quoteDepth===1||A.quoteDepth===2||A.quoteDepth===3)}var X=2,P=33554432,K=200000,D=4000000,Q=240000,DA=`
3
3
  ...[executor output truncated]`,j=2000,f=1,b=16384,p=32768,w=128,RA=64,i=2097152,h=1,y=16384,d=32768,YA=8388608,s=1000,c=2500,n=2000,LA=c+n,t=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/,r=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,o={text_only:4430,invalid_json:4431,invalid_cancel_request:4432,invalid_sdk_response:4433,claim_required:4434,invalid_claim:4435,executor_mismatch:4436,stale_generation:4437,fence_conflict:4438,frame_too_large:4439,result_too_large:4440,progress_too_large:4441,terminal_cleanup_started:4442,job_journal_unavailable:4443},v=new Map(Object.entries(o).map(([x,A])=>[A,x]));function OA(x,A){return A||(v.get(x)??"")}var l=["cancelled","command_failed","duplicate_request_id","duplicate_result_evicted","invalid_repl_response","invalid_request","process_group_cleanup_unconfirmed","repl_failed","result_too_large","repl_response_too_large","repl_transport_failed","request_ledger_full","request_journal_unavailable","request_outcome_uncertain","maintenance_held","request_not_found","resume_digest_mismatch","spawn_failed","stale_generation","timeout"],u=new Set(l),a=200,e=2000,AA=["maintenance_held","invalid_job_request","jobs_disabled","job_not_found","job_conflict","job_capacity","job_journal_unavailable","job_not_running","job_lease_expired","job_input_sequence","job_input_backpressure","stale_generation","pty_unsupported","job_mode_mismatch"];class G extends Error{code;constructor(x){super(x);this.name="HandsProtocolError",this.code=x}}function k(x){return new TextEncoder().encode(x).byteLength}function F(x){return typeof x==="object"&&x!==null&&!Array.isArray(x)}function W(x,A){let B=new Set(A);return Object.keys(x).every((N)=>B.has(N))}function M(x){return typeof x==="string"&&t.test(x)}function V(x){return Number.isSafeInteger(x)&&Number(x)>=1}function $(x){return typeof x==="string"&&r.test(x)}function C(x){return typeof x==="string"&&x.startsWith("pty-")&&$(x.slice(4))}function z(x){return[x.cols,x.rows].every((A)=>Number.isSafeInteger(A)&&Number(A)>=1&&Number(A)<=s)}function H(x){if(typeof x!=="string"||x.length>Math.ceil(y/3)*4||x.length%4!==0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(x))return-1;let A=x.endsWith("==")?2:x.endsWith("=")?1:0;if(A&&"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(x[x.length-A-1])&(A===2?15:3))return-1;let N=x.length/4*3-A;return N<=y?N:-1}function S(x){return typeof x==="string"&&/^[0-9a-f]{64}$/.test(x)}function Z(x){if(k(x)>P)throw new G("frame_too_large");try{return JSON.parse(x)}catch{throw new G("invalid_json")}}function xA(x){let A=Z(x);if(!F(A)||!W(A,["version","generation","id","tool","input","semanticDigest","lifecycleLeaseId"])||A.version!==X||!V(A.generation)||!M(A.id)||!["bash","repl","resume","read","edit","write","pi_tool"].includes(String(A.tool))||!F(A.input)||A.lifecycleLeaseId!==void 0&&(A.tool!=="bash"||!$(A.lifecycleLeaseId)))throw new G("invalid_request");if(A.tool==="bash"){if(!W(A.input,["script","retainBackground","machineSdk"])||typeof A.input.script!=="string"||A.input.script.length>K||A.input.retainBackground!==void 0&&A.input.retainBackground!==!0||A.input.machineSdk!==void 0&&A.input.machineSdk!==!0||A.semanticDigest!==void 0&&!S(A.semanticDigest))throw new G("invalid_request");return{version:X,generation:A.generation,id:A.id,tool:"bash",input:{script:A.input.script,...A.input.retainBackground===!0?{retainBackground:!0}:{},...A.input.machineSdk===!0?{machineSdk:!0}:{}},...A.semanticDigest===void 0?{}:{semanticDigest:A.semanticDigest},...A.lifecycleLeaseId===void 0?{}:{lifecycleLeaseId:A.lifecycleLeaseId}}}if(A.tool==="resume"){if(A.semanticDigest!==void 0||!W(A.input,["semanticDigest"])||!S(A.input.semanticDigest))throw new G("invalid_request");return{version:X,generation:A.generation,id:A.id,tool:"resume",input:{semanticDigest:A.input.semanticDigest}}}if(A.tool==="repl"){if(!W(A.input,["code"])||typeof A.input.code!=="string"||A.input.code.length>K||A.semanticDigest!==void 0)throw new G("invalid_request");return{version:X,generation:A.generation,id:A.id,tool:"repl",input:{code:A.input.code}}}if(A.tool==="pi_tool"){let B=A.semanticDigest===void 0?BA(A.input):null;if(!B)throw new G("invalid_request");return{version:X,generation:A.generation,id:A.id,tool:"pi_tool",input:B}}if(A.tool==="read"){if(!W(A.input,["path","offset","limit"])||typeof A.input.path!=="string"||A.input.path.length<1||A.input.path.length>K||A.semanticDigest!==void 0||A.input.offset!==void 0&&(!Number.isSafeInteger(A.input.offset)||Number(A.input.offset)<1)||A.input.limit!==void 0&&(!Number.isSafeInteger(A.input.limit)||Number(A.input.limit)<1||Number(A.input.limit)>2000))throw new G("invalid_request");return{version:X,generation:A.generation,id:A.id,tool:"read",input:{path:A.input.path,...A.input.offset===void 0?{}:{offset:Number(A.input.offset)},...A.input.limit===void 0?{}:{limit:Number(A.input.limit)}}}}if(A.tool==="edit"){if(!W(A.input,["path","edits"])||typeof A.input.path!=="string"||A.input.path.length<1||!Array.isArray(A.input.edits)||A.input.edits.length<1||A.input.edits.length>128||A.semanticDigest!==void 0)throw new G("invalid_request");let B=A.input.path.length,N=[];for(let I of A.input.edits){if(!F(I)||!W(I,["oldText","newText"])||typeof I.oldText!=="string"||I.oldText.length<1||typeof I.newText!=="string")throw new G("invalid_request");if(B+=I.oldText.length+I.newText.length,B>D)throw new G("invalid_request");N.push({oldText:I.oldText,newText:I.newText})}return{version:X,generation:A.generation,id:A.id,tool:"edit",input:{path:A.input.path,edits:N}}}if(A.tool!=="write"||!W(A.input,["path","content"])||typeof A.input.path!=="string"||A.input.path.length<1||typeof A.input.content!=="string"||A.input.path.length+A.input.content.length>D||A.semanticDigest!==void 0)throw new G("invalid_request");return{version:X,generation:A.generation,id:A.id,tool:"write",input:{path:A.input.path,content:A.input.content}}}function L(x){return x===void 0||typeof x==="number"&&Number.isFinite(x)}function BA(x){let A=x.args;if(!W(x,["tool","args"])||!F(A))return null;if(x.tool==="bash")return W(A,["command","timeout"])&&typeof A.command==="string"&&A.command.length<=K&&L(A.timeout)?{tool:"bash",args:{command:A.command,...A.timeout===void 0?{}:{timeout:Number(A.timeout)}}}:null;if(typeof A.path!=="string"||A.path.length>K)return null;if(x.tool==="read")return W(A,["path","offset","limit"])&&L(A.offset)&&L(A.limit)?{tool:"read",args:{path:A.path,...A.offset===void 0?{}:{offset:Number(A.offset)},...A.limit===void 0?{}:{limit:Number(A.limit)}}}:null;if(x.tool==="write")return W(A,["path","content"])&&typeof A.content==="string"&&A.path.length+A.content.length<=D?{tool:"write",args:{path:A.path,content:A.content}}:null;if(x.tool!=="edit"||!W(A,["path","edits"])||!Array.isArray(A.edits))return null;let B=A.path.length,N=[];for(let I of A.edits){if(!F(I)||!W(I,["oldText","newText"])||typeof I.oldText!=="string"||typeof I.newText!=="string")return null;if(B+=I.oldText.length+I.newText.length,B>D)return null;N.push({oldText:I.oldText,newText:I.newText})}return{tool:"edit",args:{path:A.path,edits:N}}}function WA(x){if(!F(x))return null;if("thrown"in x)return W(x,["thrown"])&&typeof x.thrown==="string"?{thrown:x.thrown}:null;let A=x.structuredContent;if(!W(x,["content","details","structuredContent","isError"])||!Array.isArray(x.content)||x.isError!==void 0&&x.isError!==!0||A!==void 0&&(!F(A)||!W(A,["output","truncated","full_output_path","exit_code","wall_time_seconds"])||typeof A.output!=="string"||typeof A.truncated!=="boolean"||A.full_output_path!==void 0&&typeof A.full_output_path!=="string"||typeof A.exit_code!=="number"||typeof A.wall_time_seconds!=="number"))return null;let B=[];for(let N of x.content)if(F(N)&&N.type==="text"&&W(N,["type","text"])&&typeof N.text==="string")B.push({type:"text",text:N.text});else if(F(N)&&N.type==="image"&&W(N,["type","data","mimeType"])&&typeof N.data==="string"&&typeof N.mimeType==="string")B.push({type:"image",data:N.data,mimeType:N.mimeType});else return null;return{content:B,...x.details===void 0?{}:{details:x.details},...F(A)?{structuredContent:{output:String(A.output),truncated:A.truncated===!0,...typeof A.full_output_path==="string"?{full_output_path:A.full_output_path}:{},exit_code:Number(A.exit_code),wall_time_seconds:Number(A.wall_time_seconds)}}:{},...x.isError===!0?{isError:!0}:{}}}function GA(x){let A=Z(x);if(!F(A)||!W(A,["version","generation","id","ok","exitCode","stdout","stderr","cwd","error","resumed","browserActions","automaticProgressImage","piToolOutcome","workerElapsedMs","environmentWaitMs"])||A.version!==X||!V(A.generation)||!M(A.id)||typeof A.ok!=="boolean"||!Number.isSafeInteger(A.exitCode)||Number(A.exitCode)<0||Number(A.exitCode)>255||typeof A.stdout!=="string"||A.stdout.length>Q||typeof A.stderr!=="string"||A.stderr.length>Q||A.cwd!==void 0&&(typeof A.cwd!=="string"||A.cwd.length<1||A.cwd.length>4096||!A.cwd.startsWith("/")||A.cwd.includes("\x00"))||A.error!==void 0&&(typeof A.error!=="string"||A.error.length<1||A.error.length>j||!u.has(A.error))||A.browserActions!==void 0&&!R(A.browserActions)||A.automaticProgressImage!==void 0&&(A.automaticProgressImage!==!0||!A.ok)||A.resumed!==void 0&&A.resumed!==!0||A.workerElapsedMs!==void 0&&(!Number.isSafeInteger(A.workerElapsedMs)||Number(A.workerElapsedMs)<0)||A.environmentWaitMs!==void 0&&(!Number.isSafeInteger(A.environmentWaitMs)||Number(A.environmentWaitMs)<0)||A.ok&&(A.exitCode!==0||A.error!==void 0)||!A.ok&&A.exitCode===0)throw new G("invalid_result");let B=A.piToolOutcome===void 0?void 0:WA(A.piToolOutcome);if(B===null||B&&!A.ok)throw new G("invalid_result");return{version:X,generation:A.generation,id:A.id,ok:A.ok,exitCode:Number(A.exitCode),stdout:A.stdout,stderr:A.stderr,...typeof A.cwd==="string"?{cwd:A.cwd}:{},...A.browserActions!==void 0?{browserActions:R(A.browserActions)}:{},...typeof A.error==="string"?{error:A.error}:{},...A.automaticProgressImage===!0?{automaticProgressImage:!0}:{},...A.resumed===!0?{resumed:!0}:{},...B?{piToolOutcome:B}:{},...A.workerElapsedMs!==void 0?{workerElapsedMs:Number(A.workerElapsedMs)}:{},...A.environmentWaitMs!==void 0?{environmentWaitMs:Number(A.environmentWaitMs)}:{}}}function NA(x){let A=Z(x);if(!F(A)||!W(A,["type","version","generation","id","sequence","stdout","stderr"])||A.type!=="progress"||A.version!==X||!V(A.generation)||!M(A.id)||!Number.isSafeInteger(A.sequence)||Number(A.sequence)<1||typeof A.stdout!=="string"||A.stdout.length>Q||typeof A.stderr!=="string"||A.stderr.length>Q)throw new G("invalid_progress");return{type:"progress",version:X,generation:Number(A.generation),id:A.id,sequence:Number(A.sequence),stdout:A.stdout,stderr:A.stderr}}function UA(x){let A=Z(x);if(!F(A)||!W(A,["type","version","generation","fenceId","executorLaunchId","requestCancelVersion","managedJobsVersion","browserRunEnvelopeVersion","terminalCleanupVersion","guestMemoryVersion","guestMemoryDiagnosticsVersion","piToolsVersion","piToolsConfinement","backgroundBashVersion","machineSdkVersion","executionTimingVersion","environmentWaitVersion"])||A.type!=="claim"||A.version!==X||!V(A.generation)||!$(A.fenceId)||!$(A.executorLaunchId)||A.requestCancelVersion!==void 0&&A.requestCancelVersion!==1||A.managedJobsVersion!==void 0&&A.managedJobsVersion!==f||A.guestMemoryVersion!==void 0&&A.guestMemoryVersion!==1||A.guestMemoryDiagnosticsVersion!==void 0&&(A.guestMemoryDiagnosticsVersion!==1||A.guestMemoryVersion!==1)||A.terminalCleanupVersion!==void 0&&A.terminalCleanupVersion!==1||A.browserRunEnvelopeVersion!==void 0&&A.browserRunEnvelopeVersion!==1||A.piToolsVersion!==void 0&&A.piToolsVersion!==1||A.piToolsConfinement!==void 0&&(!Y(A.piToolsConfinement)||A.piToolsVersion!==1)||A.backgroundBashVersion!==void 0&&A.backgroundBashVersion!==1||A.machineSdkVersion!==void 0&&A.machineSdkVersion!==1||A.executionTimingVersion!==void 0&&A.executionTimingVersion!==1||A.environmentWaitVersion!==void 0&&(A.environmentWaitVersion!==1||A.executionTimingVersion!==1))throw new G("invalid_claim");return{type:"claim",version:X,generation:A.generation,fenceId:A.fenceId,executorLaunchId:A.executorLaunchId,...A.requestCancelVersion===1?{requestCancelVersion:1}:{},...A.managedJobsVersion===1?{managedJobsVersion:1}:{},...A.guestMemoryVersion===1?{guestMemoryVersion:1}:{},...A.guestMemoryDiagnosticsVersion===1?{guestMemoryDiagnosticsVersion:1}:{},...A.terminalCleanupVersion===1?{terminalCleanupVersion:1}:{},...A.browserRunEnvelopeVersion===1?{browserRunEnvelopeVersion:1}:{},...A.piToolsVersion===1?{piToolsVersion:1}:{},...Y(A.piToolsConfinement)?{piToolsConfinement:{template:A.piToolsConfinement.template,quoteDepth:A.piToolsConfinement.quoteDepth}}:{},...A.backgroundBashVersion===1?{backgroundBashVersion:1}:{},...A.machineSdkVersion===1?{machineSdkVersion:1}:{},...A.executionTimingVersion===1?{executionTimingVersion:1}:{},...A.environmentWaitVersion===1?{environmentWaitVersion:1}:{}}}function FA(x){let A=Z(x);if(!F(A)||!W(A,["type","version","generation","fenceId","executorLaunchId","workerVersion","workerArtifactSha256","requestCancelVersion","managedJobsVersion","lifecycleVersion","browserRunEnvelopeVersion","terminalCleanupVersion","guestMemoryVersion","guestMemoryDiagnosticsVersion","piToolsVersion","piToolsConfinementVersion","backgroundBashVersion","machineSdkVersion","executionTimingVersion","environmentWaitVersion"])||A.lifecycleVersion!==void 0&&A.lifecycleVersion!==1||A.piToolsVersion!==void 0&&A.piToolsVersion!==1||A.piToolsConfinementVersion!==void 0&&(A.piToolsConfinementVersion!==1||A.piToolsVersion!==1)||A.backgroundBashVersion!==void 0&&A.backgroundBashVersion!==1||A.machineSdkVersion!==void 0&&A.machineSdkVersion!==1||A.executionTimingVersion!==void 0&&A.executionTimingVersion!==1||A.environmentWaitVersion!==void 0&&(A.environmentWaitVersion!==1||A.executionTimingVersion!==1)||A.guestMemoryVersion!==void 0&&A.guestMemoryVersion!==1||A.guestMemoryDiagnosticsVersion!==void 0&&(A.guestMemoryDiagnosticsVersion!==1||A.guestMemoryVersion!==1)||A.terminalCleanupVersion!==void 0&&A.terminalCleanupVersion!==1||A.browserRunEnvelopeVersion!==void 0&&A.browserRunEnvelopeVersion!==1||A.type!=="claim_ack"||A.version!==X||!V(A.generation)||!$(A.fenceId)||!$(A.executorLaunchId)||!Number.isSafeInteger(A.workerVersion)||Number(A.workerVersion)<1||!S(A.workerArtifactSha256)||A.requestCancelVersion!==void 0&&A.requestCancelVersion!==1||A.managedJobsVersion!==void 0&&A.managedJobsVersion!==f)throw new G("invalid_claim_ack");return{type:"claim_ack",...A.guestMemoryVersion===1?{guestMemoryVersion:1}:{},...A.guestMemoryDiagnosticsVersion===1?{guestMemoryDiagnosticsVersion:1}:{},...A.terminalCleanupVersion===1?{terminalCleanupVersion:1}:{},...A.browserRunEnvelopeVersion===1?{browserRunEnvelopeVersion:1}:{},...A.lifecycleVersion===1?{lifecycleVersion:1}:{},...A.piToolsVersion===1?{piToolsVersion:1}:{},...A.piToolsConfinementVersion===1?{piToolsConfinementVersion:1}:{},...A.backgroundBashVersion===1?{backgroundBashVersion:1}:{},...A.machineSdkVersion===1?{machineSdkVersion:1}:{},...A.executionTimingVersion===1?{executionTimingVersion:1}:{},...A.environmentWaitVersion===1?{environmentWaitVersion:1}:{},version:X,generation:A.generation,fenceId:A.fenceId,executorLaunchId:A.executorLaunchId,workerVersion:Number(A.workerVersion),workerArtifactSha256:A.workerArtifactSha256,...A.requestCancelVersion===1?{requestCancelVersion:1}:{},...A.managedJobsVersion===1?{managedJobsVersion:1}:{}}}function zA(x){let A=Z(x);if(!F(A)||!W(A,["type","version","generation","id","jobId","action","input"])||A.type!=="job"||A.version!==X||!V(A.generation)||!M(A.id)||!M(A.jobId)||!F(A.input))throw new G("invalid_job_request");let B=A.input,N=Number.isSafeInteger(B.leaseExpiresAtMs)&&Number(B.leaseExpiresAtMs)>0,I=Number.isSafeInteger(B.sequence)&&Number(B.sequence)>=1;if(!(A.action==="start"?B.mode==="pty"?W(B,["mode","cols","rows","leaseExpiresAtMs"])&&C(A.jobId)&&z(B)&&N:W(B,["script","leaseExpiresAtMs"])&&typeof B.script==="string"&&B.script.length<=K&&N:A.action==="inspect"?W(B,["after"])&&Number.isSafeInteger(B.after)&&Number(B.after)>=0:A.action==="input"?"dataBase64"in B?W(B,["sequence","dataBase64"])&&C(A.jobId)&&I&&H(B.dataBase64)>0:W(B,["sequence","data","eof"])&&I&&typeof B.data==="string"&&B.data.length<=b&&typeof B.eof==="boolean":A.action==="resize"?W(B,["sequence","cols","rows"])&&C(A.jobId)&&I&&z(B):A.action==="renew"?W(B,["leaseExpiresAtMs"])&&N:A.action==="cancel"&&W(B,[])))throw new G("invalid_job_request");return A}function IA(x){let A=Z(x);if(!F(A)||!W(A,["type","version","generation","id","ok","job","error"])||A.type!=="job_result"||A.version!==X||!V(A.generation)||!M(A.id))throw new G("invalid_job_result");if(A.ok===!1&&A.job===void 0&&typeof A.error==="string"&&AA.some((U)=>U===A.error))return A;let B=A.job;if(A.ok!==!0||A.error!==void 0||!F(B)||!W(B,["jobId","state","startedAtMs","finishedAtMs","leaseExpiresAtMs","exitCode","inputSequence","output","firstCursor","nextCursor","truncated","process","environmentRevision","environmentSnapshotId","pty"])||!M(B.jobId)||!["starting","running","exited","cancelled","expired","uncertain"].includes(String(B.state))||!Number.isSafeInteger(B.startedAtMs)||Number(B.startedAtMs)<1||!Number.isSafeInteger(B.leaseExpiresAtMs)||Number(B.leaseExpiresAtMs)<1||B.finishedAtMs!==null&&(!Number.isSafeInteger(B.finishedAtMs)||Number(B.finishedAtMs)<Number(B.startedAtMs))||B.exitCode!==null&&(!Number.isSafeInteger(B.exitCode)||Number(B.exitCode)<0||Number(B.exitCode)>255)||!Number.isSafeInteger(B.inputSequence)||Number(B.inputSequence)<0||!Number.isSafeInteger(B.firstCursor)||Number(B.firstCursor)<1||!Number.isSafeInteger(B.nextCursor)||Number(B.nextCursor)<Number(B.firstCursor)-1||typeof B.truncated!=="boolean"||!Array.isArray(B.output)||B.output.length>w)throw new G("invalid_job_result");if(B.environmentRevision===void 0!==(B.environmentSnapshotId===void 0)||B.environmentRevision!==void 0&&(!Number.isSafeInteger(B.environmentRevision)||Number(B.environmentRevision)<1||!$(B.environmentSnapshotId)))throw new G("invalid_job_result");let N=Number(B.firstCursor)-1,I=0;for(let U of B.output){if(!F(U)||!W(U,["cursor","stream","text"])||!Number.isSafeInteger(U.cursor)||Number(U.cursor)<=N||Number(U.cursor)>Number(B.nextCursor)||!["stdout","stderr"].includes(String(U.stream))||typeof U.text!=="string")throw new G("invalid_job_result");I+=U.text.length,N=Number(U.cursor)}if(I>p)throw new G("invalid_job_result");let _=B.state==="starting"||B.state==="running";if(_&&(B.finishedAtMs!==null||B.exitCode!==null)||!_&&B.finishedAtMs===null||B.state==="uncertain"&&B.exitCode!==null||B.state==="exited"&&B.exitCode===null||B.state==="cancelled"&&B.exitCode!==130||B.state==="expired"&&B.exitCode!==124)throw new G("invalid_job_result");if(B.process!==void 0){let U=B.process;if(!F(U)||!W(U,["pid","processGroupId","executorLaunchId"])||!Number.isSafeInteger(U.pid)||Number(U.pid)<1||U.processGroupId!==U.pid||!$(U.executorLaunchId)||!["starting","running"].includes(String(B.state)))throw new G("invalid_job_result")}if(B.pty!==void 0){let U=B.pty;if(!F(U)||!W(U,["version","cols","rows","output","cleanup"])||U.version!==h||!C(B.jobId)||!z(U)||B.output.length!==0||!Array.isArray(U.output)||U.output.length>w||(_?U.cleanup!=="pending":B.state==="uncertain"?U.cleanup!=="unconfirmed":U.cleanup!=="confirmed")||B.state==="running"&&(B.process===void 0||B.environmentRevision===void 0))throw new G("invalid_job_result");let T=Number(B.firstCursor)-1,g=0;for(let J of U.output){if(!F(J)||!W(J,["cursor","dataBase64"])||!Number.isSafeInteger(J.cursor)||Number(J.cursor)<=T||Number(J.cursor)>Number(B.nextCursor))throw new G("invalid_job_result");let q=H(J.dataBase64);if(q<=0||(g+=q)>d)throw new G("invalid_job_result");T=Number(J.cursor)}}return A}function SA(x){if(k(x)>i)throw new G("frame_too_large");let A=Z(x);if(!F(A)||!W(A,["version","sessionId","operationId","runId","deviceId","rootId","workspace","binding","targetRevision","rootGrantRevision","generation","fenceId","executorLaunchId","job"])||A.version!==h||![A.sessionId,A.operationId,A.runId].every(M)||![A.deviceId,A.rootId,A.fenceId,A.executorLaunchId].every($)||!V(A.generation)||!Number.isSafeInteger(A.rootGrantRevision)||Number(A.rootGrantRevision)<1||!["workspace_source","mcp_control"].includes(String(A.binding))||!Number.isSafeInteger(A.targetRevision)||Number(A.targetRevision)<0||A.binding==="workspace_source"&&A.targetRevision!==0||!F(A.workspace))throw new G("invalid_pty_receipt");if(!m(A.workspace))throw new G("invalid_pty_receipt");let B=IA(JSON.stringify({type:"job_result",version:X,generation:A.generation,id:A.operationId,ok:!0,job:A.job}));if(!B.ok||!B.job.pty||B.job.pty.output.length!==0||B.job.process&&B.job.process.executorLaunchId!==A.executorLaunchId)throw new G("invalid_pty_receipt");return A}function TA(x){let A=Z(x);if(!F(A)||!W(A,["type","version","generation","id","targetId"])||A.type!=="cancel_request"||A.version!==X||!V(A.generation)||!M(A.id)||!M(A.targetId))throw new G("invalid_cancel_request");return A}function qA(x){let A=Z(x);if(!F(A)||!W(A,["type","version","generation","id","targetId","status"])||A.type!=="cancel_ack"||A.version!==X||!V(A.generation)||!M(A.id)||!M(A.targetId)||!["cancelled","settled","not_found","unsupported","unconfirmed"].includes(String(A.status)))throw new G("invalid_cancel_ack");return A}function wA(x){let A=JSON.stringify(x);return xA(A),A}function yA(x){let A=JSON.stringify(x);return GA(A),A}function mA(x){let A=JSON.stringify(x);return NA(A),A}function fA(x){let A=JSON.stringify(x);return UA(A),A}function hA(x){let A=JSON.stringify(x);return FA(A),A}function O(x){return typeof x==="string"&&x.length>=1&&x.length<=a&&!x.includes("\x00")}function XA(x){let A=["type","version","generation","id","jobRequestId","verb"];if(x.verb==="help")return W(x,A)?{verb:"help"}:null;if(x.verb==="describe"||x.verb==="namespace")return W(x,[...A,"name"])&&O(x.name)?{verb:x.verb,name:x.name}:null;if(x.verb==="search"){let B=x.args;if(!W(x,[...A,"query","args"])||typeof x.query!=="string"||x.query.trim().length<1||x.query.length>e)return null;if(B===void 0)return{verb:"search",query:x.query};if(!F(B)||!W(B,["namespace","limit"])||B.namespace!==void 0&&!O(B.namespace)||B.limit!==void 0&&(!Number.isSafeInteger(B.limit)||Number(B.limit)<1||Number(B.limit)>50))return null;return{verb:"search",query:x.query,args:{...typeof B.namespace==="string"?{namespace:B.namespace}:{},...B.limit===void 0?{}:{limit:Number(B.limit)}}}}if(x.verb!=="call"||!W(x,[...A,"name","args"])||!O(x.name)||!F(x.args)||JSON.stringify(x.args).length>K)return null;return{verb:"call",name:x.name,args:x.args}}function kA(x){let A=Z(x);if(!F(A)||A.type!=="sdk_request"||A.version!==X||!V(A.generation)||!M(A.id)||!M(A.jobRequestId))throw new G("invalid_sdk_request");let B=XA(A);if(!B)throw new G("invalid_sdk_request");return{type:"sdk_request",version:X,generation:Number(A.generation),id:A.id,jobRequestId:A.jobRequestId,...B}}function MA(x){let A=Z(x);if(!F(A)||A.type!=="sdk_response"||A.version!==X||!V(A.generation)||!M(A.id))throw new G("invalid_sdk_response");let B={type:"sdk_response",version:X,generation:Number(A.generation),id:A.id},N=["type","version","generation","id","ok"];if(A.ok===!0&&W(A,[...N,"result"])&&typeof A.result==="string"&&A.result.length<=Q)return{...B,ok:!0,result:A.result};if(A.ok===!1&&W(A,[...N,"error"])&&typeof A.error==="string"&&A.error.length>=1&&A.error.length<=Q)return{...B,ok:!1,error:A.error};throw new G("invalid_sdk_response")}function HA(x){let A=JSON.stringify(x);return MA(A),A}
4
- export{VA as ef,$A as ff,JA as gf,X as hf,P as if,K as jf,D as kf,Q as lf,DA as mf,j as nf,f as of,b as pf,p as qf,w as rf,RA as sf,i as tf,h as uf,y as vf,d as wf,YA as xf,s as yf,c as zf,n as Af,LA as Bf,o as Cf,OA as Df,l as Ef,a as Ff,e as Gf,AA as Hf,G as If,M as Jf,V as Kf,$ as Lf,C as Mf,S as Nf,xA as Of,GA as Pf,NA as Qf,UA as Rf,FA as Sf,zA as Tf,IA as Uf,SA as Vf,TA as Wf,qA as Xf,wA as Yf,yA as Zf,mA as _f,fA as $f,hA as ag,kA as bg,MA as cg,HA as dg};
4
+ export{VA as gf,$A as hf,JA as if,X as jf,P as kf,K as lf,D as mf,Q as nf,DA as of,j as pf,f as qf,b as rf,p as sf,w as tf,RA as uf,i as vf,h as wf,y as xf,d as yf,YA as zf,s as Af,c as Bf,n as Cf,LA as Df,o as Ef,OA as Ff,l as Gf,a as Hf,e as If,AA as Jf,G as Kf,M as Lf,V as Mf,$ as Nf,C as Of,S as Pf,xA as Qf,GA as Rf,NA as Sf,UA as Tf,FA as Uf,zA as Vf,IA as Wf,SA as Xf,TA as Yf,qA as Zf,wA as _f,yA as $f,mA as ag,fA as bg,hA as cg,kA as dg,MA as eg,HA as fg};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Gh as l}from"./vm-hands-entry-lite-ffg7rf02.js";import{execFile as zj,spawn as I}from"child_process";var Cj="h264_ws_v1",kj="video",h=["smooth","sharp","data_saver","balanced"];var Yj="video_presets";var V=8388608,Y=65536,Lj="control",Aj="v1",d=200;function s(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q,J=(Q)=>typeof Q==="string"&&Q.length>0&&Q.length<=d;if(Object.keys(j).length!==2||!J(j.user_id)||!J(j.name))return null;return{user_id:j.user_id,name:j.name}}var xj="windows",Mj="v1",A=200,o=(q)=>typeof q==="string"&&h.includes(q);function fj(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q;if(Object.keys(j).length!==2||j.format!=="h264_ws_v1"||!o(j.preset))return null;return{format:"h264_ws_v1",preset:j.preset}}var $={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23};class U extends Error{constructor(q){super(q);this.name="DisplayVideoProtocolError"}}var e=new TextEncoder,jj=new TextDecoder("utf-8",{fatal:!0});function H(q,j){if(j.byteLength+1>V)throw new U("message_too_large");let J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,j.byteLength+1),Q.setUint8(4,q),J.set(j,5),J}function R(q){let j=e.encode(q);if(j.byteLength>Y)throw new U("text_too_large");return j}function f(q,j){if(!Number.isInteger(q)||q<0||q>65535)throw new U(`invalid_${j}`);return q}function qj(q){if(!Number.isFinite(q))throw new U("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(q)))}function hj(q){switch(q.type){case"hello":{let j=R(q.codec),J=new Uint8Array(6+j.byteLength),Q=new DataView(J.buffer);return Q.setUint16(0,f(q.width,"width")),Q.setUint16(2,f(q.height,"height")),Q.setUint8(4,Math.max(1,Math.min(240,Math.round(q.fps)))),Q.setUint8(5,h.indexOf(q.preset)),J.set(j,6),H($.hello,J)}case"frame":{let j=new Uint8Array(13+q.data.byteLength),J=new DataView(j.buffer);return J.setUint8(0,q.key?1:0),J.setUint32(1,q.seq>>>0),J.setBigUint64(5,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,13),H($.frame,j)}case"stats":return H($.stats,R(JSON.stringify(q.stats)));case"pong":case"ping":{let j=new Uint8Array(8);return new DataView(j.buffer).setFloat64(0,q.token),H(q.type==="ping"?$.ping:$.pong,j)}case"serverClipboard":return H($.serverClipboard,R(q.text));case"clientClipboard":return H($.clientClipboard,R(q.text));case"error":return H($.error,R(q.code));case"pointer":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint16(0,f(q.x,"x")),J.setUint16(2,f(q.y,"y")),J.setUint8(4,q.buttons&255),H($.pointer,j)}case"key":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint8(0,q.down?1:0),J.setUint32(1,q.keysym>>>0),H($.key,j)}case"config":return H($.config,Uint8Array.of(h.indexOf(q.preset)));case"keyframeRequest":return H($.keyframeRequest,new Uint8Array(0));case"audioHello":{let j=R(q.codec),J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,q.sampleRate>>>0),Q.setUint8(4,q.channels&255),J.set(j,5),H($.audioHello,J)}case"audio":{let j=new Uint8Array(8+q.data.byteLength);return new DataView(j.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,8),H($.audio,j)}case"control":return H($.control,R(JSON.stringify(q.control)));case"windows":{let j=q.bounds.slice(0,A),J=new Uint8Array(j.length*16),Q=new DataView(J.buffer);return j.forEach((Z,z)=>{[Z.x,Z.y,Z.width,Z.height].forEach((G,F)=>Q.setInt32(z*16+F*4,qj(G)))}),H($.windows,J)}case"audioEnable":return H($.audioEnable,Uint8Array.of(q.on?1:0));case"ack":{let j=new Uint8Array(4);return new DataView(j.buffer).setUint32(0,q.seq>>>0),H($.ack,j)}}}function T(q){let j=h[q];if(!j)throw new U("invalid_preset");return j}function C(q,j){if(q.byteLength!==j)throw new U("invalid_length")}function k(q){if(q.byteLength>Y)throw new U("text_too_large");try{return jj.decode(q)}catch{throw new U("invalid_text")}}function Jj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_stats")}let J=j;if(!J||typeof J!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((Z)=>typeof J[Z]!=="number"||!Number.isFinite(J[Z])))throw new U("invalid_stats");return{fps:J.fps,kbps:J.kbps,dropped:J.dropped,restarts:J.restarts,queued_bytes:J.queued_bytes}}function Qj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_control")}let J=j;if(!J||typeof J!=="object"||typeof J.you!=="boolean"||typeof J.same_user!=="boolean")throw new U("invalid_control");let Q=J.holder===null?null:s(J.holder);if(Q===null&&J.holder!==null)throw new U("invalid_control");return{holder:Q,you:J.you,same_user:J.same_user}}function Zj(q,j){let J=new DataView(j.buffer,j.byteOffset,j.byteLength);switch(q){case $.hello:if(j.byteLength<6)throw new U("invalid_length");return{type:"hello",width:J.getUint16(0),height:J.getUint16(2),fps:J.getUint8(4),preset:T(J.getUint8(5)),codec:k(j.subarray(6))};case $.frame:if(j.byteLength<14)throw new U("invalid_length");if(J.getUint8(0)>1)throw new U("invalid_frame_flags");return{type:"frame",key:J.getUint8(0)===1,seq:J.getUint32(1),captureMicros:Number(J.getBigUint64(5)),data:j.subarray(13)};case $.stats:return{type:"stats",stats:Jj(j)};case $.ping:case $.pong:return C(j,8),{type:q===$.ping?"ping":"pong",token:J.getFloat64(0)};case $.serverClipboard:return{type:"serverClipboard",text:k(j)};case $.clientClipboard:return{type:"clientClipboard",text:k(j)};case $.error:return{type:"error",code:k(j)};case $.pointer:return C(j,5),{type:"pointer",x:J.getUint16(0),y:J.getUint16(2),buttons:J.getUint8(4)};case $.key:if(C(j,5),J.getUint8(0)>1)throw new U("invalid_key_flags");return{type:"key",down:J.getUint8(0)===1,keysym:J.getUint32(1)};case $.config:return C(j,1),{type:"config",preset:T(J.getUint8(0))};case $.keyframeRequest:return C(j,0),{type:"keyframeRequest"};case $.audioHello:if(j.byteLength<5)throw new U("invalid_length");return{type:"audioHello",sampleRate:J.getUint32(0),channels:J.getUint8(4),codec:k(j.subarray(5))};case $.audio:if(j.byteLength<9)throw new U("invalid_length");return{type:"audio",captureMicros:Number(J.getBigUint64(0)),data:j.subarray(8)};case $.audioEnable:if(C(j,1),J.getUint8(0)>1)throw new U("invalid_audio_flags");return{type:"audioEnable",on:J.getUint8(0)===1};case $.control:return{type:"control",control:Qj(j)};case $.windows:{if(j.byteLength%16!==0||j.byteLength>A*16)throw new U("invalid_length");let Q=[];for(let Z=0;Z<j.byteLength;Z+=16)Q.push({x:J.getInt32(Z),y:J.getInt32(Z+4),width:J.getInt32(Z+8),height:J.getInt32(Z+12)});return{type:"windows",bounds:Q}}case $.ack:return C(j,4),{type:"ack",seq:J.getUint32(0)};default:return null}}class $j{buffer=new Uint8Array(0);push(q){let j=new Uint8Array(this.buffer.byteLength+q.byteLength);j.set(this.buffer),j.set(q,this.buffer.byteLength);let J=[],Q=0;while(j.byteLength-Q>=4){let Z=new DataView(j.buffer,j.byteOffset+Q,4).getUint32(0);if(Z<1||Z>V)throw new U("invalid_message_length");if(j.byteLength-Q-4<Z)break;let z=j[Q+4],G=j.slice(Q+5,Q+4+Z),F=Zj(z,G);if(F)J.push(F);Q+=4+Z}return this.buffer=j.slice(Q),J}}var t="/usr/bin/osascript",Gj=5000,Kj=1048576,Uj=String.raw`
2
+ import{Ih as l}from"./vm-hands-entry-lite-wffqkcjq.js";import{execFile as zj,spawn as I}from"child_process";var Cj="h264_ws_v1",kj="video",h=["smooth","sharp","data_saver","balanced"];var Yj="video_presets";var V=8388608,Y=65536,Lj="control",Aj="v1",d=200;function s(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q,J=(Q)=>typeof Q==="string"&&Q.length>0&&Q.length<=d;if(Object.keys(j).length!==2||!J(j.user_id)||!J(j.name))return null;return{user_id:j.user_id,name:j.name}}var xj="windows",Mj="v1",A=200,o=(q)=>typeof q==="string"&&h.includes(q);function fj(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q;if(Object.keys(j).length!==2||j.format!=="h264_ws_v1"||!o(j.preset))return null;return{format:"h264_ws_v1",preset:j.preset}}var $={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23};class U extends Error{constructor(q){super(q);this.name="DisplayVideoProtocolError"}}var e=new TextEncoder,jj=new TextDecoder("utf-8",{fatal:!0});function H(q,j){if(j.byteLength+1>V)throw new U("message_too_large");let J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,j.byteLength+1),Q.setUint8(4,q),J.set(j,5),J}function R(q){let j=e.encode(q);if(j.byteLength>Y)throw new U("text_too_large");return j}function f(q,j){if(!Number.isInteger(q)||q<0||q>65535)throw new U(`invalid_${j}`);return q}function qj(q){if(!Number.isFinite(q))throw new U("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(q)))}function hj(q){switch(q.type){case"hello":{let j=R(q.codec),J=new Uint8Array(6+j.byteLength),Q=new DataView(J.buffer);return Q.setUint16(0,f(q.width,"width")),Q.setUint16(2,f(q.height,"height")),Q.setUint8(4,Math.max(1,Math.min(240,Math.round(q.fps)))),Q.setUint8(5,h.indexOf(q.preset)),J.set(j,6),H($.hello,J)}case"frame":{let j=new Uint8Array(13+q.data.byteLength),J=new DataView(j.buffer);return J.setUint8(0,q.key?1:0),J.setUint32(1,q.seq>>>0),J.setBigUint64(5,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,13),H($.frame,j)}case"stats":return H($.stats,R(JSON.stringify(q.stats)));case"pong":case"ping":{let j=new Uint8Array(8);return new DataView(j.buffer).setFloat64(0,q.token),H(q.type==="ping"?$.ping:$.pong,j)}case"serverClipboard":return H($.serverClipboard,R(q.text));case"clientClipboard":return H($.clientClipboard,R(q.text));case"error":return H($.error,R(q.code));case"pointer":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint16(0,f(q.x,"x")),J.setUint16(2,f(q.y,"y")),J.setUint8(4,q.buttons&255),H($.pointer,j)}case"key":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint8(0,q.down?1:0),J.setUint32(1,q.keysym>>>0),H($.key,j)}case"config":return H($.config,Uint8Array.of(h.indexOf(q.preset)));case"keyframeRequest":return H($.keyframeRequest,new Uint8Array(0));case"audioHello":{let j=R(q.codec),J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,q.sampleRate>>>0),Q.setUint8(4,q.channels&255),J.set(j,5),H($.audioHello,J)}case"audio":{let j=new Uint8Array(8+q.data.byteLength);return new DataView(j.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,8),H($.audio,j)}case"control":return H($.control,R(JSON.stringify(q.control)));case"windows":{let j=q.bounds.slice(0,A),J=new Uint8Array(j.length*16),Q=new DataView(J.buffer);return j.forEach((Z,z)=>{[Z.x,Z.y,Z.width,Z.height].forEach((G,F)=>Q.setInt32(z*16+F*4,qj(G)))}),H($.windows,J)}case"audioEnable":return H($.audioEnable,Uint8Array.of(q.on?1:0));case"ack":{let j=new Uint8Array(4);return new DataView(j.buffer).setUint32(0,q.seq>>>0),H($.ack,j)}}}function T(q){let j=h[q];if(!j)throw new U("invalid_preset");return j}function C(q,j){if(q.byteLength!==j)throw new U("invalid_length")}function k(q){if(q.byteLength>Y)throw new U("text_too_large");try{return jj.decode(q)}catch{throw new U("invalid_text")}}function Jj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_stats")}let J=j;if(!J||typeof J!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((Z)=>typeof J[Z]!=="number"||!Number.isFinite(J[Z])))throw new U("invalid_stats");return{fps:J.fps,kbps:J.kbps,dropped:J.dropped,restarts:J.restarts,queued_bytes:J.queued_bytes}}function Qj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_control")}let J=j;if(!J||typeof J!=="object"||typeof J.you!=="boolean"||typeof J.same_user!=="boolean")throw new U("invalid_control");let Q=J.holder===null?null:s(J.holder);if(Q===null&&J.holder!==null)throw new U("invalid_control");return{holder:Q,you:J.you,same_user:J.same_user}}function Zj(q,j){let J=new DataView(j.buffer,j.byteOffset,j.byteLength);switch(q){case $.hello:if(j.byteLength<6)throw new U("invalid_length");return{type:"hello",width:J.getUint16(0),height:J.getUint16(2),fps:J.getUint8(4),preset:T(J.getUint8(5)),codec:k(j.subarray(6))};case $.frame:if(j.byteLength<14)throw new U("invalid_length");if(J.getUint8(0)>1)throw new U("invalid_frame_flags");return{type:"frame",key:J.getUint8(0)===1,seq:J.getUint32(1),captureMicros:Number(J.getBigUint64(5)),data:j.subarray(13)};case $.stats:return{type:"stats",stats:Jj(j)};case $.ping:case $.pong:return C(j,8),{type:q===$.ping?"ping":"pong",token:J.getFloat64(0)};case $.serverClipboard:return{type:"serverClipboard",text:k(j)};case $.clientClipboard:return{type:"clientClipboard",text:k(j)};case $.error:return{type:"error",code:k(j)};case $.pointer:return C(j,5),{type:"pointer",x:J.getUint16(0),y:J.getUint16(2),buttons:J.getUint8(4)};case $.key:if(C(j,5),J.getUint8(0)>1)throw new U("invalid_key_flags");return{type:"key",down:J.getUint8(0)===1,keysym:J.getUint32(1)};case $.config:return C(j,1),{type:"config",preset:T(J.getUint8(0))};case $.keyframeRequest:return C(j,0),{type:"keyframeRequest"};case $.audioHello:if(j.byteLength<5)throw new U("invalid_length");return{type:"audioHello",sampleRate:J.getUint32(0),channels:J.getUint8(4),codec:k(j.subarray(5))};case $.audio:if(j.byteLength<9)throw new U("invalid_length");return{type:"audio",captureMicros:Number(J.getBigUint64(0)),data:j.subarray(8)};case $.audioEnable:if(C(j,1),J.getUint8(0)>1)throw new U("invalid_audio_flags");return{type:"audioEnable",on:J.getUint8(0)===1};case $.control:return{type:"control",control:Qj(j)};case $.windows:{if(j.byteLength%16!==0||j.byteLength>A*16)throw new U("invalid_length");let Q=[];for(let Z=0;Z<j.byteLength;Z+=16)Q.push({x:J.getInt32(Z),y:J.getInt32(Z+4),width:J.getInt32(Z+8),height:J.getInt32(Z+12)});return{type:"windows",bounds:Q}}case $.ack:return C(j,4),{type:"ack",seq:J.getUint32(0)};default:return null}}class $j{buffer=new Uint8Array(0);push(q){let j=new Uint8Array(this.buffer.byteLength+q.byteLength);j.set(this.buffer),j.set(q,this.buffer.byteLength);let J=[],Q=0;while(j.byteLength-Q>=4){let Z=new DataView(j.buffer,j.byteOffset+Q,4).getUint32(0);if(Z<1||Z>V)throw new U("invalid_message_length");if(j.byteLength-Q-4<Z)break;let z=j[Q+4],G=j.slice(Q+5,Q+4+Z),F=Zj(z,G);if(F)J.push(F);Q+=4+Z}return this.buffer=j.slice(Q),J}}var t="/usr/bin/osascript",Gj=5000,Kj=1048576,Uj=String.raw`
3
3
  ObjC.import("CoreGraphics");
4
4
  ObjC.import("ApplicationServices");
5
5
  ObjC.import("AppKit");
@@ -109,4 +109,4 @@ function run() {
109
109
  `);X>=0;X=B.indexOf(`
110
110
  `)){let S=B.slice(0,X);if(B=B.slice(X+1),!S.startsWith("c "))continue;let O=S.slice(2);if(O.length>Math.ceil(Y/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(O)){K({reason:"display_protocol"});return}let _=Buffer.from(O,"base64");if(_.byteLength<=Y)q.clipboard(_.toString("utf8"));if(z)return}if(B.length>Math.ceil(Y/3)*4+2)K({reason:"display_protocol"})}),G.once("error",()=>W("Reason could not watch this Mac's desktop clipboard.")),G.once("exit",()=>{if(!z)W("Reason could not watch this Mac's desktop clipboard.")})};return J.stdout.on("data",(B)=>{if(z||Z===null)return;Z+=B.toString("utf8");let N=Z.indexOf(`
111
111
  `);if(N<0){if(Z.length>4096)K({reason:"display_protocol"});return}let X=y(Z.slice(0,N));if(Z=null,!X)K({reason:"display_protocol"});else if(!X.screen||!X.accessibility)W(j.length>0?"Reason's background worker needs Screen Recording and Accessibility on this Mac (its own Reason entry in System Settings > Privacy & Security, not the Reason app's): run `reason permissions allow` on this Mac.":"Allow Screen Recording and Accessibility for this Mac's Reason worker, then restart it.");else i(),q.ready({width:X.width,height:X.height})}),J.stdin.on("error",()=>{return}),J.once("error",()=>W("Reason could not start this Mac's desktop input.")),J.once("exit",()=>{if(Z!==null)W("Reason could not start this Mac's desktop input.");else K({reason:"display_closed"})}),{pointer:(B,N,X)=>L(Q.pointer(B,N,X)),key:(B,N)=>L(Q.key(B,N)),clipboard:(B)=>L([`c ${Buffer.from(B,"utf8").toString("base64")}`]),close(){z=!0,F()}}}
112
- export{Cj as yg,kj as zg,h as Ag,Yj as Bg,Y as Cg,Lj as Dg,Aj as Eg,s as Fg,xj as Gg,Mj as Hg,fj as Ig,hj as Jg,$j as Kg,y as Lg,Sj as Mg,_j as Ng,Hj as Og,Tj as Pg,a as Qg,Vj as Rg};
112
+ export{Cj as Ag,kj as Bg,h as Cg,Yj as Dg,Y as Eg,Lj as Fg,Aj as Gg,s as Hg,xj as Ig,Mj as Jg,fj as Kg,hj as Lg,$j as Mg,y as Ng,Sj as Og,_j as Pg,Hj as Qg,Tj as Rg,a as Sg,Vj as Tg};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{cf as Z8}from"./vm-hands-entry-lite-bfwf82rw.js";import{lf as R0}from"./vm-hands-entry-lite-ptmqg51y.js";import{gg as Kq}from"./vm-hands-entry-lite-25t4e0vk.js";import{Cg as p,Fg as V0,Ig as F0,Jg as C8,Kg as eq,Mg as g8,Pg as q0,Rg as x0}from"./vm-hands-entry-lite-s2xydt0n.js";import{Wg as wq}from"./vm-hands-entry-lite-s5qn1k80.js";import{Xg as o,Yg as C0}from"./vm-hands-entry-lite-9pmag2qk.js";import{jh as B0}from"./vm-hands-entry-lite-84aq8d12.js";import{zh as A0}from"./vm-hands-entry-lite-anaydk9m.js";import{Gh as Z}from"./vm-hands-entry-lite-ffg7rf02.js";import{execFile as V1,spawn as w0}from"child_process";import{randomBytes as F1}from"crypto";import{chmodSync as w1,existsSync as K0,lstatSync as K1,mkdirSync as M1,readFileSync as z1,rmSync as Y1,writeFileSync as Xq}from"fs";import{connect as _1}from"net";import{join as H}from"path";var Bq="./desktop-wallpaper-0pjhgyfk.jpg";var Rq="./dock-browser-afp005mt.png";var Cq="./dock-files-rywdm96b.png";var yq="./dock-terminal-s41cj1jp.png";var Sq=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
2
+ import{ef as Z8}from"./vm-hands-entry-lite-k1wbh9dq.js";import{nf as R0}from"./vm-hands-entry-lite-53jm8bj7.js";import{ig as Kq}from"./vm-hands-entry-lite-rnykqcys.js";import{Eg as p,Hg as V0,Kg as F0,Lg as C8,Mg as eq,Og as g8,Rg as q0,Tg as x0}from"./vm-hands-entry-lite-5vrdj7jm.js";import{Yg as wq}from"./vm-hands-entry-lite-qbk0wxrz.js";import{Zg as o,_g as C0}from"./vm-hands-entry-lite-vvmq0mtv.js";import{lh as B0}from"./vm-hands-entry-lite-kxbpf40y.js";import{Bh as A0}from"./vm-hands-entry-lite-y9k070mt.js";import{Ih as Z}from"./vm-hands-entry-lite-wffqkcjq.js";import{execFile as V1,spawn as w0}from"child_process";import{randomBytes as F1}from"crypto";import{chmodSync as w1,existsSync as K0,lstatSync as K1,mkdirSync as M1,readFileSync as z1,rmSync as Y1,writeFileSync as Xq}from"fs";import{connect as _1}from"net";import{join as H}from"path";var Bq="./desktop-wallpaper-0pjhgyfk.jpg";var Rq="./dock-browser-afp005mt.png";var Cq="./dock-files-rywdm96b.png";var yq="./dock-terminal-s41cj1jp.png";var Sq=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
3
3
  # The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
4
4
  # python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
5
5
  # Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
@@ -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 G0=new Set;async function u1(q,x,X){let Q=await v1(),P=/^:(\d+)(?:\.\d+)?$/.exec(Q.DISPLAY??"")?.[1];if(!P||`:${P}`===G8||Q.WAYLAND_DISPLAY||Q.XDG_SESSION_TYPE==="wayland")return null;let b={display:`:${P}`,xauthority:Q.XAUTHORITY??H(q,".Xauthority"),rfbSocket:H(x,`rfb-${P}.sock`)},J=`${b.display} ${b.xauthority}`;if(G0.has(J)||!await e({path:`/tmp/.X11-unix/X${P}`},!1))return null;let L={HOME:q,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:b.display,XAUTHORITY:b.xauthority};if(await z0(X,b,x,`x11vnc-${P}.log`,L))return{...b,sound:null};return G0.add(J),process.stderr.write(`Reason worker: your screen ${b.display} could not be served; using the virtual desktop
179
179
  `),null}function c1(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])=>!K0(`/usr/bin/${b}`)).map(([b])=>b),P=Aq({root:q,display:x,screen:Qq,browserExec:X,absent:Q});for(let b of["","openbox","tint2","picom"])A8(H(q,b));for(let[b,J]of Object.entries(P.files))Xq(H(q,b),J,{mode:384});for(let[b,J]of Object.entries(Gq))Xq(H(q,`ara-${b}`),z1(J),{mode:384});return{root:q,openboxConfig:H(q,"openbox","rc.xml"),start:P.start}}async function m1(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=w0("/bin/sh",["-c",X],{stdio:"ignore",env:{...x,PATH:"/usr/bin:/bin"}}),b=setTimeout(()=>{P.kill(),Q()},V8);P.once("error",()=>{clearTimeout(b),Q()}),P.once("exit",()=>{clearTimeout(b),Q()})})}async function O9(q,x={}){let X=x.now??Date.now,Q=g1(q.payload,X());if(q.signal.throwIfAborted(),!Q.video)throw new Z("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 Z("display_video_unsupported","This machine does not serve desktop video.");let b=Q.video,J=(x.video?.desktop??(P==="darwin"?async()=>X0:I1))();return await r1(q.signal,Q,x,X,(L)=>W0(L,{request:b,desktop:J,...Q.viewer?{viewer:Q.viewer}:{},viewerSameNetwork:Q.viewer_same_network===!0},x.video),(L)=>C8({type:"error",code:L}))}function r1(q,x,X,Q,P,b){let J=Q();return new Promise((L,y)=>{let W=null,U=!1,C=!1,R,D,Y,A=!1,N=null,S=(V)=>{if(C)return;if(N)V=N;C=!0,clearTimeout(R),clearTimeout(D),q.removeEventListener("abort",K),Y?.close();try{W?.close(1000,"display_session_over")}catch{}if("error"in V){y(V.error);return}L({reason:V.reason,...Y?.summary(),duration_ms:Math.max(0,Q()-J)})},F=()=>S({error:new Z("display_relay_unavailable","Reason could not reach the desktop relay.")}),K=()=>{let V=q.reason;S({error:V instanceof Z?V:new Z("cancelled","Reason closed the desktop session.")})},$=()=>{if(!N||!W)return;let V=N.error;try{W.send(b(V instanceof Z?V.code:"display_unavailable"))}catch{}S(N)};if(Y=P({get done(){return C||N!==null},get open(){return U&&!C&&N===null},get bufferedAmount(){return W?.bufferedAmount??0},send(V){if(C||N||!U||!W)return;try{W.send(V)}catch{S({reason:"relay_closed"})}},end:(V)=>{if(C||N)return;if(!("error"in V)){S(V);return}if(N=V,A&&U)$()}}),C){Y.close();return}if(q.aborted){K();return}q.addEventListener("abort",K,{once:!0}),R=setTimeout(()=>S({reason:"session_expired"}),Math.max(1,Date.parse(x.expires_at)-Q())),D=setTimeout(()=>S({reason:"viewer_absent"}),X.viewerWaitMs??$1);try{W=(X.connect??qq)(x.relay_url,(X.loadProxy??Z8)()?.url)}catch{F();return}W.binaryType="arraybuffer",W.onopen=()=>{if(C||!W)return;U=!0,Y?.opened()},W.onmessage=(V)=>{if(C)return;let g=V.data,v=g instanceof ArrayBuffer?new Uint8Array(g):ArrayBuffer.isView(g)?new Uint8Array(g.buffer,g.byteOffset,g.byteLength):null;if(!v||v.byteLength===0)return;if(clearTimeout(D),A=!0,N){$();return}Y?.received(v)},W.onclose=()=>{if(C)return;if(!U){F();return}S({reason:"relay_closed"})},W.onerror=()=>{if(C||U)return;F()}})}
181
- export{T1 as $d,T0 as ae,D1 as be,D9 as ce,B9 as de,O8 as ee,PX as fe,NX as ge,i as he,R8 as ie,Q9 as je,U0 as ke,Vq as le,Hq as me,r as ne,HX as oe,fX as pe,gX as qe,E1 as re,G8 as se,g1 as te,h1 as ue,$9 as ve,A8 as we,I1 as xe,O9 as ye};
181
+ export{T1 as be,T0 as ce,D1 as de,D9 as ee,B9 as fe,O8 as ge,PX as he,NX as ie,i as je,R8 as ke,Q9 as le,U0 as me,Vq as ne,Hq as oe,r as pe,HX as qe,fX as re,gX as se,E1 as te,G8 as ue,g1 as ve,h1 as we,$9 as xe,A8 as ye,I1 as ze,O9 as Ae};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Vb as i,Wb as l,Xb as g,Yb as y}from"./vm-hands-entry-lite-n07kxrd1.js";import{Af as I,Cf as O,ff as Q,gf as J,hf as z,if as Z,jf as K,kf as $,lf as k,nf as G,pf as X,qf as M,rf as Y,sf as H,tf as V,vf as S,wf as _,yf as P,zf as C}from"./vm-hands-entry-lite-ptmqg51y.js";import{lh as L,mh as W,nh as F,oh as j}from"./vm-hands-entry-lite-84aq8d12.js";var d=["cgroup_membership_read_failed","cgroup_v2_membership_absent","cgroup_scope_invalid","cgroup_root_unavailable","cgroup_directory_unavailable","cgroup_limit_read_failed","cgroup_events_read_failed","cgroup_current_read_failed","cgroup_stat_read_failed","boot_id_read_failed","boot_id_invalid","guest_meminfo_read_failed","guest_vmstat_read_failed","memory_counter_invalid","memory_field_missing","memory_capacity_invalid"];var a=String.raw`(function(fs, path) {
2
+ import{Vb as i,Wb as l,Xb as g,Yb as y}from"./vm-hands-entry-lite-n07kxrd1.js";import{Af as P,Bf as C,Cf as I,Ef as O,hf as Q,if as J,jf as z,kf as Z,lf as K,mf as $,nf as k,pf as G,rf as X,sf as M,tf as Y,uf as H,vf as V,xf as S,yf as _}from"./vm-hands-entry-lite-53jm8bj7.js";import{nh as L,oh as W,ph as F,qh as j}from"./vm-hands-entry-lite-kxbpf40y.js";var d=["cgroup_membership_read_failed","cgroup_v2_membership_absent","cgroup_scope_invalid","cgroup_root_unavailable","cgroup_directory_unavailable","cgroup_limit_read_failed","cgroup_events_read_failed","cgroup_current_read_failed","cgroup_stat_read_failed","boot_id_read_failed","boot_id_invalid","guest_meminfo_read_failed","guest_vmstat_read_failed","memory_counter_invalid","memory_field_missing","memory_capacity_invalid"];var a=String.raw`(function(fs, path) {
3
3
  const fail = (message, reasonCode) => { throw Object.assign(Error(message), {reasonCode}); };
4
4
  const read = (p, reasonCode, trim=true) => { try { const text=fs.readFileSync(p, "utf8"); return trim?text.trim():text; }
5
5
  catch { fail("memory_read", reasonCode); } };
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- var r={name:"github-native-engineer-device-worker-production",version:"0.2.282",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@anthropic-ai/sandbox-runtime":"^0.0.73","@earendil-works/pi-tui":"1.0.0","@modelcontextprotocol/sdk":"^1.29.0","@reason/runtime-distribution":"workspace:*","playwright-core":"1.60.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"1.20.0","basic-ftp":"6.2.1","@grpc/grpc-js":"1.14.5",browserslist:"4.28.8","engine.io":"6.6.7","fast-uri":"3.1.8",hono:"^4.13.7","ip-address":"10.7.1",nanoid:"3.3.18",dompurify:"3.4.13",postcss:"8.5.23",qs:"6.16.0","shell-quote":"1.11.0","socket.io-parser":"4.2.7",tmp:"0.2.7",toml:"4.2.0",undici:"8.10.2",ws:"^8.21.0","js-yaml":"4.3.2","@modelcontextprotocol/sdk":"1.31.0","proxy-addr":"2.0.8","source-map-js":"1.2.2"}};
3
- export{r as yh};
2
+ var r={name:"github-native-engineer-device-worker-production",version:"0.2.283",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@anthropic-ai/sandbox-runtime":"^0.0.73","@earendil-works/pi-tui":"1.0.0","@modelcontextprotocol/sdk":"^1.29.0","@reason/runtime-distribution":"workspace:*","playwright-core":"1.60.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"1.20.0","basic-ftp":"6.2.1","@grpc/grpc-js":"1.14.5",browserslist:"4.28.8","engine.io":"6.6.7","fast-uri":"3.1.8",hono:"^4.13.7","ip-address":"10.7.1",nanoid:"3.3.18",dompurify:"3.4.13",postcss:"8.5.23",qs:"6.16.0","shell-quote":"1.11.0","socket.io-parser":"4.2.7",tmp:"0.2.7",toml:"4.2.0",undici:"8.10.2",ws:"^8.21.0","js-yaml":"4.3.2","@modelcontextprotocol/sdk":"1.31.0","proxy-addr":"2.0.8","source-map-js":"1.2.2"}};
3
+ export{r as Ah};