@reason-machines/cli-linux-arm64-musl 0.2.359 → 0.2.361

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 (85) hide show
  1. package/bin/ara +2 -2
  2. package/bin/vm-hands/api-credentials-vtpssnm1.js +2 -0
  3. package/bin/vm-hands/api-dvwzjwmh.js +2 -0
  4. package/bin/vm-hands/{ask-relay-fkb3bj30.js → ask-relay-tkvyxa1h.js} +5 -5
  5. package/bin/vm-hands/connect-cli-bc074w36.js +2 -0
  6. package/bin/vm-hands/custom-endpoint-device-8v87dhjx.js +2 -0
  7. package/bin/vm-hands/desktop-account-q57958y1.js +2 -0
  8. package/bin/vm-hands/{device-workspace-fhbpenda.js → device-workspace-c05vq771.js} +1 -1
  9. package/bin/vm-hands/{hands-worker-source-ze6q6h8b.js → hands-worker-source-wfv9csj2.js} +1 -1
  10. package/bin/vm-hands/{index-tv4kcb2a.js → index-80ep9259.js} +1 -1
  11. package/bin/vm-hands/{install-receipt-3s9amwp3.js → install-receipt-pbfhgaxc.js} +1 -1
  12. package/bin/vm-hands/local-automation-y118qzv6.js +2 -0
  13. package/bin/vm-hands/local-capabilities-fpjwj7a5.js +2 -0
  14. package/bin/vm-hands/local-desktop-users-m7rexsex.js +2 -0
  15. package/bin/vm-hands/local-display-mac-9de01n3r.js +2 -0
  16. package/bin/vm-hands/local-display-session-x25wfj8b.js +2 -0
  17. package/bin/vm-hands/local-pty-session-e7j0kj19.js +2 -0
  18. package/bin/vm-hands/{managed-runtime-mg7kmckn.js → managed-runtime-cv1vnm9k.js} +1 -1
  19. package/bin/vm-hands/{network-contract-gq8x3ehk.js → network-contract-zjq3w2n3.js} +1 -1
  20. package/bin/vm-hands/package-44a3p8yk.js +2 -0
  21. package/bin/vm-hands/permissions-ab559brd.js +2 -0
  22. package/bin/vm-hands/{reason-hands-protocol-67d4b6fm.js → reason-hands-protocol-aj1zwpk0.js} +1 -1
  23. package/bin/vm-hands/serve-service-csbg58wj.js +2 -0
  24. package/bin/vm-hands/{status-f146chye.js → status-00w678nv.js} +2 -2
  25. package/bin/vm-hands/version-x9tfh3sx.js +2 -0
  26. package/bin/vm-hands/{vm-hands-entry-lite-5xtkyx25.js → vm-hands-entry-lite-0763vz5v.js} +1 -1
  27. package/bin/vm-hands/{vm-hands-entry-lite-kxdw4myj.js → vm-hands-entry-lite-1hv536wk.js} +1 -1
  28. package/bin/vm-hands/{vm-hands-entry-lite-tg2bkah3.js → vm-hands-entry-lite-2vfv33yn.js} +1 -1
  29. package/bin/vm-hands/{vm-hands-entry-lite-r6pap1kh.js → vm-hands-entry-lite-4xfs7y6w.js} +1 -1
  30. package/bin/vm-hands/{vm-hands-entry-lite-p8662x7z.js → vm-hands-entry-lite-5wmh1c1y.js} +2 -2
  31. package/bin/vm-hands/{vm-hands-entry-lite-3ew5ftk0.js → vm-hands-entry-lite-5y2kfnv2.js} +2 -2
  32. package/bin/vm-hands/{vm-hands-entry-lite-qm18wqgz.js → vm-hands-entry-lite-6fvjbwqq.js} +1 -1
  33. package/bin/vm-hands/{vm-hands-entry-lite-d2hbz0r4.js → vm-hands-entry-lite-7nk0873d.js} +1 -1
  34. package/bin/vm-hands/{vm-hands-entry-lite-sx2gpbap.js → vm-hands-entry-lite-97zxda1y.js} +1 -1
  35. package/bin/vm-hands/{vm-hands-entry-lite-pf1gagky.js → vm-hands-entry-lite-9grctmjf.js} +3 -3
  36. package/bin/vm-hands/{vm-hands-entry-lite-kt4831mq.js → vm-hands-entry-lite-a43ss1hy.js} +2 -2
  37. package/bin/vm-hands/{vm-hands-entry-lite-ha1ej910.js → vm-hands-entry-lite-avstvbbc.js} +2 -2
  38. package/bin/vm-hands/{vm-hands-entry-lite-bybpy28m.js → vm-hands-entry-lite-cety9pka.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-22we2jrv.js → vm-hands-entry-lite-cwf21py1.js} +1 -1
  40. package/bin/vm-hands/{vm-hands-entry-lite-w88zkzhr.js → vm-hands-entry-lite-dqnhebfx.js} +1 -1
  41. package/bin/vm-hands/{vm-hands-entry-lite-qbnz4h30.js → vm-hands-entry-lite-dzkqn26g.js} +2 -2
  42. package/bin/vm-hands/{vm-hands-entry-lite-szfy3kx7.js → vm-hands-entry-lite-fr2k6eah.js} +2 -2
  43. package/bin/vm-hands/{vm-hands-entry-lite-qhgfnhjt.js → vm-hands-entry-lite-gj6znkxv.js} +2 -2
  44. package/bin/vm-hands/{vm-hands-entry-lite-463aheya.js → vm-hands-entry-lite-hfq6jjnh.js} +1 -1
  45. package/bin/vm-hands/{vm-hands-entry-lite-h2xemq1f.js → vm-hands-entry-lite-hw8vgsmm.js} +1 -1
  46. package/bin/vm-hands/{vm-hands-entry-lite-jn95s3j4.js → vm-hands-entry-lite-jjkkee8q.js} +2 -2
  47. package/bin/vm-hands/{vm-hands-entry-lite-x4j4058x.js → vm-hands-entry-lite-jn8v1fp1.js} +2 -2
  48. package/bin/vm-hands/{vm-hands-entry-lite-r5y08n0q.js → vm-hands-entry-lite-jpkf3569.js} +2 -2
  49. package/bin/vm-hands/{vm-hands-entry-lite-kv0qat0x.js → vm-hands-entry-lite-k7fkfytm.js} +2 -2
  50. package/bin/vm-hands/{vm-hands-entry-lite-c7krpmd8.js → vm-hands-entry-lite-k8as28ss.js} +2 -2
  51. package/bin/vm-hands/{vm-hands-entry-lite-ygx9kj92.js → vm-hands-entry-lite-kxtjkzzh.js} +1 -1
  52. package/bin/vm-hands/{vm-hands-entry-lite-07er2w8q.js → vm-hands-entry-lite-mhvfdbq5.js} +2 -2
  53. package/bin/vm-hands/{vm-hands-entry-lite-5kgvss4p.js → vm-hands-entry-lite-p1nb6n3r.js} +2 -2
  54. package/bin/vm-hands/{vm-hands-entry-lite-gzxxsjmr.js → vm-hands-entry-lite-qkvwh6b7.js} +2 -2
  55. package/bin/vm-hands/{vm-hands-entry-lite-9z6k7898.js → vm-hands-entry-lite-qy9xzp2m.js} +2 -2
  56. package/bin/vm-hands/{vm-hands-entry-lite-c0m2jewa.js → vm-hands-entry-lite-t4gcrmbp.js} +1 -1
  57. package/bin/vm-hands/{vm-hands-entry-lite-1j9r1fca.js → vm-hands-entry-lite-tbps80f1.js} +2 -2
  58. package/bin/vm-hands/{vm-hands-entry-lite-v08mjs3f.js → vm-hands-entry-lite-vcm4389c.js} +2 -2
  59. package/bin/vm-hands/{vm-hands-entry-lite-n867d88m.js → vm-hands-entry-lite-vgj22wxq.js} +2 -2
  60. package/bin/vm-hands/{vm-hands-entry-lite-j05685sg.js → vm-hands-entry-lite-xhr0m9r0.js} +1 -1
  61. package/bin/vm-hands/{vm-hands-entry-lite-s98hjhz3.js → vm-hands-entry-lite-xj0p1ax7.js} +2 -2
  62. package/bin/vm-hands/{vm-hands-entry-lite-taw01cp4.js → vm-hands-entry-lite-zn303jrg.js} +1 -1
  63. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  64. package/bin/vm-hands/{vm-hands-executor-5nqmf61x.js → vm-hands-executor-kmar1gzz.js} +1 -1
  65. package/bin/vm-hands/vm-hands-op-runner-mm3bkzhq.js +2 -0
  66. package/bin/vm-hands/{vm-hands-runtime-hnpk8xmf.js → vm-hands-runtime-kxsr73mx.js} +3 -3
  67. package/bin/vm-hands/worker-sandbox-wb5thd4n.js +2 -0
  68. package/package.json +1 -1
  69. package/bin/vm-hands/api-credentials-axffq0pk.js +0 -2
  70. package/bin/vm-hands/api-texm6ayv.js +0 -2
  71. package/bin/vm-hands/connect-cli-ev4xex04.js +0 -2
  72. package/bin/vm-hands/custom-endpoint-device-bsanzqj2.js +0 -2
  73. package/bin/vm-hands/desktop-account-jxfva4m1.js +0 -2
  74. package/bin/vm-hands/local-automation-f8f33qpp.js +0 -2
  75. package/bin/vm-hands/local-capabilities-ya6yzxh5.js +0 -2
  76. package/bin/vm-hands/local-desktop-users-3th2aaac.js +0 -2
  77. package/bin/vm-hands/local-display-mac-neweyjpa.js +0 -2
  78. package/bin/vm-hands/local-display-session-v00nv1fm.js +0 -2
  79. package/bin/vm-hands/local-pty-session-2crsy5td.js +0 -2
  80. package/bin/vm-hands/package-s3eg9zrd.js +0 -2
  81. package/bin/vm-hands/permissions-3kjdp3ge.js +0 -2
  82. package/bin/vm-hands/serve-service-nqshfese.js +0 -2
  83. package/bin/vm-hands/version-ss25ccvh.js +0 -2
  84. package/bin/vm-hands/vm-hands-op-runner-zedtdcmk.js +0 -2
  85. package/bin/vm-hands/worker-sandbox-vmp22sk6.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{De as UJ,Le as TJ,pf as CJ}from"./vm-hands-entry-lite-szfy3kx7.js";import{createHash as I,randomBytes as zJ}from"crypto";import{closeSync as LJ,fsyncSync as qJ,mkdirSync as fJ,openSync as NJ,renameSync as mJ,rmSync as bJ,statSync as DJ,writeSync as AJ,constants as y}from"fs";import{join as r}from"path";var cJ=1;var i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function KJ(J){if(J.environment!==void 0||J.payload.environment!==void 0)throw new W("vm_hands_bind_invalid","bind carries a plaintext environment");if(J.payload.vm_hands_env_deferred===!0&&J.environment_sealed!==void 0)throw new W("vm_hands_bind_invalid","split bind carries an environment");return J.environment_sealed!==void 0}function BJ(J,Z){let{payload:z,authority:K}=J;if(!z||typeof z!=="object"||Array.isArray(z)||!K||typeof K!=="object"||Array.isArray(K)||!Z.deviceId||!Z.rootId||z.run_id!==Z.runId||z.device_id!==Z.deviceId||K.device_id!==Z.deviceId||z.root_id!==Z.rootId||Z.snapshotId!==void 0&&z.snapshot_id!==Z.snapshotId)throw new W("vm_hands_env_invalid","environment does not match this Hands");return z}function xJ(J){if(J.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not a hands.connect claim");let Z=J.payload;return{kind:"vm_hands.bind",v:1,bind_id:J.attempt_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,run_id:J.run_id,session_id:typeof Z.workspace_id==="string"&&i.test(Z.workspace_id)?Z.workspace_id:J.run_id,brain_generation:Z.target_generation,fence_id:Z.target_fence_id,lease_until:J.lease_until,policy:{agent_profile:"",confinement_key:String(Z.hands_confinement??""),browser_egress:Z.browser_egress??null,policy_digest:Z.vm_hands_policy_digest},cwd:typeof Z.cwd==="string"?Z.cwd:"",claim:J,env:KJ(J)?J.environment_sealed:null}}class W extends Error{code;constructor(J,Z){super(Z);this.code=J}}var v=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),R=(J)=>new Uint8Array(Buffer.from(J,"base64url"));function f(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return`[${J.map(f).join(",")}]`;return`{${Object.keys(J).sort().map((Z)=>`${JSON.stringify(Z)}:${f(J[Z])}`).join(",")}}`}async function QZ(J){let Z=await crypto.subtle.importKey("pkcs8",R(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),z=R(J.device_key.spki),K=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),B=new Uint8Array(await crypto.subtle.exportKey("spki",K.publicKey)),L=I("sha256").update(z).digest("base64url");return{signing:{privateKey:Z},agreement:K,signingSpki:z,agreementSpki:B,fingerprint:L}}var pJ=4;class lJ{init;keys;hooks;options;identity="identity_free";lastBrainGeneration=new Map;bound=new Map;binding=new Map;unbinding=new Set;servedRun=!1;commandsSinceVerified=!1;bootKillPending=!1;unverified=new Set;structural=Promise.resolve();exclusive(J){let Z=this.structural.then(J,J);return this.structural=Z.catch(()=>{return}),Z}constructor(J,Z,z,K){this.init=J;this.keys=Z;this.hooks=z;this.options=K;if(!i.test(J.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(J.workspace_id))throw new W("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(J.instance_generation)||J.instance_generation<1)throw new W("vm_hands_layout_invalid","bad generation")}get phase(){if(this.identity==="identity_free")return"identity_free";if(this.unbinding.size)return"unbinding";return this.bound.size||this.binding.size?"bound":"registered"}isBoundRun(J){for(let Z of this.bound.values())if(Z.runId===J)return!0;return!1}bindIdForRun(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}async environmentInstalled(J,Z,z){for(let K=Date.now()+Z;;){let B=this.bound.get(J);if(!B)return!1;if(B.envInstalled)return!0;if(Date.now()>=K||z?.aborted)return!1;await new Promise((L)=>setTimeout(L,25))}}opServed(){this.commandsSinceVerified=!0}canSpawn(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.envInstalled;return!1}async registerFrame(J){if(this.identity!=="identity_free")throw new W("vm_hands_register_twice","already registered");if(typeof J!=="string"||J.length<16||J.length>256)throw new W("vm_hands_challenge_invalid","bad register challenge");let Z={challenge:J,t:"register",v:cJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:v(this.keys.signingSpki),env_public_key:v(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:v(zJ(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},z=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(f(Z)));return{...Z,device_signature:v(z)}}async helloFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","hello before register");let z=String((this.options.now??Date.now)()),K=v(zJ(32)),B=CJ({method:"GET",pathAndQuery:UJ,timestamp:z,nonce:K,challenge:J,bodySha256:I("sha256").update("").digest("hex")}),L=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(B)));return{t:"hello",timestamp:z,nonce:K,signature:v(uJ(L)),...Z?{vm_hands_previous_connection:Z}:{}}}registered(){if(this.identity!=="identity_free")throw new W("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(J){if(this.identity!=="registered")throw new W("vm_hands_not_registered","bind before register");if(J.kind!=="vm_hands.bind"||J.v!==1)throw new W("vm_hands_bind_invalid","bad bind");for(let z of[J.bind_id,J.attempt_id,J.run_id,J.session_id,J.fence_id])if(!i.test(z))throw new W("vm_hands_bind_invalid","bad id");if(!Number.isSafeInteger(J.brain_generation)||J.brain_generation<=(this.lastBrainGeneration.get(J.run_id)??0))throw new W("vm_hands_generation_stale","brain generation not strictly higher");if(J.env&&(J.env.aad!==J.bind_id||J.env.alg!=="ECDH-P256+A256GCM"))throw new W("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(J.policy.policy_digest))throw new W("vm_hands_bind_invalid","bad policy or nonce");if(I("sha256").update(f({hands_confinement:J.policy.confinement_key||null,browser_egress:J.policy.browser_egress??null})).digest("hex")!==J.policy.policy_digest)throw new W("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(J.bind_id)||[...this.bound.values()].some((z)=>z.runId===J.run_id)||[...this.binding.values()].includes(J.run_id))throw new W("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=pJ)throw new W("vm_hands_busy","every bind slot is held");return this.lastBrainGeneration.set(J.run_id,J.brain_generation),this.binding.set(J.bind_id,J.run_id),this.exclusive(()=>this.setUp(J))}async setUp(J){let Z=[...this.bound.keys()],z=null,K=!1;try{if(Z.length===0){if(this.bootKillPending&&!this.servedRun){try{await this.hooks.killProbe()}catch{throw new W("vm_hands_kill_unverified","the boot's scoped kill did not verify")}this.bootKillPending=!1}if(this.commandsSinceVerified)await this.hooks.killAndVerifyPayload(),this.unverified.clear(),this.commandsSinceVerified=!1;else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({own:!0}),this.unverified.clear()}else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({keep:Z}),this.unverified.clear();this.servedRun=!0,K=!0;let{launchId:B,applied:L,readyData:j}=await this.hooks.startExecutor({bindId:J.bind_id,sessionId:J.session_id,policyDigest:J.policy.policy_digest,confinementKey:J.policy.confinement_key,browserEgress:J.policy.browser_egress,cwd:J.cwd,claim:J.claim}),E=this.hooks.restatLayout(),N=null,_=null;if(J.env){let H=J.claim?.owner??{},T=BJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof H.device_id==="string"?H.device_id:"",rootId:J.claim?.root_id??""});this.commandsSinceVerified=!0,N=this.hooks.installEnvironment(J.bind_id,T),_=typeof T.snapshot_id==="string"&&T.snapshot_id?T.snapshot_id:null,z=this.writeJobEnvRootOnly(J.bind_id,T)}if(this.unbinding.has(J.bind_id))throw new W("vm_hands_bind_lost","unbound while binding");return this.bound.set(J.bind_id,{bindId:J.bind_id,runId:J.run_id,sessionId:J.session_id,brainGeneration:J.brain_generation,policyDigest:J.policy.policy_digest,launchId:B,envInstalled:N!==null,rootId:J.claim?.root_id??"",envDirectory:z}),this.binding.delete(J.bind_id),{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:B,snapshot_revision:N,snapshot_id:_,layout:E,...j?{ready_data:j}:{},policy_digest:I("sha256").update(f({hands_confinement:L.hands_confinement??null,browser_egress:L.browser_egress??null})).digest("hex")}}catch(B){if(z)GJ(z);if(K){let j=[...this.bound.keys()];await this.hooks.killAndVerifyPayload({bindId:J.bind_id,keep:j,own:!0}).catch(()=>{this.unverified.add(J.bind_id)})}this.binding.delete(J.bind_id);let L=B&&typeof B==="object"&&"code"in B&&typeof B.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(B.code)?B.code:"vm_hands_bind_failed";throw B instanceof W?B:new W(L,"executor refused the bind")}}async deliverEnvironment(J){let Z=this.bound.get(J.attemptId);if(!Z||this.unbinding.has(J.attemptId))throw new W("vm_hands_not_bound","environment delivered while not bound");if(!i.test(J.attemptId)||typeof J.snapshotId!=="string"||!J.snapshotId||J.snapshotId.length>128||J.snapshotId.includes("/"))throw new W("vm_hands_env_invalid","bad snapshot id");let z=`${J.attemptId}/${J.snapshotId}`;if(J.sealed?.alg!=="ECDH-P256+A256GCM"||J.sealed.aad!==z)throw new W("vm_hands_env_invalid","bad env envelope");let K=BJ(await this.openSealed(J.sealed,z),{runId:Z.runId,deviceId:J.deviceId,rootId:Z.rootId,snapshotId:J.snapshotId});this.commandsSinceVerified=!0;let B=this.hooks.installEnvironment(Z.bindId,K);if(Z.envInstalled=!0,Z.envDirectory)GJ(Z.envDirectory);return Z.envDirectory=null,Z.envDirectory=this.writeJobEnvRootOnly(`${Z.bindId}-r${B}`,K),{snapshot_id:J.snapshotId,installed_revision:B,installed:!0}}async attestFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","attest before register");if(!J||J.length>65536)throw new W("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new W("vm_hands_attest_invalid","attest beside a bind");let z=await this.hooks.runProbe({nonce:Z,script:J});try{await this.hooks.killProbe()}catch{this.bootKillPending=!0}return{t:"attest",nonce:Z,exit_code:z.exitCode,markers:z.markers,proof_dir_inode:z.proofDirInode,script_sha256:I("sha256").update(J).digest("hex")}})}executorExited(J){return this.hooks.executorExited?.(J)??new Promise(()=>{})}async boundRefused(J){await this.unbind(J)}async unbind(J){let Z=this.bound.get(J)??null;if(this.unbinding.add(J),this.bound.delete(J),Z)try{this.hooks.freezeBind?.(J)}catch{}return this.exclusive(()=>this.tearDown(J,Z))}async tearDown(J,Z){try{this.bound.delete(J);let z=[...this.bound.keys()].filter((B)=>B!==J),K=!z.length&&!this.commandsSinceVerified;try{await this.hooks.killAndVerifyPayload(z.length?{bindId:J,keep:z}:K?{bindId:J,own:!0}:void 0)}catch(B){throw this.unverified.add(J),B}if(!z.length)this.unverified.clear(),this.commandsSinceVerified=!1;if(Z?.envDirectory)GJ(Z.envDirectory);return{bind_id:Z?J:null,killed_verified:!0,shredded:!0,srt_fallbacks:z.length?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(J)}}async openSealed(J,Z){let z=()=>{throw new W("vm_hands_env_invalid","env did not decrypt")},K=await crypto.subtle.importKey("spki",R(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(z),B=await crypto.subtle.deriveKey({name:"ECDH",public:K},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),L=await crypto.subtle.decrypt({name:"AES-GCM",iv:R(J.iv),additionalData:new TextEncoder().encode(Z)},B,R(J.ct)).catch(z),j=JSON.parse(new TextDecoder().decode(L));if(!j||typeof j!=="object"||Array.isArray(j))throw new W("vm_hands_env_invalid","env not an object");return j}writeJobEnvRootOnly(J,Z){let z=r(this.options.envRoot,`bind-${J}`);fJ(z,{mode:448});let K=DJ(z);if(!K.isDirectory()||(K.mode&63)!==0||K.uid!==(process.getuid?.()??-1))throw new W("vm_hands_env_dir_unsafe","env directory is not root's 0700");let B=Z.variables&&typeof Z.variables==="object"?Z.variables:{},L=Object.entries(B).filter(([N,_])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(N)&&typeof _==="string").map(([N,_])=>`export ${N}='${String(_).replaceAll("'","'\\''")}'`).join(`
2
+ import{Ee as UJ,Me as TJ,qf as CJ}from"./vm-hands-entry-lite-fr2k6eah.js";import{createHash as I,randomBytes as zJ}from"crypto";import{closeSync as LJ,fsyncSync as qJ,mkdirSync as fJ,openSync as NJ,renameSync as mJ,rmSync as bJ,statSync as DJ,writeSync as AJ,constants as y}from"fs";import{join as r}from"path";var cJ=1;var i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function KJ(J){if(J.environment!==void 0||J.payload.environment!==void 0)throw new W("vm_hands_bind_invalid","bind carries a plaintext environment");if(J.payload.vm_hands_env_deferred===!0&&J.environment_sealed!==void 0)throw new W("vm_hands_bind_invalid","split bind carries an environment");return J.environment_sealed!==void 0}function BJ(J,Z){let{payload:z,authority:K}=J;if(!z||typeof z!=="object"||Array.isArray(z)||!K||typeof K!=="object"||Array.isArray(K)||!Z.deviceId||!Z.rootId||z.run_id!==Z.runId||z.device_id!==Z.deviceId||K.device_id!==Z.deviceId||z.root_id!==Z.rootId||Z.snapshotId!==void 0&&z.snapshot_id!==Z.snapshotId)throw new W("vm_hands_env_invalid","environment does not match this Hands");return z}function xJ(J){if(J.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not a hands.connect claim");let Z=J.payload;return{kind:"vm_hands.bind",v:1,bind_id:J.attempt_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,run_id:J.run_id,session_id:typeof Z.workspace_id==="string"&&i.test(Z.workspace_id)?Z.workspace_id:J.run_id,brain_generation:Z.target_generation,fence_id:Z.target_fence_id,lease_until:J.lease_until,policy:{agent_profile:"",confinement_key:String(Z.hands_confinement??""),browser_egress:Z.browser_egress??null,policy_digest:Z.vm_hands_policy_digest},cwd:typeof Z.cwd==="string"?Z.cwd:"",claim:J,env:KJ(J)?J.environment_sealed:null}}class W extends Error{code;constructor(J,Z){super(Z);this.code=J}}var v=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),R=(J)=>new Uint8Array(Buffer.from(J,"base64url"));function f(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return`[${J.map(f).join(",")}]`;return`{${Object.keys(J).sort().map((Z)=>`${JSON.stringify(Z)}:${f(J[Z])}`).join(",")}}`}async function QZ(J){let Z=await crypto.subtle.importKey("pkcs8",R(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),z=R(J.device_key.spki),K=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),B=new Uint8Array(await crypto.subtle.exportKey("spki",K.publicKey)),L=I("sha256").update(z).digest("base64url");return{signing:{privateKey:Z},agreement:K,signingSpki:z,agreementSpki:B,fingerprint:L}}var pJ=4;class lJ{init;keys;hooks;options;identity="identity_free";lastBrainGeneration=new Map;bound=new Map;binding=new Map;unbinding=new Set;servedRun=!1;commandsSinceVerified=!1;bootKillPending=!1;unverified=new Set;structural=Promise.resolve();exclusive(J){let Z=this.structural.then(J,J);return this.structural=Z.catch(()=>{return}),Z}constructor(J,Z,z,K){this.init=J;this.keys=Z;this.hooks=z;this.options=K;if(!i.test(J.workspace_id)&&!/^ws-[a-z0-9]{8,64}$/.test(J.workspace_id))throw new W("vm_hands_layout_invalid","bad workspace id");if(!Number.isSafeInteger(J.instance_generation)||J.instance_generation<1)throw new W("vm_hands_layout_invalid","bad generation")}get phase(){if(this.identity==="identity_free")return"identity_free";if(this.unbinding.size)return"unbinding";return this.bound.size||this.binding.size?"bound":"registered"}isBoundRun(J){for(let Z of this.bound.values())if(Z.runId===J)return!0;return!1}bindIdForRun(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.bindId;return null}get liveBindIds(){return[...new Set([...this.bound.keys(),...this.binding.keys(),...this.unbinding])]}async environmentInstalled(J,Z,z){for(let K=Date.now()+Z;;){let B=this.bound.get(J);if(!B)return!1;if(B.envInstalled)return!0;if(Date.now()>=K||z?.aborted)return!1;await new Promise((L)=>setTimeout(L,25))}}opServed(){this.commandsSinceVerified=!0}canSpawn(J){for(let Z of this.bound.values())if(Z.runId===J)return Z.envInstalled;return!1}async registerFrame(J){if(this.identity!=="identity_free")throw new W("vm_hands_register_twice","already registered");if(typeof J!=="string"||J.length<16||J.length>256)throw new W("vm_hands_challenge_invalid","bad register challenge");let Z={challenge:J,t:"register",v:cJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:v(this.keys.signingSpki),env_public_key:v(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:v(zJ(32)),timestamp_ms:(this.options.now??Date.now)(),vm_hands_attest_hold:!0},z=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new TextEncoder().encode(f(Z)));return{...Z,device_signature:v(z)}}async helloFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","hello before register");let z=String((this.options.now??Date.now)()),K=v(zJ(32)),B=CJ({method:"GET",pathAndQuery:UJ,timestamp:z,nonce:K,challenge:J,bodySha256:I("sha256").update("").digest("hex")}),L=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(B)));return{t:"hello",timestamp:z,nonce:K,signature:v(uJ(L)),...Z?{vm_hands_previous_connection:Z}:{}}}registered(){if(this.identity!=="identity_free")throw new W("vm_hands_register_unexpected","registered twice");this.identity="registered"}async bind(J){if(this.identity!=="registered")throw new W("vm_hands_not_registered","bind before register");if(J.kind!=="vm_hands.bind"||J.v!==1)throw new W("vm_hands_bind_invalid","bad bind");for(let z of[J.bind_id,J.attempt_id,J.run_id,J.session_id,J.fence_id])if(!i.test(z))throw new W("vm_hands_bind_invalid","bad id");if(!Number.isSafeInteger(J.brain_generation)||J.brain_generation<=(this.lastBrainGeneration.get(J.run_id)??0))throw new W("vm_hands_generation_stale","brain generation not strictly higher");if(J.env&&(J.env.aad!==J.bind_id||J.env.alg!=="ECDH-P256+A256GCM"))throw new W("vm_hands_bind_invalid","bad env envelope");if(!/^[0-9a-f]{64}$/.test(J.policy.policy_digest))throw new W("vm_hands_bind_invalid","bad policy or nonce");if(I("sha256").update(f({hands_confinement:J.policy.confinement_key||null,browser_egress:J.policy.browser_egress??null})).digest("hex")!==J.policy.policy_digest)throw new W("vm_hands_policy_mismatch","policy digest does not match the claim");if(this.liveBindIds.includes(J.bind_id)||[...this.bound.values()].some((z)=>z.runId===J.run_id)||[...this.binding.values()].includes(J.run_id))throw new W("vm_hands_busy","this run already holds a bind here");if(this.liveBindIds.length>=pJ)throw new W("vm_hands_busy","every bind slot is held");return this.lastBrainGeneration.set(J.run_id,J.brain_generation),this.binding.set(J.bind_id,J.run_id),this.exclusive(()=>this.setUp(J))}async setUp(J){let Z=[...this.bound.keys()],z=null,K=!1;try{if(Z.length===0){if(this.bootKillPending&&!this.servedRun){try{await this.hooks.killProbe()}catch{throw new W("vm_hands_kill_unverified","the boot's scoped kill did not verify")}this.bootKillPending=!1}if(this.commandsSinceVerified)await this.hooks.killAndVerifyPayload(),this.unverified.clear(),this.commandsSinceVerified=!1;else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({own:!0}),this.unverified.clear()}else if(this.unverified.size>0)await this.hooks.killAndVerifyPayload({keep:Z}),this.unverified.clear();this.servedRun=!0,K=!0;let{launchId:B,applied:L,readyData:j}=await this.hooks.startExecutor({bindId:J.bind_id,sessionId:J.session_id,policyDigest:J.policy.policy_digest,confinementKey:J.policy.confinement_key,browserEgress:J.policy.browser_egress,cwd:J.cwd,claim:J.claim}),E=this.hooks.restatLayout(),N=null,_=null;if(J.env){let H=J.claim?.owner??{},T=BJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof H.device_id==="string"?H.device_id:"",rootId:J.claim?.root_id??""});this.commandsSinceVerified=!0,N=this.hooks.installEnvironment(J.bind_id,T),_=typeof T.snapshot_id==="string"&&T.snapshot_id?T.snapshot_id:null,z=this.writeJobEnvRootOnly(J.bind_id,T)}if(this.unbinding.has(J.bind_id))throw new W("vm_hands_bind_lost","unbound while binding");return this.bound.set(J.bind_id,{bindId:J.bind_id,runId:J.run_id,sessionId:J.session_id,brainGeneration:J.brain_generation,policyDigest:J.policy.policy_digest,launchId:B,envInstalled:N!==null,rootId:J.claim?.root_id??"",envDirectory:z}),this.binding.delete(J.bind_id),{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:B,snapshot_revision:N,snapshot_id:_,layout:E,...j?{ready_data:j}:{},policy_digest:I("sha256").update(f({hands_confinement:L.hands_confinement??null,browser_egress:L.browser_egress??null})).digest("hex")}}catch(B){if(z)GJ(z);if(K){let j=[...this.bound.keys()];await this.hooks.killAndVerifyPayload({bindId:J.bind_id,keep:j,own:!0}).catch(()=>{this.unverified.add(J.bind_id)})}this.binding.delete(J.bind_id);let L=B&&typeof B==="object"&&"code"in B&&typeof B.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(B.code)?B.code:"vm_hands_bind_failed";throw B instanceof W?B:new W(L,"executor refused the bind")}}async deliverEnvironment(J){let Z=this.bound.get(J.attemptId);if(!Z||this.unbinding.has(J.attemptId))throw new W("vm_hands_not_bound","environment delivered while not bound");if(!i.test(J.attemptId)||typeof J.snapshotId!=="string"||!J.snapshotId||J.snapshotId.length>128||J.snapshotId.includes("/"))throw new W("vm_hands_env_invalid","bad snapshot id");let z=`${J.attemptId}/${J.snapshotId}`;if(J.sealed?.alg!=="ECDH-P256+A256GCM"||J.sealed.aad!==z)throw new W("vm_hands_env_invalid","bad env envelope");let K=BJ(await this.openSealed(J.sealed,z),{runId:Z.runId,deviceId:J.deviceId,rootId:Z.rootId,snapshotId:J.snapshotId});this.commandsSinceVerified=!0;let B=this.hooks.installEnvironment(Z.bindId,K);if(Z.envInstalled=!0,Z.envDirectory)GJ(Z.envDirectory);return Z.envDirectory=null,Z.envDirectory=this.writeJobEnvRootOnly(`${Z.bindId}-r${B}`,K),{snapshot_id:J.snapshotId,installed_revision:B,installed:!0}}async attestFrame(J,Z){if(this.identity==="identity_free")throw new W("vm_hands_not_registered","attest before register");if(!J||J.length>65536)throw new W("vm_hands_attest_invalid","no probe script");return this.exclusive(async()=>{if(this.liveBindIds.length)throw new W("vm_hands_attest_invalid","attest beside a bind");let z=await this.hooks.runProbe({nonce:Z,script:J});try{await this.hooks.killProbe()}catch{this.bootKillPending=!0}return{t:"attest",nonce:Z,exit_code:z.exitCode,markers:z.markers,proof_dir_inode:z.proofDirInode,script_sha256:I("sha256").update(J).digest("hex")}})}executorExited(J){return this.hooks.executorExited?.(J)??new Promise(()=>{})}async boundRefused(J){await this.unbind(J)}async unbind(J){let Z=this.bound.get(J)??null;if(this.unbinding.add(J),this.bound.delete(J),Z)try{this.hooks.freezeBind?.(J)}catch{}return this.exclusive(()=>this.tearDown(J,Z))}async tearDown(J,Z){try{this.bound.delete(J);let z=[...this.bound.keys()].filter((B)=>B!==J),K=!z.length&&!this.commandsSinceVerified;try{await this.hooks.killAndVerifyPayload(z.length?{bindId:J,keep:z}:K?{bindId:J,own:!0}:void 0)}catch(B){throw this.unverified.add(J),B}if(!z.length)this.unverified.clear(),this.commandsSinceVerified=!1;if(Z?.envDirectory)GJ(Z.envDirectory);return{bind_id:Z?J:null,killed_verified:!0,shredded:!0,srt_fallbacks:z.length?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(J)}}async openSealed(J,Z){let z=()=>{throw new W("vm_hands_env_invalid","env did not decrypt")},K=await crypto.subtle.importKey("spki",R(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(z),B=await crypto.subtle.deriveKey({name:"ECDH",public:K},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),L=await crypto.subtle.decrypt({name:"AES-GCM",iv:R(J.iv),additionalData:new TextEncoder().encode(Z)},B,R(J.ct)).catch(z),j=JSON.parse(new TextDecoder().decode(L));if(!j||typeof j!=="object"||Array.isArray(j))throw new W("vm_hands_env_invalid","env not an object");return j}writeJobEnvRootOnly(J,Z){let z=r(this.options.envRoot,`bind-${J}`);fJ(z,{mode:448});let K=DJ(z);if(!K.isDirectory()||(K.mode&63)!==0||K.uid!==(process.getuid?.()??-1))throw new W("vm_hands_env_dir_unsafe","env directory is not root's 0700");let B=Z.variables&&typeof Z.variables==="object"?Z.variables:{},L=Object.entries(B).filter(([N,_])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(N)&&typeof _==="string").map(([N,_])=>`export ${N}='${String(_).replaceAll("'","'\\''")}'`).join(`
3
3
  `)+`
4
4
  `,j=r(z,`.job.env.${zJ(8).toString("hex")}`),E=NJ(j,y.O_WRONLY|y.O_CREAT|y.O_EXCL|y.O_NOFOLLOW,384);try{AJ(E,L),qJ(E)}finally{LJ(E)}return mJ(j,r(z,"job.env")),z}}function GJ(J){try{let Z=r(J,"job.env"),z=DJ(Z).size,K=NJ(Z,y.O_WRONLY|y.O_NOFOLLOW);try{AJ(K,Buffer.alloc(z)),qJ(K)}finally{LJ(K)}}catch{}bJ(J,{recursive:!0,force:!0})}function uJ(J){if(J.length!==64)throw new W("vm_hands_signature_invalid","unexpected ECDSA signature length");let Z=(B)=>{let L=0;while(L<B.length-1&&B[L]===0)L++;let j=B.subarray(L),E=j[0]&128?Uint8Array.of(0,...j):j;return Uint8Array.of(2,E.length,...E)},z=Z(J.subarray(0,32)),K=Z(J.subarray(32));return Uint8Array.of(48,z.length+K.length,...z,...K)}import{randomUUID as oJ}from"crypto";var dJ="/app/local-runtime/session?register=vm_hands_v1",rJ="/app/local-runtime",MJ=25000,iJ=20000,sJ=1e4,wJ=5000,EJ=new Set(["pty.start","jobs.control","preview.serve.v1","display.stream.v1"]),YJ=75000,aJ=2000,nJ=1e4,s=20000;function OJ(J,Z){return typeof J==="string"&&/^[A-Za-z0-9._:-]{1,160}$/.test(J)?J:Z}class k extends Error{}var tJ=64;async function hJ(J,Z){let z=[...J.modelOps.get(Z)??[]];for(let K of z)K.abort.abort();await Promise.race([Promise.all(z.map((K)=>K.settled)),new Promise((K)=>setTimeout(K,wJ))])}async function eJ(J){let Z=[...J.personTerminals];for(let z of Z)z.abort.abort();if(Z.length)await Promise.race([Promise.all(Z.map((z)=>z.settled)),new Promise((z)=>setTimeout(z,wJ))]);return Z.length}async function m(J,Z,z){return await hJ(J,z),Z.unbind(z)}function a(J){for(let Z of J.outbox?.splice(0)??[])Z.reject(Error("vm_hands_attempt_ended"))}var _J=15000,JZ=1e4,ZZ=1000;async function BZ(J){let Z=Date.now(),z={deviceId:null,connection:null,turns:new Map,lostAt:0,receipts:[],attest:"pending",attestWaiters:[],modelOps:new Map,personTerminals:new Set,bindsStarting:0},K=J.log??(()=>{}),B=async(L)=>{for(let[j,E]of[...z.turns]){z.turns.delete(j),J.onTurn?.(j,null),a(E);let N=await m(z,J.agent,j).catch(()=>null);if(N)z.receipts.push({turn:E,failure:"vm_hands_bind_lost",unbound:N});K("vm_hands.bound_dropped",{reason:L})}};try{for(let L=0;!J.signal.aborted;L++){let j=await $Z(J,z).catch((N)=>{if(N instanceof W&&z.deviceId===null&&N.code==="vm_hands_no_session"&&Date.now()-Z<nJ)return{closeCode:0,closeReason:"vm_hands_no_session"};if(N instanceof W&&z.deviceId===null)throw N;return{closeCode:0,closeReason:N instanceof Error?N.message:String(N)}});if(K("vm_hands.session_closed",{close_code:j.closeCode,reason:j.closeReason.slice(0,120),registered:z.deviceId!==null}),j.closeCode===4401||z.attest==="refused")return;if(J.signal.aborted)return;if(z.turns.size&&Date.now()-z.lostAt>=YJ)await B("reconnect_deadline");if(z.served)z.served=!1,L=0;let E=j.closeReason==="drain_reconnect"?0:j.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(L,5),2000):z.turns.size?Math.min(250*2**Math.min(L,5),5000,Math.max(0,z.lostAt+YJ-Date.now())):Math.min(500*2**L,30000);if(await new Promise((N)=>setTimeout(N,E)),z.turns.size&&Date.now()-z.lostAt>=YJ)await B("reconnect_deadline")}}finally{await B("session_ended")}}async function $Z(J,Z){let z=Z.deviceId,K=J.log??(()=>{}),B=z?`/app/local-runtime/session?device_id=${encodeURIComponent(z)}`:dJ,L=`${J.apiOrigin.replace(/^http/,"ws")}${B}`,j=new WebSocket(L),E=0,N="",_=new Map,H=[],T=null,kJ=new Promise(($)=>{j.onclose=(Q)=>{E=Q.code,N=Q.reason;for(let G of _.values())G.reject(new k(`session closed ${Q.code}`));for(let G of Z.attestWaiters.splice(0))G(!1);_.clear(),$()}});j.onmessage=($)=>{let Q;try{Q=JSON.parse(String($.data))}catch{j.close(4400);return}if(Q.t==="res"){let G=Q;_.get(G.id)?.resolve({status:G.status,body:G.body}),_.delete(G.id);return}if(Q.t==="reconnect"){let G=Math.max(0,Math.min(Number(Q.after_ms)||0,ZZ));K("vm_hands.drain_reconnect",{after_ms:G}),setTimeout(()=>{try{j.close(4001,"drain_reconnect")}catch{}},G).unref?.();return}if(!T?.(Q))H.push(Q)};let b=($,Q)=>new Promise((G,X)=>{let U=H.findIndex((C)=>$.includes(C.t));if(U>=0){G(H.splice(U,1)[0]);return}let q=setTimeout(()=>{T=null,X(new W("vm_hands_no_register",`no ${$.join("/")} in ${Q} ms`))},Q);T=(C)=>{if(!$.includes(C.t))return!1;return clearTimeout(q),T=null,G(C),!0}}),c=($)=>j.send(JSON.stringify($)),g=($,Q)=>new Promise((G,X)=>{if(j.readyState!==WebSocket.OPEN){X(new k("session closed"));return}let U=oJ(),q=typeof Q.wait_ms==="number"?Q.wait_ms:0,C=setTimeout(()=>{if(!_.delete(U))return;X(new k(`no answer to ${$.split("/").pop()} in ${q+_J} ms`)),j.close(4000,"request_timeout")},q+_J);_.set(U,{reject:(Y)=>{clearTimeout(C),X(Y)},resolve:({status:Y,body:F})=>{clearTimeout(C);let P=null;try{P=F?JSON.parse(F):null}catch{}G({status:Y,json:P})}}),c({t:"req",id:U,path:`${rJ}${$}`,body:JSON.stringify(Q)})}),QJ=()=>j.close(1001,"stopping");J.signal.addEventListener("abort",QJ,{once:!0});let n,p=new Map,l=new Map,t=!1,e=new Set,JJ=new Set,ZJ=Promise.resolve(),u=!1;try{await new Promise((Y,F)=>{let P=setTimeout(()=>F(Error("session open timeout")),JZ);j.onopen=()=>{clearTimeout(P),K("vm_hands.ws_open",{}),Y()},j.onerror=()=>{clearTimeout(P),F(Error("session socket error"))}});let $=await b(["challenge"],5000);K("vm_hands.challenge",{});let Q=[],G=null,X;if(z){c(await J.agent.helloFrame($.challenge,Z.connection));let Y=await b(["ready"],1e4);if(typeof Y.vm_hands_connection==="string")Z.connection=Y.vm_hands_connection;if(X={device_id:z,...Y.cadence?{cadence:Y.cadence}:{}},typeof Y.vm_hands_probe_script==="string"){if(G=Y.vm_hands_probe_script,u=!0,J.agent.phase==="registered"&&!Z.turns.size)Z.attest="pending"}Z.served=!0,K("vm_hands.reconnected",{device_id:z});let F=Array.isArray(Y.vm_hands_binds)?Y.vm_hands_binds:Y.vm_hands_bind?[Y.vm_hands_bind]:[];for(let[P,D]of[...Z.turns]){if(F.some((O)=>O&&O.operation_id===D.claim.operation_id&&O.attempt_id===D.claim.attempt_id)){Q.push(D),K("vm_hands.bound_resumed",{operation_id:D.claim.operation_id});continue}Z.turns.delete(P),J.onTurn?.(P,null),a(D);let x=await m(Z,J.agent,P).catch(()=>null);if(x)Z.receipts.push({turn:D,failure:"vm_hands_bind_lost",unbound:x});K("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}else{c(await J.agent.registerFrame($.challenge)),K("vm_hands.register_sent",{});let Y=await b(["registered","register_refused"],1e4);if(Y.t==="register_refused")throw new W(Y.code,"register refused");J.agent.registered();let F=Y;if(X=F,Z.deviceId=F.device_id,typeof F.vm_hands_connection==="string")Z.connection=F.vm_hands_connection;if(typeof F.vm_hands_probe_script==="string"){if(G=F.vm_hands_probe_script,u=!0,J.agent.phase==="registered"&&!Z.turns.size)Z.attest="pending"}Z.served=!0,K("vm_hands.registered",{device_id:X.device_id})}let U=async()=>{let Y=await g("/heartbeat",await J.heartbeat());if(Y.status>=300)throw Error(`heartbeat ${Y.status}`)};await U();let q=X.cadence?.presence_interval_ms??30000;if(n=setInterval(()=>{U().catch(()=>j.close())},q),G&&Z.attest!=="accepted"&&J.agent.phase==="registered"&&!Z.turns.size)SJ(G,$.challenge);let C=(Y,F)=>{l.set(Y,F().catch(async(P)=>{if(await XJ(P,Y),P instanceof k)j.close();else await $J().catch(()=>{return})}).finally(()=>{l.delete(Y)}))};try{await $J();for(let Y of Q)Y.flush=()=>FJ(Y),Y.flush(),C(Y.claim.attempt_id,()=>WJ(Y));while(!J.signal.aborted&&j.readyState===WebSocket.OPEN){let Y=await g("/operations/claim",{wait_ms:Math.min(X.cadence?.claim_wait_ms??MJ,MJ)});if(Y.status===204||!Y.json)continue;if(Y.status>=300)throw Error(`claim ${Y.status}`);let F=Y.json;if(F.capability==="hands.connect"){if(l.has(F.attempt_id)){w({claim:F,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}C(F.attempt_id,()=>HJ(F))}else VJ(F).catch(()=>{return})}}catch(Y){await XJ(Y,null)}}finally{if(n)clearInterval(n);J.signal.removeEventListener("abort",QJ);for(let $ of Z.turns.values())$.flush=null;j.close(),await kJ,await Promise.all([...l.values()]);for(let $ of J.agent.liveBindIds){if(Z.turns.has($))continue;let Q=await m(Z,J.agent,$).catch(()=>null),G=p.get($);if(Q&&G)Z.receipts.push({turn:{...G,eventSeq:G.eventSeq+1},failure:"vm_hands_bind_lost",unbound:Q});K("vm_hands.bound_dropped",{reason:"bound_after_loss"})}for(let $ of e)$.abort()}return{closeCode:E,closeReason:N};async function XJ($,Q){if($ instanceof k){if(!t&&Z.turns.size)Z.lostAt=Date.now();t=!0}else{let G=Q!==null?[Q]:[...new Set([...Z.turns.keys(),...J.agent.liveBindIds])];if(Q===null)t=!0;for(let X of G){let U=Z.turns.get(X);if(Z.turns.delete(X),U)a(U),J.onTurn?.(X,null);if(J.agent.liveBindIds.includes(X)){let q=await m(Z,J.agent,X).catch(()=>null),C=p.get(X)??U;if(q&&C)Z.receipts.push({turn:{...C,eventSeq:C.eventSeq+1},failure:"vm_hands_bind_lost",unbound:q})}}}K("vm_hands.session_lost",{error:$ instanceof Error?$.message:String($),bound_kept:Z.turns.size})}function w($){let Q=$.claim,G={attempt_id:Q.attempt_id,attempt_token:Q.attempt_token},X=encodeURIComponent(Q.operation_id);return{fence:G,op:X,complete:(q,C={})=>g(`/operations/${X}/complete`,{...G,status:q,...C}),emit:(q,C)=>{let Y=($.chain??Promise.resolve()).catch(()=>{return}).then(()=>U(q,C));return $.chain=Y,Y}};async function U(q,C){let Y=$.eventSeq,F=(O)=>g(`/operations/${X}/events`,{...G,event_seq_start:O,events:[{kind:q,payload:{sequence:O,capability:String(Q.capability??"hands.connect"),data:C}}]}),P=Y,D=await F(P),x=D.status===409?D.json?.expected_event_seq:void 0;if(typeof x==="number"&&x===Y+1)D={status:200,json:{duplicate:!0}};else if(typeof x==="number"&&x>=0&&x!==Y)P=x,D=await F(P);if(D.status<300)$.eventSeq=P+1;return D}}function gJ($){return(Q,G)=>new Promise((X,U)=>{if(Z.turns.get($.claim.attempt_id)!==$){U(Error("vm_hands_attempt_ended"));return}if($.outbox??=[],$.outbox.length>=tJ){U(Error("vm_hands_outbox_full"));return}$.outbox.push({kind:Q,data:G,resolve:X,reject:U}),$.flush?.()})}function FJ($){if(JJ.has($))return;JJ.add($),(async()=>{try{while($.outbox?.length&&Z.turns.get($.claim.attempt_id)===$&&j.readyState===WebSocket.OPEN){let Q=$.outbox[0],G;try{G=await w($).emit(Q.kind,Q.data)}catch(X){if(X instanceof k)return;G={status:500}}if($.outbox.shift(),G.status<300)Q.resolve();else Q.reject(Error(`${Q.kind} refused ${G.status}`))}}finally{JJ.delete($)}})()}async function SJ($,Q){try{let G=await J.agent.attestFrame($,Q);if(j.readyState!==WebSocket.OPEN)return;c(G);let X=await b(["attested","attest_refused"],15000);Z.attest=X.t==="attested"?"accepted":"refused";for(let U of Z.attestWaiters.splice(0))U(Z.attest==="accepted");if(K("vm_hands.attest",{result:Z.attest,exit_code:G.exit_code,...X.t==="attest_refused"?{code:String(X.code??"")}:{}}),Z.attest==="refused")j.close(4401,"attest_refused")}catch(G){K("vm_hands.attest_failed",{code:G instanceof W?G.code:"probe_error"});for(let X of Z.attestWaiters.splice(0))X(!1);if(Z.attest!=="accepted")j.close(4000,"attest_unanswered")}}async function HJ($){let Q=u&&Z.attest==="pending",G=$.vm_hands_attest,X=G;if(Z.attest==="refused"){K("vm_hands.claim_attest_refused",{said:typeof G==="string"?G.slice(0,16):typeof G,local:Z.attest}),await w({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(X==="accepted"){if(!Q&&Z.attest!=="accepted"){Z.attest="accepted";for(let M of Z.attestWaiters.splice(0))M(!0)}}else if(X!=="pending"||!Q&&Z.attest!=="accepted"){K("vm_hands.claim_attest_refused",{said:typeof G==="string"?G.slice(0,16):typeof G,local:Z.attest}),await w({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(Z.attest!=="accepted"){let M=Date.parse($.lease_until)-Date.now()-5000,V=Math.max(0,Math.min(s,Number.isFinite(M)?M:s));if(!await new Promise((d)=>{let A=setTimeout(()=>d(!1),V);Z.attestWaiters.push((h)=>{clearTimeout(A),d(h)})})){await w({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let U={claim:$,eventSeq:0},{complete:q,emit:C}=w(U),Y;try{if($.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not hands.connect");Y=!KJ($)}catch(M){K("vm_hands.bind_refused",{code:M instanceof W?M.code:"unexpected"}),await q("failed",{error_code:M instanceof W?M.code:"vm_hands_bind_invalid"});return}let F;Z.bindsStarting++;try{let M=await eJ(Z);if(M)K("vm_hands.person_terminals_closed",{count:M});F=await J.agent.bind(xJ($))}catch(M){K("vm_hands.bind_refused",{code:M instanceof W?M.code:"unexpected"}),await q("failed",{error_code:M instanceof W?M.code:"vm_hands_bind_failed"});return}finally{Z.bindsStarting--}let P={...F.ready_data??J.readyData({launchId:F.launch_id,claim:$})};if(Y)delete P.environment_installed;let D=!Y&&F.snapshot_revision!==null&&F.snapshot_id!==null?{environment_installed:{snapshot_id:F.snapshot_id,installed_revision:F.snapshot_revision}}:{};p.set($.attempt_id,{claim:$,launchId:F.launch_id,readyData:P,eventSeq:U.eventSeq,ackSeq:-1});let x=await C("hands.ready",{...P,...D,vm_hands:{layout:F.layout,policy_digest:F.policy_digest,launch_id:F.launch_id}});if(p.delete($.attempt_id),x.status>=300){await hJ(Z,$.attempt_id),await J.agent.boundRefused($.attempt_id),await q("failed",{error_code:OJ(x.json?.error,"vm_hands_probe_failed")});return}let O={claim:$,launchId:F.launch_id,readyData:P,eventSeq:U.eventSeq,ackSeq:-1};Z.turns.set($.attempt_id,O),O.flush=()=>FJ(O),J.onTurn?.($.attempt_id,gJ(O)),await WJ(O)}async function WJ($){let{fence:Q,op:G}=w($),X=null,U=null,q=J.agent.executorExited($.claim.attempt_id).then((C)=>{return U=C,null});J:for(;;){let C=await Promise.race([q,g(`/operations/${G}/heartbeat`,{...Q,control_ack_seq:$.ackSeq,wait_ms:iJ})]);if(!C){X="vm_hands_executor_exited",K("vm_hands.executor_exited",{reason:U});break}if(C.status>=300)break;let Y=(C.json?.controls??[]).slice().sort((F,P)=>F.seq-P.seq);for(let F of Y){if(F.seq<=$.ackSeq)continue;if(F.kind==="operation.cancel"||F.kind==="cancel"){$.ackSeq=F.seq;break J}if(F.kind===TJ)try{await yJ($,F.payload??{})}catch(P){if(P instanceof k)throw P;X=P instanceof W?P.code:"environment_unavailable";let D=P&&typeof P==="object"&&"code"in P&&typeof P.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(P.code)?P.code:null;K("vm_hands.environment_refused",{code:X,cause:D});break J}$.ackSeq=F.seq}}await vJ($,X)}async function VJ($){let Q=$,G={claim:Q,eventSeq:0},{complete:X,emit:U,fence:q,op:C}={...w(G)},Y=$.vm_hands_origin==="person"?"person":"model",F=String($.capability??"");if(!J.executeOp){await X("failed",{error_code:"vm_hands_op_unsupported"});return}if($.vm_hands_attest==="accepted"&&Z.attest==="pending"&&!(u&&Z.attest==="pending")){Z.attest="accepted";for(let A of Z.attestWaiters.splice(0))A(!0)}if(Z.attest!=="accepted"){let A=Date.parse(String($.lease_until??""))-Date.now()-5000,h=Z.attest==="refused"?0:Math.max(0,Math.min(s,Number.isFinite(A)?A:s));if(!(h>0&&await new Promise((jJ)=>{let IJ=setTimeout(()=>jJ(!1),h);Z.attestWaiters.push((RJ)=>{clearTimeout(IJ),jJ(RJ)})}))){await X("failed",{error_code:"vm_hands_unattested"});return}}let P=J.agent.bindIdForRun(Q.run_id);if(Y==="model"&&P===null){await X("failed",{error_code:"vm_hands_not_bound"});return}let D=F==="pty.start"&&Y==="person"&&!$.authority;if(D&&(J.agent.liveBindIds.length>0||Z.bindsStarting>0)){await X("failed",{error_code:"vm_hands_bound"});return}if(EJ.has(F)&&!D&&J.agent.liveBindIds.length===0){await X("failed",{error_code:"vm_hands_not_bound"});return}if(Y==="model"&&P||EJ.has(F)&&!D)J.agent.opServed();let x=new AbortController;e.add(x);let O,M=new Promise((A)=>{O=A}),V={abort:x,settled:M};if(D)Z.personTerminals.add(V);if(Y==="model"&&P){let A=Z.modelOps.get(P)??new Set;A.add(V),Z.modelOps.set(P,A),await J.agent.environmentInstalled(P,aJ,x.signal)}let o=-1,d=setInterval(()=>{g(`/operations/${C}/heartbeat`,{...q,control_ack_seq:o,wait_ms:0}).then((A)=>{if(A.status>=300){x.abort();return}let h=A.json?.controls??[];for(let S of h)if(o=Math.max(o,S.seq),S.kind==="operation.cancel"||S.kind==="cancel")x.abort()},()=>x.abort())},sJ);try{let A=await J.executeOp({kind:Y,claim:$,...Y==="model"&&P?{bindId:P}:{},signal:x.signal,emit:async(S)=>{await U(S.kind,S.data??{})}}),h=await X(A.status,{...A.result?{result:A.result}:{},...A.error_code?{error_code:OJ(A.error_code,"vm_hands_op_failed")}:{}});K("vm_hands.op",{capability:F,kind:Y,status:A.status,code:A.error_code??null,...h.status>=300?{complete_status:h.status,complete_error:String(h.json?.error??"").slice(0,64)}:{}})}finally{if(clearInterval(d),e.delete(x),P)Z.modelOps.get(P)?.delete(V);Z.personTerminals.delete(V),O()}}async function vJ($,Q){let G=$.claim.attempt_id;if(Z.turns.get(G)===$)Z.turns.delete(G);J.onTurn?.(G,null),a($);let X=await m(Z,J.agent,G);Z.receipts.push({turn:$,failure:Q,unbound:X}),await $J()}function $J(){return ZJ=ZJ.then(PJ,PJ),ZJ}async function PJ(){while(Z.receipts.length){let{turn:$,failure:Q,unbound:G}=Z.receipts[0],{complete:X,emit:U}=w($);try{if(await U("hands.stopped",{...$.readyData,reason_code:Q?"failed":"cancelled",killed_verified:G.killed_verified,shredded:G.shredded,...G.srt_fallbacks?{vm_hands_srt_fallbacks:G.srt_fallbacks}:{}}),Q)await X("failed",{error_code:Q});else await X("cancelled",{error_code:"driver_stopped"})}catch(q){if(q instanceof k)return}Z.receipts.shift()}}async function yJ($,Q){let{fence:G,op:X}=w($),U=Q.snapshot_id;if(Q.version!==1||typeof U!=="string"||Object.keys(Q).length!==2)throw new W("vm_hands_env_invalid","invalid environment delivery");let q=await g(`/operations/${X}/environment`,{...G,snapshot_id:U}),C=q.json?.environment_sealed;if(q.status!==200||!C||q.json?.payload!==void 0)throw new W("vm_hands_env_invalid","environment not delivered sealed");let Y=await J.agent.deliverEnvironment({attemptId:$.claim.attempt_id,snapshotId:U,deviceId:Z.deviceId??"",sealed:C});if((await g(`/operations/${X}/environment-ack`,{...G,...Y})).status>=300)throw new W("vm_hands_env_ack_refused","environment ack refused")}}
5
5
  export{QZ as xa,lJ as ya,BZ as za};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ci as v,Fi as _,Hi as w,Li as S,Mi as x}from"./vm-hands-entry-lite-x4j4058x.js";import{Ri as I}from"./vm-hands-entry-lite-1j9r1fca.js";import{pj as O}from"./vm-hands-entry-lite-p8662x7z.js";import{Ij as L,Jj as T}from"./vm-hands-entry-lite-ha1ej910.js";import{ak as G}from"./vm-hands-entry-lite-h2xemq1f.js";import{spawnSync as l}from"child_process";import{dirname as B}from"path";import{spawn as y}from"child_process";import{accessSync as c,constants as g}from"fs";import{basename as h,join as m}from"path";var j=null;function U(q){if(j===q)j=null;if(q.exitCode===null&&q.signalCode===null)q.kill("SIGTERM")}var C=(q,z)=>{if(j)U(j);let J=m(q,v);try{c(J,g.X_OK)}catch{return()=>{}}let F;try{F=y(J,["--app",q,"--name",h(q,".app"),"--permission",z==="screen"?"screen_recording":"accessibility"],{detached:!0,stdio:"ignore"})}catch{return()=>{}}return F.on("error",()=>{if(j===F)j=null}),F.once("exit",()=>{if(j===F)j=null}),F.unref(),j=F,()=>U(F)};var M=`Reason permissions
2
+ import{Di as v,Gi as _,Ii as w,Mi as S,Ni as x}from"./vm-hands-entry-lite-jn8v1fp1.js";import{Si as I}from"./vm-hands-entry-lite-tbps80f1.js";import{qj as O}from"./vm-hands-entry-lite-5wmh1c1y.js";import{Jj as L,Kj as T}from"./vm-hands-entry-lite-avstvbbc.js";import{bk as G}from"./vm-hands-entry-lite-hw8vgsmm.js";import{spawnSync as l}from"child_process";import{dirname as B}from"path";import{spawn as y}from"child_process";import{accessSync as c,constants as g}from"fs";import{basename as h,join as m}from"path";var j=null;function U(q){if(j===q)j=null;if(q.exitCode===null&&q.signalCode===null)q.kill("SIGTERM")}var C=(q,z)=>{if(j)U(j);let J=m(q,v);try{c(J,g.X_OK)}catch{return()=>{}}let F;try{F=y(J,["--app",q,"--name",h(q,".app"),"--permission",z==="screen"?"screen_recording":"accessibility"],{detached:!0,stdio:"ignore"})}catch{return()=>{}}return F.on("error",()=>{if(j===F)j=null}),F.once("exit",()=>{if(j===F)j=null}),F.unref(),j=F,()=>U(F)};var M=`Reason permissions
3
3
 
4
4
  Usage:
5
5
  reason permissions [--json]
@@ -14,7 +14,7 @@ The macOS privacy permissions of this computer's Reason worker:
14
14
  allow asks for each missing one, or the one named. macOS cannot ask for Full
15
15
  Disk Access: allow disk opens its pane, shows the file to add in Finder and
16
16
  waits until the worker has it.
17
- `,D="x-apple.systempreferences:com.apple.preference.security",a="curl -fsSL https://reasonmachines.com/install.sh | bash",d=180000,n=2000,E=["screen","accessibility","disk"],N={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${D}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${D}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${D}?Privacy_AllFiles`}};function k(q){return q.executable}function p(q,z){if(q==="computer_use_identity_missing")return`Reason's background identity is not installed (${q}); reinstall Reason: ${a}`;if(q==="computer_use_identity_outdated")return`Reason's background identity is outdated (${w(z)??"unknown"}; this CLI is ${O}) (${q}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${q}); run the installed \`reason\``}function s(q=I()){let z=S(q);if(z.length>0)return{state:"ready",path:B(B(B(z[0]))),prefix:z};let J=x(z,q)??"computer_use_identity_unavailable";return{state:J,path:_(q),detail:p(J,q)}}function u(){return{identity:()=>s(),grants:(q)=>L(q),request:(q,z)=>T(q,z),worker:async()=>(await import("./status-f146chye.js")).connectionMacState(),open:(q)=>{l("/usr/bin/open",q,{stdio:"ignore",timeout:1e4})},tile:C,restartConnection:async()=>(await import("./connect-cli-ev4xex04.js")).restartConnection(),sleep:(q)=>new Promise((z)=>setTimeout(z,q)),now:()=>Date.now()}}function P(q,z,J){if(q.state!=="ready"||!z)return"unknown";return z[J]?"granted":"missing"}async function b(q){let z=q.identity(),J=z.state==="ready"?await q.grants(z.prefix):null,F=await q.worker(),X=F?k(F):null,Q=!X||F?.full_disk_access==="unknown"?"unknown":F?.full_disk_access==="granted"?"granted":"missing",$=(K,H,Z)=>{let{label:R,purpose:W,level:V}=N[K];return{id:K,label:R,purpose:W,level:V,state:H,holder:Z}};return{identity:{state:z.state,path:z.path,detail:z.state==="ready"?null:z.detail},worker_detail:X?null:"Full Disk Access is read from this computer's running worker; `reason connect` starts it.",permissions:[$("screen",P(z,J,"screen"),z.path),$("accessibility",P(z,J,"accessibility"),z.path),$("disk",Q,X)]}}function Rq(q){let z=q.identity.state==="ready"?null:q.identity.state,J=q.permissions.filter((Q)=>Q.state==="granted").length,F=[...z?[z]:[],...q.permissions.filter((Q)=>Q.state!=="granted"&&!(z&&Q.id!=="disk")).map((Q)=>`${Q.label} ${Q.state}`)],X=!z&&q.permissions.some((Q)=>Q.state==="missing");return`Permissions: ${J} of ${q.permissions.length}${F.length>0?` (${F.join(", ")})`:""}`+(X?" \u2014 reason permissions allow":F.length>0?" \u2014 reason permissions":"")}function t(q){let z=[];if(q.identity.detail)z.push(q.identity.detail);z.push(`Reason: ${q.identity.path}`);let J=q.permissions.find((F)=>F.id==="disk");z.push(J?.holder?`Worker: ${J.holder}`:`Worker: ${q.worker_detail}`),z.push("");for(let F of q.permissions){let X=`${F.label}${F.level==="recommended"?" (recommended)":""}`;z.push(` ${F.id.padEnd(13)} ${F.state.padEnd(7)} ${X}: ${F.purpose}`)}if(q.permissions.some((F)=>F.state==="missing"))z.push("","Allow the missing ones: reason permissions allow");return`${z.join(`
17
+ `,D="x-apple.systempreferences:com.apple.preference.security",a="curl -fsSL https://reasonmachines.com/install.sh | bash",d=180000,n=2000,E=["screen","accessibility","disk"],N={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${D}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${D}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${D}?Privacy_AllFiles`}};function k(q){return q.executable}function p(q,z){if(q==="computer_use_identity_missing")return`Reason's background identity is not installed (${q}); reinstall Reason: ${a}`;if(q==="computer_use_identity_outdated")return`Reason's background identity is outdated (${w(z)??"unknown"}; this CLI is ${O}) (${q}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${q}); run the installed \`reason\``}function s(q=I()){let z=S(q);if(z.length>0)return{state:"ready",path:B(B(B(z[0]))),prefix:z};let J=x(z,q)??"computer_use_identity_unavailable";return{state:J,path:_(q),detail:p(J,q)}}function u(){return{identity:()=>s(),grants:(q)=>L(q),request:(q,z)=>T(q,z),worker:async()=>(await import("./status-00w678nv.js")).connectionMacState(),open:(q)=>{l("/usr/bin/open",q,{stdio:"ignore",timeout:1e4})},tile:C,restartConnection:async()=>(await import("./connect-cli-bc074w36.js")).restartConnection(),sleep:(q)=>new Promise((z)=>setTimeout(z,q)),now:()=>Date.now()}}function P(q,z,J){if(q.state!=="ready"||!z)return"unknown";return z[J]?"granted":"missing"}async function b(q){let z=q.identity(),J=z.state==="ready"?await q.grants(z.prefix):null,F=await q.worker(),X=F?k(F):null,Q=!X||F?.full_disk_access==="unknown"?"unknown":F?.full_disk_access==="granted"?"granted":"missing",$=(K,H,Z)=>{let{label:R,purpose:W,level:V}=N[K];return{id:K,label:R,purpose:W,level:V,state:H,holder:Z}};return{identity:{state:z.state,path:z.path,detail:z.state==="ready"?null:z.detail},worker_detail:X?null:"Full Disk Access is read from this computer's running worker; `reason connect` starts it.",permissions:[$("screen",P(z,J,"screen"),z.path),$("accessibility",P(z,J,"accessibility"),z.path),$("disk",Q,X)]}}function Rq(q){let z=q.identity.state==="ready"?null:q.identity.state,J=q.permissions.filter((Q)=>Q.state==="granted").length,F=[...z?[z]:[],...q.permissions.filter((Q)=>Q.state!=="granted"&&!(z&&Q.id!=="disk")).map((Q)=>`${Q.label} ${Q.state}`)],X=!z&&q.permissions.some((Q)=>Q.state==="missing");return`Permissions: ${J} of ${q.permissions.length}${F.length>0?` (${F.join(", ")})`:""}`+(X?" \u2014 reason permissions allow":F.length>0?" \u2014 reason permissions":"")}function t(q){let z=[];if(q.identity.detail)z.push(q.identity.detail);z.push(`Reason: ${q.identity.path}`);let J=q.permissions.find((F)=>F.id==="disk");z.push(J?.holder?`Worker: ${J.holder}`:`Worker: ${q.worker_detail}`),z.push("");for(let F of q.permissions){let X=`${F.label}${F.level==="recommended"?" (recommended)":""}`;z.push(` ${F.id.padEnd(13)} ${F.state.padEnd(7)} ${X}: ${F.purpose}`)}if(q.permissions.some((F)=>F.state==="missing"))z.push("","Allow the missing ones: reason permissions allow");return`${z.join(`
18
18
  `)}
19
19
  `}async function A(q,z){let J=z.now()+d;for(;;){if(await q())return!0;if(z.now()>=J)return!1;await z.sleep(n)}}async function o(q,z){let J=z.host??u(),{io:F}=z,X=await b(J),Q=X.permissions.filter((Z)=>q.includes(Z.id)&&Z.state!=="granted");if(Q.length===0)return F.stdout.write(`Reason permissions: ${q.map((Z)=>N[Z].label).join(", ")} already allowed.
20
20
  `),0;let $=!1,K=!1,H=J.identity();for(let Z of Q){let{label:R,pane:W}=N[Z.id];if(Z.id!=="disk"){if(H.state!=="ready"){if(!$)F.stderr.write(`Reason permissions: ${H.detail}
@@ -34,4 +34,4 @@ ${M}`),1;if(F.command==="help")return J.stdout.write(M),0;let X=z.platform??proc
34
34
  `:`Reason permissions: macOS privacy permissions do not apply on this computer.
35
35
  `),0;let Q=z.host??u();if(F.command==="allow")return o(F.ids,{io:J,wait:!0,host:Q});let $=await b(Q);return J.stdout.write(F.json?`${JSON.stringify({platform:X,applicable:!0,...$},null,2)}
36
36
  `:t($)),0}
37
- export{C as pi,M as qi,E as ri,k as si,s as ti,b as ui,Rq as vi,t as wi,o as xi,i as yi,Vq as zi};
37
+ export{C as qi,M as ri,E as si,k as ti,s as ui,b as vi,Rq as wi,t as xi,o as yi,i as zi,Vq as Ai};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{r as v0}from"./vm-hands-entry-lite-5xtkyx25.js";import{v as n1,x as x6,y as c9}from"./vm-hands-entry-lite-463aheya.js";import{A as X2,B as E6,C as $4,D as J4,E as V6,F as m0,J as G6,K as A$}from"./vm-hands-entry-lite-taw01cp4.js";import{V as g2,oa as e0,ra as u1,ta as VJ}from"./vm-hands-entry-lite-c0m2jewa.js";import{Ba as f5,Ca as m5,Da as e4,Ea as $8,Fa as DJ,Ga as WJ,Ha as _9,Ia as d8,Ja as Q8,Ka as L0,La as I1,Ma as C1,Na as I0,Oa as g1,Pa as p8,Qa as B5,Ra as f3,Sa as t8,Wa as r8,cb as AJ,db as RJ,eb as PJ,fb as IJ,gb as D9}from"./vm-hands-entry-lite-c7krpmd8.js";import{$b as _J,Ab as x8,Bb as J8,Cb as Z8,Db as MJ,Eb as TJ,Gb as u,Hb as e,Ib as s,Jb as c,Kb as H8,Lb as FJ,Mb as N1,Pb as t2,Qb as r2,Rb as R6,Sb as P6,Tb as I6,Ub as S0,Vb as J0,Wb as g,Xb as j9,Yb as j1,Zb as i1,_b as N0,ec as V5,gc as S4,ib as cJ,jc as I2,lb as L8,lc as u8,mb as F8,mc as i3,oc as S8,pb as U8,rb as A8,sc as jJ,tc as l3,ub as R8,zb as E8}from"./vm-hands-entry-lite-qbnz4h30.js";import{xc as X8}from"./vm-hands-entry-lite-22we2jrv.js";import{Ec as g8}from"./vm-hands-entry-lite-gxjxx1r2.js";import{Jc as P8,Kc as I8,Rc as C8}from"./vm-hands-entry-lite-j05685sg.js";import{Xc as H$}from"./vm-hands-entry-lite-wry37am5.js";import{nd as o4}from"./vm-hands-entry-lite-r5y08n0q.js";import{Bd as v5,Cd as g5,vd as c8,yd as OJ}from"./vm-hands-entry-lite-n867d88m.js";import{Fd as p$,Hd as Q$,Id as R$,Jd as U1,Ld as B6,Md as S6,Nd as b6,Pd as H1,Qd as w6,Rd as b9,Sd as y6,Td as s2,Ud as M$,Vd as A4,Wd as a2}from"./vm-hands-entry-lite-gzxxsjmr.js";import{Ae as HJ,Be as qJ,cf as r4,kf as J6,lf as n$,vf as Z2,we as L2}from"./vm-hands-entry-lite-szfy3kx7.js";import{If as C6,Jf as m2,Mf as zJ,Pf as w1,Rf as o6,Sf as e6,Xf as n8}from"./vm-hands-entry-lite-07er2w8q.js";import{jg as V0,kg as $2,lg as xJ,mg as SJ,ng as i$,og as N3,pg as z2,qg as K4,sg as A2,tg as b$,ug as k0,vg as t$,wg as R2,zg as w$}from"./vm-hands-entry-lite-s98hjhz3.js";import{Cg as d1,Dg as v8}from"./vm-hands-entry-lite-3ew5ftk0.js";import{Ig as z8}from"./vm-hands-entry-lite-v08mjs3f.js";import{Zh as Z$,bi as W$,ci as P0,di as i9,ei as O6,fi as z6,hi as q2,ii as A6,ji as T9,ki as O4,li as z4,mi as r$}from"./vm-hands-entry-lite-5kgvss4p.js";import{ni as v1,oi as z1}from"./vm-hands-entry-lite-r6pap1kh.js";import{Ei as F6,Mi as l8,Ni as L9,Pi as Y8}from"./vm-hands-entry-lite-x4j4058x.js";import{Ri as H0,Ti as QJ}from"./vm-hands-entry-lite-1j9r1fca.js";import{pj as r}from"./vm-hands-entry-lite-p8662x7z.js";import{Oj as K}from"./vm-hands-entry-lite-kv0qat0x.js";import{Rj as LJ}from"./vm-hands-entry-lite-jn95s3j4.js";import{Wj as h0}from"./vm-hands-entry-lite-ygx9kj92.js";import{ak as aV}from"./vm-hands-entry-lite-h2xemq1f.js";import{spawn as k6,spawnSync as iV}from"child_process";import{closeSync as h6,mkdirSync as nV,openSync as f6,readdirSync as tV,realpathSync as X$,rmSync as M1}from"fs";import{hostname as rV}from"os";import{dirname as w9,join as F0,resolve as oV}from"path";import{createHash as J7}from"crypto";import{unlinkSync as Z7}from"fs";import{platform as Q7}from"os";import{join as X7}from"path";var s9=K.discriminatedUnion("store",[K.strictObject({version:K.literal(1),store:K.literal("keychain")}),K.strictObject({version:K.literal(1),store:K.literal("file"),api_key:K.string().min(1).max(4096)})]),S$=($)=>X7($,"api-key.json");function F$($){let J=J7("sha256").update(`reason-connect-api-key
2
+ import{r as v0}from"./vm-hands-entry-lite-0763vz5v.js";import{v as n1,x as x6,y as c9}from"./vm-hands-entry-lite-hfq6jjnh.js";import{A as X2,B as E6,C as $4,D as J4,E as V6,F as m0,J as G6,K as A$}from"./vm-hands-entry-lite-zn303jrg.js";import{V as g2,oa as e0,ra as u1,ta as VJ}from"./vm-hands-entry-lite-t4gcrmbp.js";import{Ba as f5,Ca as m5,Da as e4,Ea as $8,Fa as DJ,Ga as WJ,Ha as _9,Ia as d8,Ja as Q8,Ka as L0,La as I1,Ma as C1,Na as I0,Oa as g1,Pa as p8,Qa as B5,Ra as f3,Sa as t8,Wa as r8,cb as AJ,db as RJ,eb as PJ,fb as IJ,gb as D9}from"./vm-hands-entry-lite-k8as28ss.js";import{$b as _J,Ab as x8,Bb as J8,Cb as Z8,Db as MJ,Eb as TJ,Gb as u,Hb as e,Ib as s,Jb as c,Kb as H8,Lb as FJ,Mb as N1,Pb as t2,Qb as r2,Rb as R6,Sb as P6,Tb as I6,Ub as S0,Vb as J0,Wb as g,Xb as j9,Yb as j1,Zb as i1,_b as N0,ec as V5,gc as S4,ib as cJ,jc as I2,lb as L8,lc as u8,mb as F8,mc as i3,oc as S8,pb as U8,rb as A8,sc as jJ,tc as l3,ub as R8,zb as E8}from"./vm-hands-entry-lite-dzkqn26g.js";import{xc as X8}from"./vm-hands-entry-lite-cwf21py1.js";import{Ec as g8}from"./vm-hands-entry-lite-gxjxx1r2.js";import{Jc as P8,Kc as I8,Rc as C8}from"./vm-hands-entry-lite-xhr0m9r0.js";import{Xc as H$}from"./vm-hands-entry-lite-wry37am5.js";import{nd as o4}from"./vm-hands-entry-lite-jpkf3569.js";import{Cd as v5,Dd as g5,wd as c8,zd as OJ}from"./vm-hands-entry-lite-vgj22wxq.js";import{Gd as p$,Id as Q$,Jd as R$,Kd as U1,Md as B6,Nd as S6,Od as b6,Qd as H1,Rd as w6,Sd as b9,Td as y6,Ud as s2,Vd as M$,Wd as A4,Xd as a2}from"./vm-hands-entry-lite-qkvwh6b7.js";import{Be as HJ,Ce as qJ,df as r4,lf as J6,mf as n$,wf as Z2,xe as L2}from"./vm-hands-entry-lite-fr2k6eah.js";import{Jf as C6,Kf as m2,Nf as zJ,Qf as w1,Sf as o6,Tf as e6,Yf as n8}from"./vm-hands-entry-lite-mhvfdbq5.js";import{Ag as w$,kg as V0,lg as $2,mg as xJ,ng as SJ,og as i$,pg as N3,qg as z2,rg as K4,tg as A2,ug as b$,vg as k0,wg as t$,xg as R2}from"./vm-hands-entry-lite-xj0p1ax7.js";import{Dg as d1,Eg as v8}from"./vm-hands-entry-lite-5y2kfnv2.js";import{Jg as z8}from"./vm-hands-entry-lite-vcm4389c.js";import{_h as Z$,ci as W$,di as P0,ei as i9,fi as O6,gi as z6,ii as q2,ji as A6,ki as T9,li as O4,mi as z4,ni as r$}from"./vm-hands-entry-lite-p1nb6n3r.js";import{oi as v1,pi as z1}from"./vm-hands-entry-lite-4xfs7y6w.js";import{Fi as F6,Ni as l8,Oi as L9,Qi as Y8}from"./vm-hands-entry-lite-jn8v1fp1.js";import{Si as H0,Ui as QJ}from"./vm-hands-entry-lite-tbps80f1.js";import{qj as r}from"./vm-hands-entry-lite-5wmh1c1y.js";import{Pj as K}from"./vm-hands-entry-lite-k7fkfytm.js";import{Sj as LJ}from"./vm-hands-entry-lite-jjkkee8q.js";import{Xj as h0}from"./vm-hands-entry-lite-kxtjkzzh.js";import{bk as aV}from"./vm-hands-entry-lite-hw8vgsmm.js";import{spawn as k6,spawnSync as iV}from"child_process";import{closeSync as h6,mkdirSync as nV,openSync as f6,readdirSync as tV,realpathSync as X$,rmSync as M1}from"fs";import{hostname as rV}from"os";import{dirname as w9,join as F0,resolve as oV}from"path";import{createHash as J7}from"crypto";import{unlinkSync as Z7}from"fs";import{platform as Q7}from"os";import{join as X7}from"path";var s9=K.discriminatedUnion("store",[K.strictObject({version:K.literal(1),store:K.literal("keychain")}),K.strictObject({version:K.literal(1),store:K.literal("file"),api_key:K.string().min(1).max(4096)})]),S$=($)=>X7($,"api-key.json");function F$($){let J=J7("sha256").update(`reason-connect-api-key
3
3
  ${$}`).digest("hex");return new i$($2(),Q7(),J)}function B3($,J,Z=F$($)){try{Z.deleteBinding(),Z.createBinding(new TextEncoder().encode(J)),c(S$($),{version:1,store:"keychain"});return}catch(Q){if(!(Q instanceof V0))throw Q}c(S$($),{version:1,store:"file",api_key:J})}function d0($,J=F$($)){if(!u(S$($)))return null;let Z=s9.parse(JSON.parse(s(S$($))));if(Z.store==="file")return Z.api_key;try{let Q=J.loadBinding();return Q?new TextDecoder().decode(Q):null}catch(Q){if(!(Q instanceof V0))throw Q;throw Error("worker_api_key_unreadable")}}function a9($,J=F$($)){if(!u(S$($)))return;if(s9.parse(JSON.parse(s(S$($)))).store==="keychain")try{J.deleteBinding()}catch(Z){if(!(Z instanceof V0))throw Z}Z7(S$($))}async function K3($,J){let Z;try{Z=await c9({env:{REASON_API_KEY:J,REASON_API_URL:$.apiOrigin},fetchImpl:S0($.proxy)})}catch(Q){if(Q instanceof m0&&(Q.status===401||Q.status===403))throw Error("worker_api_key_rejected");throw Q}if(!Z)throw Error("worker_api_key_rejected");if(!Z.scopes.includes("devices:write"))throw Error("worker_api_key_devices_write_required");return Z}import{readdirSync as z7,renameSync as A7,rmSync as y$}from"fs";import{join as q0}from"path";import{createHash as Y7}from"crypto";import{realpathSync as V7,statSync as G7,unlinkSync as J2}from"fs";import{platform as B7}from"os";import{join as b0}from"path";function d($){return{state:b0(g($),"device.json"),control:b0(g($),"control.json"),lock:b0(g($),"lifecycle.lock"),socket:b0(g($),"control.sock"),daemon:b0(g($),"daemon.json"),releaseCheck:b0(g($),"release-check.json"),updateDeferral:b0(g($),"update-deferral.json"),firstHeartbeat:b0(g($),"first-heartbeat.json")}}var K7=K.object({version:K.literal(1),device_id:K.string().min(1).max(160),offer:K.unknown().optional(),enrollment_ms:K.number().int().nonnegative().max(n$).optional()});function n9($,J,Z){e(g($),!0),c(d($).firstHeartbeat,{version:1,device_id:J,...Z.offer?{offer:Z.offer}:{},...Z.enrollmentMs!==void 0?{enrollment_ms:Z.enrollmentMs}:{}})}function U3($,J){let Z=d($).firstHeartbeat;try{if(!u(Z))return null;let Q=K7.safeParse(JSON.parse(s(Z)));if(J2(Z),!Q.success||Q.data.device_id!==J)return null;let X=Z2(Q.data.offer);return{...X?{offer:X}:{},...Q.data.enrollment_ms!==void 0?{enrollmentMs:Q.data.enrollment_ms}:{}}}catch{return null}}function T0($,J=!1){e(g($),J);let Z=["local-device.key","local-device.binding","device.json"].filter((Q)=>{let X=b0(g($),Q);if(!u(X))return!1;return s(X),!0});return $.lifetime==="persistent"&&Z.join()==="device.json"?H3($):new N3(g($))}function Q2($,J){T0($,!0),H7($);let Z=J??H3($),Q=new N3(g($));try{Z.deleteBinding(),Z.deleteKey(),Z.createFreshPublicKey()}catch(X){if(X instanceof V0)return Q;throw X}return Q.deleteBinding(),Q.deleteKey(),Z}function H3($){return new i$($2(),B7(),N7($))}function N7($){let J=q3($);return Y7("sha256").update(`reason-worker
4
4
  ${J?.directory??g($)}`).digest("hex")}function D1($,J){c(b0(g($),W1),{version:1,directory:q3($)?.directory??g($),devicePublicKey:J})}var W1="keychain-scope.json";function t9($){return u(b0(g($),W1))}var U7=K.strictObject({version:K.literal(1),directory:K.string().min(1),devicePublicKey:K.string().min(1)});function q3($){let J=b0(g($),W1);if(!u(J))return null;let Z=U7.safeParse(JSON.parse(s(J))),Q=d($).state;if(!Z.success||!u(Q))return null;return JSON.parse(s(Q))?.devicePublicKey===Z.data.devicePublicKey?Z.data:null}function H7($){let J=b0(g($),W1);if(!u(J))return;if(q3($))try{let Z=H3($);Z.deleteBinding(),Z.deleteKey()}catch(Z){if(!(Z instanceof V0))throw Z}J2(J)}function K$($){let J=V7($.workspaceRoot);if(J!==$.workspaceRoot||!G7(J).isDirectory()||!j1(J,$.stateDirectory))throw Error("worker_workspace_not_canonical_or_overlaps_state")}function o($){if(!u(g($)))return null;let J=b$(d($).state,{proofStore:T0($),repair:!1}),Z=J!==null&&i9($.apiOrigin,J.apiOrigin),Q=Z?[N0($),N0({...$,apiOrigin:J.apiOrigin})]:[N0($)];if(J&&(!Q.includes(J.worker?.configDigest??"")||J.worker.lifetime!==$.lifetime||J.apiOrigin!==$.apiOrigin&&!Z||J.roots.length>32||J.roots[0]?.path!==$.workspaceRoot||J.handsSlots!==$.slots))throw Error("worker_config_binding_mismatch");return J}var r9=K.strictObject({version:K.literal(1),drained:K.boolean(),revoked:K.boolean()});function $0($){let J=d($).control;return u(J)?r9.parse(JSON.parse(s(J))):{version:1,drained:!1,revoked:!1}}function R0($,J){c(d($).control,r9.parse(J))}function w0($){let J=T0($);J.deleteBinding(),J.deleteKey();let Z=b0(g($),W1);if(u(Z))J2(Z);let Q=d($).state;if(u(Q))J2(Q)}var q7=K.strictObject({read:K.boolean(),write:K.boolean(),execute:K.boolean(),discover_environment:K.boolean(),expose_mcp:K.literal(!1)}),M3=K.strictObject({version:K.literal(1),organization_id:K.string().min(1).max(160),enrollment_ticket:K.string().min(1).max(4096),code_verifier:K.string().regex(/^[A-Za-z0-9._~-]{43,128}$/),root_fingerprint_key:K.string().regex(/^[a-f0-9]{64}$/),root:K.strictObject({path_fingerprint:K.string().regex(/^[a-f0-9]{64}$/),permissions:q7,execution_mode:K.enum(["confined","host"]).default("confined")}),folders:K.array(K.strictObject({path_fingerprint:K.string().regex(/^[a-f0-9]{64}$/)})).min(1).max(31).optional()}),M7=K.object({device_id:K.string().min(1).max(160),organization_id:K.string().min(1).max(160),auth_scheme:K.literal("p256"),protocol_version:K.literal(2),roots:K.array(K.object({id:K.string().min(1),label:K.string(),path_fingerprint:K.string()})).min(1).max(32),headless:K.object({lifecycle:K.enum(["persistent","ephemeral"]),expires_at:K.iso.datetime({offset:!0})}),first_heartbeat:K.unknown().optional()}),T3=30000;class r0 extends Error{deviceRemoved;constructor($){super("worker_enrollment_rejected");this.deviceRemoved=$}}async function T7($,J,Z=fetch){let Q=await Z(`${$}/app/local-runtime/enroll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J),redirect:"error",signal:AbortSignal.timeout(T3)});if(!Q.ok){let X=Q.status===409?await Q.json().catch(()=>null):null;throw new r0(X?.error==="device_revoked")}return Q.json()}async function L3($,J,Z,Q){v0();let X=M3.parse(JSON.parse(s(J)));return o0($,X,Z,Q)}async function o0($,J,Z,Q=(Y,V)=>T7(Y,V,S0($.proxy)),X=performance.now()){let Y=e9($,J,Z),V=await Q($.apiOrigin,{...Y.request,enrollment_ticket:J.enrollment_ticket,code_verifier:J.code_verifier});return Y.receipt(V,X)}async function o9($,J,Z,Q,X=performance.now()){let Y=e9($,J,Z),V=await Q(Y.request,J.code_verifier);return V===null?null:Y.receipt(V,X)}function e9($,J,Z){if(v0(),J.root.execution_mode!==$.executionMode)throw Error("worker_enrollment_mode_mismatch");let Q=w$([$.workspaceRoot],J.root.permissions,Buffer.from(J.root_fingerprint_key,"hex"))[0];if(Q.path!==$.workspaceRoot||Q.pathFingerprint!==J.root.path_fingerprint)throw Error("worker_enrollment_root_mismatch");let X=($.folders??[]).map((B,U)=>{let M=w$([B],J.root.permissions,Buffer.from(J.root_fingerprint_key,"hex"))[0];if(M.path!==B||M.pathFingerprint!==J.folders?.[U]?.path_fingerprint)throw Error("worker_enrollment_root_mismatch");return M});if((J.folders?.length??0)!==X.length)throw Error("worker_enrollment_root_mismatch");let Y=[{...Q,label:"workspace"},...X],V;try{V=Z.loadPublicKey()}catch{V=Z.createFreshPublicKey()}return{request:{device_public_key:V,name:$.name,os:process.platform,architecture:process.arch,reason_runtime_version:r,bridge_version:r,protocol_version:2,capabilities:{supported_operations:[]},roots:Y.map((B)=>({label:B.label,path_fingerprint:B.pathFingerprint,permissions:J.root.permissions}))},receipt(B,U){let M=M7.parse(B);if(M.organization_id!==J.organization_id||M.roots.length!==Y.length||M.roots.some((H,q)=>H.path_fingerprint!==Y[q].pathFingerprint)||M.headless.lifecycle!==$.lifetime||Date.parse(M.headless.expires_at)<=Date.now())throw Error("worker_enrollment_receipt_mismatch");let G=Z2(M.first_heartbeat);try{n9($,M.device_id,{...G?{offer:G}:{},enrollmentMs:Math.min(n$,Math.max(0,Math.round(performance.now()-U)))})}catch{}return{version:4,apiOrigin:$.apiOrigin,orgId:M.organization_id,deviceId:M.device_id,devicePublicKey:V,displayName:$.name,registeredAt:new Date().toISOString(),handsSlots:$.slots,worker:{configDigest:N0($),lifetime:$.lifetime,expiresAt:M.headless.expires_at},roots:M.roots.map((H,q)=>({id:H.id,label:H.label,path:Y[q].path,pathFingerprint:H.path_fingerprint,permissions:J.root.permissions}))}}}}import{randomBytes as L7,randomUUID as F7}from"crypto";import{unlinkSync as _7}from"fs";import{join as j7}from"path";var Z4=K.strictObject({version:K.literal(1),install_id:K.uuid(),fingerprint_key:K.string().regex(/^[a-f0-9]{64}$/)}),D7=K.object({enrollment_ticket:K.string().min(1).max(4096),expires_at:K.iso.datetime({offset:!0}),device_kind:K.literal("headless"),lifecycle:K.enum(["persistent","ephemeral"]),device_expires_at:K.iso.datetime({offset:!0})});function F3($){return D7.parse($)}var W7=K.object({credentialKind:K.enum(["oauth","api_key"]).optional(),apiOrigin:K.url(),clientId:K.string(),accessToken:K.string().min(1).max(32768),refreshToken:K.string().max(32768),expiresAt:K.iso.datetime({offset:!0}),scopes:K.array(K.string().max(128)).max(128),orgId:K.string().min(1).max(160)});function _$($){return X2(z1("REASON_CLI_CHANNEL",$.channel),H0())}async function j$($,J=_$($)){if(!u(J))return null;let Z=W7.parse(JSON.parse(s(J)));if(!P0(Z.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(Z.credentialKind==="api_key")return Date.parse(Z.expiresAt)>Date.now()?Z:null;let Q=S0($.proxy),X=Object.assign((V,N)=>Q(V,{...N,redirect:"error",signal:AbortSignal.timeout(30000)}),{preconnect:fetch.preconnect}),Y=await J4({path:J,fetchImpl:X});if(Y&&!P0(Y.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");return Y}async function Q4($,J,Z){if(!P0(J.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(!J.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let Q=D$($);return Q.complete(J.orgId,await Z.createHeadlessDeviceEnrollmentTicket(Q.request))}async function X4($,J,Z,Q,X){let Y=performance.now();if(!P0(J.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(!J.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let V=D$($),N=X?void 0:Z.enrollHeadlessDevice?.bind(Z);if(N){let B=await o9($,V.direct(J.orgId),Q,(U,M)=>N({approval:V.request,code_verifier:M,registration:U}).catch((G)=>{throw O7(G)}),Y);if(B)return B}return o0($,V.complete(J.orgId,await Z.createHeadlessDeviceEnrollmentTicket(V.request)),Q,X,Y)}function O7($){if(!($ instanceof m0))return $;if($.status===409)return new r0($.code==="device_revoked");if($.status===410||$.status===401&&$.code==="invalid_enrollment_ticket"||$.status===403&&$.code==="grant_exceeded"||$.status===400&&$.code==="invalid_device_enrollment")return new r0(!1);return $}var O1=($)=>j7(g($),"enrollment-install.json");function Y4($){if(u(O1($)))_7(O1($))}function D$($,{stored:J=!0}={}){v0();let Z=O1($),Q=J&&u(Z)?Z4.parse(JSON.parse(s(Z))):{version:1,install_id:F7(),fingerprint_key:L7(32).toString("hex")};if(J&&!u(Z))c(Z,Q);let X={read:!0,write:!0,execute:!0,discover_environment:!0,expose_mcp:!1},Y=Buffer.from(Q.fingerprint_key,"hex"),V=w$([$.workspaceRoot],X,Y)[0];if(V.path!==$.workspaceRoot)throw Error("worker_workspace_not_canonical_or_overlaps_state");let N=($.folders??[]).map((G)=>{let H=w$([G],X,Y)[0];if(H.path!==G)throw Error("worker_workspace_not_canonical_or_overlaps_state");return{path_fingerprint:H.pathFingerprint}}),B=$4(),U={install_id:Q.install_id,code_challenge:B.challenge,lifecycle:$.lifetime,roots:[V.pathFingerprint,...N.map((G)=>G.path_fingerprint)].map((G)=>({path_fingerprint:G,permissions:X,execution_mode:$.executionMode}))},M=(G)=>({version:1,organization_id:G,code_verifier:B.verifier,root_fingerprint_key:Q.fingerprint_key,root:{path_fingerprint:V.pathFingerprint,permissions:X,execution_mode:$.executionMode},...N.length?{folders:N}:{}});return{request:U,saveInstall(G){e(g(G),!0),c(O1(G),Q)},complete(G,H){let q=F3(H);if(q.lifecycle!==$.lifetime||Date.parse(q.expires_at)<=Date.now()||Date.parse(q.device_expires_at)<=Date.now())throw Error("worker_ticket_receipt_mismatch");return{...M(G),enrollment_ticket:q.enrollment_ticket}},direct:M}}function V4($,J,Z){let Q=O1($);if(!u(Q))throw Error("worker_folders_unavailable");let X=Z4.parse(JSON.parse(s(Q)));return w$([J],Z,Buffer.from(X.fingerprint_key,"hex"))[0]}var Y2=8,N4=600000,U4=15000,G4=new Set(["device_revoked","invalid_device_credential"]),V2=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,N$=($)=>q0(g($),"workspaces"),H4="account.json",_3=($)=>u(q0($,H4));function y0($){let J;try{J=z7(N$($))}catch{return[]}return J.filter((Z)=>V2.test(Z)).sort().map((Z)=>{let Q=q0(N$($),Z),X=q0(Q,"worker.json"),Y=null;try{let V=J0.safeParse(JSON.parse(s(X)));if(V.success&&V.data.stateDirectory===Q)Y=V.data}catch{}return{organizationId:Z,directory:Q,configPath:X,config:Y,account:_3(Q)}})}function G2($,J){let Z=J.toLowerCase();if(!V2.test(Z))throw Error("worker_workspace_id_invalid");let Q=J0.parse({...$,stateDirectory:q0(N$($),Z)});return e(Q.stateDirectory,!0),c(q0(Q.stateDirectory,H4),{version:1}),{config:Q,configPath:q0(Q.stateDirectory,"worker.json")}}function B2($,J){try{let{config:Z,configPath:Q}=G2($,J);e(g(Z),!0),R0(Z,{version:1,drained:!0,revoked:!0}),c(Q,Z)}catch{}}function A1($,J){let Z=J.toLowerCase(),Q=null;try{Q=o($)?.orgId.toLowerCase()??null}catch{}return Q===Z||y0($).some((X)=>!X.account&&X.config!==null&&X.organizationId===Z)}var j3=["device.json","local-device.key","local-device.binding","keychain-scope.json","control.json","enrollment-install.json","first-heartbeat.json"];function B4($,J){let Z=o($);if(!Z?.worker)throw Error("worker_identity_missing");D1($,Z.devicePublicKey),e(g(J),!0);for(let Y of j3)y$(q0(g(J),Y),{force:!0});for(let Y of j3){let V=q0(g($),Y);if(u(V))A7(V,q0(g(J),Y))}let Q=T0(J),X=b$(d(J).state,{proofStore:Q,repair:!1});if(!X?.worker)throw Error("worker_identity_missing");k0({...X,worker:{...X.worker,configDigest:N0(J)}},d(J).state,{proofStore:Q})}function D3($){for(let J of y0($)){if(J.account)continue;try{if(J.config&&u(d(J.config).state))w0(J.config)}catch{}y$(J.directory,{recursive:!0,force:!0})}y$(O3($),{force:!0})}function K2($,{prefer:J,keep:Z,live:Q=!1}){let X=Date.now(),Y=(G)=>Number(Date.parse(G.worker?.expiresAt??"")>X+60000),N=y0($).flatMap((G)=>{if(!G.account||!G.config)return[];try{if($0(G.config).revoked)return[];let H=o(G.config);return H&&H.orgId.toLowerCase()===G.organizationId&&(!Q||Y(H))?[{...G,config:G.config,state:H}]:[]}catch{return[]}}).sort((G,H)=>Number(H.organizationId===J)-Number(G.organizationId===J)||Y(H.state)-Y(G.state))[0];if(!N)return null;let B=null;try{B=$0($).revoked?null:o($)}catch{}let U=B?.orgId.toLowerCase()??"";if(Z&&B&&V2.test(U)&&U!==N.organizationId){let G=G2($,U);B4($,G.config),c(G.configPath,G.config)}else if(u(g($))){try{if(u(d($).state))w0($)}catch{}for(let G of j3)y$(q0(g($),G),{force:!0})}D3($);let M=J0.parse({...N.config,stateDirectory:$.stateDirectory});return B4(N.config,M),c(q0($.stateDirectory,"worker.json"),M),y$(N.directory,{recursive:!0,force:!0}),M}var W3={before($){for(let{config:J}of y0($))try{let Z=J?o(J):null;if(J&&Z)D1(J,Z.devicePublicKey)}catch{}},after($,J){for(let{organizationId:Z,directory:Q,configPath:X,config:Y}of y0(J)){if(Y)continue;try{let V=J0.parse(JSON.parse(s(X)));if(V.stateDirectory!==q0(N$($),Z))continue;let N=J0.parse({...V,stateDirectory:Q}),B=T0(N),U=b$(d(N).state,{proofStore:B,repair:!1});if(U?.worker?.configDigest===N0(V))k0({...U,worker:{...U.worker,configDigest:N0(N)}},d(N).state,{proofStore:B});c(X,N)}catch{}}}},O3=($)=>q0(N$($),"listed.json");function q4($){try{let J=JSON.parse(s(O3($))),Z=J.names&&typeof J.names==="object"&&!Array.isArray(J.names)?Object.fromEntries(Object.entries(J.names).filter((Q)=>typeof Q[1]==="string")):{};return{listed:J.listed===!0,reason:J.reason==="sign_in"?"sign_in":null,blocked:Array.isArray(J.blocked)?J.blocked.filter((Q)=>typeof Q==="string"):[],names:Z}}catch{return null}}function M4($,J){let Z=y0($),Q=Z.filter((B)=>B.account),X=Z.filter((B)=>!B.account),Y=q4($),V=Y&&!Y.listed?Y.reason:null,N=V||X.length===0&&Y&&!Y.listed?[]:X;if(Q.length===0&&N.length===0&&(V||Y&&!Y.listed))return{workspaces:null,off:V};return{off:V,workspaces:[...Q,...N].map(({organizationId:B,config:U,account:M})=>{let G=!1,H=null,q=!1,T=null;try{G=U?$0(U).revoked:!1,H=U&&!G?o(U):null;let L=U?t$(d(U).daemon):null;q=J&&!!H&&L?.state==="connected",T=q?K4(L,H):null}catch{}return{...T?{permission_recovery:T}:{},organization_id:B,device_id:H?.deviceId??null,name:Y?.names?.[B]??null,root:H?.roots[0]?{id:H.roots[0].id,permissions:H.roots[0].permissions}:null,state:G?"removed":q?"connected":"not_running",blocked:!M&&!G&&!q&&(Y?.blocked.includes(B)??!1),...M?{account:!0}:{}}})}}function T4($){let{config:J,state:Z,client:Q,signal:X}=$,Y=$.log??(()=>{return}),V=new Map,N=null,B=!1,U=q4(J)??{listed:!1,reason:null,blocked:[]},M=(_)=>{let{folders:D,...R}=J,E=Z.roots.slice(1).map((P)=>P.path);return J0.parse({...R,...E.length?{folders:E}:{},stateDirectory:q0(N$(J),_)})},G=async(_)=>{let D=V.get(_);if(!D)return;D.controller.abort(),await D.done},H=(_,D=!1)=>{let R=new AbortController,E=()=>R.abort();if(X.addEventListener("abort",E,{once:!0}),X.aborted)R.abort();let P={..._,controller:R,claims:0,done:Promise.resolve(),account:D};P.done=$.serve(_,R.signal,(I)=>{P.claims=I}).then(()=>{return},(I)=>{if(D&&I instanceof L0&&I.status===401&&G4.has(I.code)){try{R0(_.config,{version:1,drained:!0,revoked:!0})}catch{}Y(`Reason worker: workspace ${_.organizationId} (another account's) no longer accepts this computer (${I.code}); run \`reason connect\` signed in as that account to connect it again
5
5
  `)}else if(I instanceof L0&&I.status===401&&G4.has(I.code)){try{w0(_.config)}catch{}Y(`Reason worker: workspace ${_.organizationId} no longer accepts this computer
@@ -309,7 +309,7 @@ Usage:
309
309
  `),host:Z.host}),N=_4({...V,log:(q)=>Q.stderr.write(`${q}
310
310
  `)}),{configPath:B}=N,U=N.saved;if(!U)return Q.stderr.write("Reason: this computer has no saved connection. Run `reason connect`.\n"),0;let M=(q,T)=>{let L=Z3(Z.home,Z.channel),j;try{let O=null;try{O=T.keep?null:o(U)?.orgId.toLowerCase()??null}catch{}if(j=K2(U,{prefer:t1(Z.home,Z.channel,U),...T}),j&&O)B2(j,O)}finally{L()}if(!j)return!1;U=j;let W="";try{W=` (workspace ${o(j)?.orgId??"unknown"})`}catch{}return Q.stderr.write(`Reason: ${q}; this computer goes on running Sessions for its other Reason account${W}.
311
311
  `),!0};if($0(U).revoked&&!M("this computer's connection was removed from Reason",{keep:!1}))return Q.stderr.write("Reason: this computer was removed from Reason. Run `reason connect` to connect it again.\n"),0;if(U.executionMode==="confined"||!q1(U)){let q=d0(U.stateDirectory)??void 0,T=q?null:t1(Z.home,Z.channel,U);if(!q&&!(T&&A1(U,T)))M("this computer's connection expired and its account is not signed in here",{keep:!0,live:!0})}let G=U.executionMode==="confined";if(G||!q1(U)){let q=d0(U.stateDirectory)??void 0;if(Q.stderr.write(G?u6:`Reason: this computer's connection expired; renewing it with ${q?"its API key":"your login"}\u2026
312
- `),await y9(J0.parse({...U,executionMode:"host"}),B,Q,X,q)!==0)return Q.stderr.write(q?"Reason: could not renew this computer's connection. Run `reason connect --api-key KEY` with a valid key.\n":"Reason: could not renew this computer's connection. Run `reason login`, then `reason connect`.\n"),0}let H=new AbortController;if(!X.runWorker)import("./ask-relay-fkb3bj30.js").then(({runBackgroundAskRelay:q})=>q(H.signal,(T)=>Q.stderr.write(`${T}
312
+ `),await y9(J0.parse({...U,executionMode:"host"}),B,Q,X,q)!==0)return Q.stderr.write(q?"Reason: could not renew this computer's connection. Run `reason connect --api-key KEY` with a valid key.\n":"Reason: could not renew this computer's connection. Run `reason login`, then `reason connect`.\n"),0}let H=new AbortController;if(!X.runWorker)import("./ask-relay-tkvyxa1h.js").then(({runBackgroundAskRelay:q})=>q(H.signal,(T)=>Q.stderr.write(`${T}
313
313
  `))).catch(()=>{});try{for(;;){let q=d0(U.stateDirectory)===null?{ownerWorkspaces:X.worker?.ownerWorkspaces??{}}:{},T=X.runWorker?null:l2({stateDirectory:U.stateDirectory}),L=!1,j;try{j=await(X.runWorker??q$)(["start","--config",B],{deferOptionalLanes:!0,...X.worker,...q,ownComputer:!0,io:{stdout:Q.stdout,stderr:Q.stderr},onDeviceRevoked:()=>{L=!0}})}finally{T?.stop()}if(!L)return j;if(!M("this computer's connection was removed from Reason",{keep:!1}))break}return e2(Z.home,Z.channel,!0),Q.stderr.write("Reason: this computer was removed from Reason. Run `reason connect` to connect it again.\n"),0}finally{H.abort()}}async function VG($,J,Z){let{io:Q,options:X,home:Y,channel:V,environment:N}=Z;if(J&&await(X.controlWorker??K0)(J,"status").catch(()=>null))throw new l("This computer is already connected in the background (see `reason status`). Run `reason disconnect` first to connect it only while a command runs.");let B=g0(Y,V,!0),U=p6({parsed:$,saved:J,stateDirectory:B,lifetime:"ephemeral",home:Y,channel:V,options:X,environment:N}),M=l6(U,Z.apiKey??(J?d0(J.stateDirectory)??void 0:void 0)),G=F0(B,"worker.json");return e(B,!0),c(G,M),Q.stdout.write(x9(`Reason: connecting "${M.name}" while this command runs`,M,Z.host.platform,["Connecting\u2026"])),(X.runWorker??q$)(["start","--config",G],{...k9(X.worker,Z.apiKey),ownComputer:!0,io:{stdout:Q.stdout,stderr:n2(Q.stderr)},onStartup:(H)=>{if(H==="ready")Q.stdout.write(`Connected. Start Sessions on "${M.name}" from Reason. Press Ctrl-C to stop.
314
314
  `);X.worker?.onStartup?.(H)}})}function GG($,J,Z,Q){if(Z.platform!=="darwin")throw new l("--keep-awake is for macOS.");if(!J)throw new l("This computer is not connected to Reason. Run reason connect first.");e(g(J),!0),x4(d(J).daemon,$);let X=M2(d(J).daemon)==="battery_and_ac";return Q.stdout.write(`Keep awake: ${X?"on (this Mac stays awake while it runs Sessions)":"off"}
315
315
  `),0}var BG=K.object({root:K.object({id:K.string().min(1).max(160),label:K.string().max(160),path_fingerprint:K.string()})});async function c6($,J,Z,Q){let X=await(k9(Q.worker,Z).enrollmentCredentials??j$)($,_$($));if(!X)throw Error("worker_session_login_required");if(!X.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let Y=Q.folderApi?.(X)??new A$(X,{credentialsPath:_$($),fetchImpl:S0($.proxy)}),V=(N)=>N instanceof m0&&N.status===404&&!["device_not_found","root_not_found"].includes(N.code);return{add:async(N)=>{let B=V4($,N,{...J.roots[0].permissions,expose_mcp:!1}),U=await Y.addDeviceRoot(J.deviceId,{path_fingerprint:B.pathFingerprint,label:B.label,permissions:{...B.permissions,expose_mcp:!1}}).catch((G)=>{if(V(G))throw Error("worker_folders_unavailable");if(G instanceof m0&&G.code==="root_limit_reached")throw new l("This computer already has the most folders Reason allows (32).");throw G}),M=BG.parse(U).root;if(M.path_fingerprint!==B.pathFingerprint)throw Error("worker_enrollment_receipt_mismatch");return{...B,id:M.id,label:M.label}},remove:async(N)=>{await Y.removeDeviceRoot(J.deviceId,N).catch((B)=>{if(V(B))throw Error("worker_folders_unavailable");if(!(B instanceof m0&&B.code==="root_not_found"))throw B})}}}function s6($,J,Z){k0({...J,roots:Z,handsSlots:$.slots,worker:{...J.worker,configDigest:N0($)}},d($).state,{proofStore:T0($)})}async function a6($,J,Z,Q){let{io:X,options:Y,host:V}=Q,N=J&&!Q.apiKey&&d0(J.stateDirectory)===null?t1(Q.home,Q.channel,J):null,B=J&&N&&P$(J)&&!A1(J,N)?y0(J).find((P)=>P.account&&P.organizationId===N)??null:void 0;if(B===null)throw new l("This computer is not connected for your account. Run reason connect first.");let U=B?B.config:J,M=B?B.configPath:Z,G=U&&P$(U)&&!$0(U).revoked?o(U):null;if(!J||!U||!G||U.lifetime!=="persistent")throw new l("This computer is not connected to Reason. Run reason connect first.");let H=$.addFolder!==void 0,q=H?$.addFolder:$.removeFolder,T=Y.cwd??process.cwd(),L;try{L=i2(T,q)}catch(P){if(H)throw new l(P instanceof Error?P.message:String(P));L=oV(T,q)}if(L===U.workspaceRoot)throw new l(`${L} is this computer's main folder. To use another one, run reason connect --folder PATH.`);let j=U.folders??[],W=G.roots.slice(1).find((P)=>P.path===L);if(!H&&!W&&!j.includes(L))throw new l(`${L} is not one of this computer's folders.`);if(H&&!j1(L,U.stateDirectory))throw new l(`${L} holds Reason's own settings.`);if(H&&!W&&j.length>=31)throw new l("This computer already has the most folders Reason allows (32).");let O=Q.apiKey??d0(U.stateDirectory)??void 0,F=await c6(U,G,O,Y),z=G.roots.filter((P)=>P.path!==L);if(H)z=[...z,await F.add(L)];else if(W)await F.remove(W.id);s6(U,G,z);let _=H?[...j.filter((P)=>P!==L),L]:j.filter((P)=>P!==L),{folders:D,...R}=U;if(c(M,J0.parse({...R,..._.length?{folders:_}:{}})),!await(Y.controlWorker??K0)(J,"reload_roots").then(()=>!0,()=>!1))M$(J,V,"connect");return X.stdout.write(H?`Added ${L}. Sessions on "${U.name}" may run in it.
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Wj as l}from"./vm-hands-entry-lite-ygx9kj92.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{Xj as l}from"./vm-hands-entry-lite-kxtjkzzh.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 uj,kj as vj,h as wj,Yj as xj,Y as yj,Lj as zj,Aj,s as Bj,xj as Cj,Mj as Dj,fj as Ej,hj as Fj,$j as Gj,y as Hj,Sj as Ij,_j as Jj,Hj as Kj,Tj as Lj,a as Mj,Vj as Nj};
112
+ export{Cj as vj,kj as wj,h as xj,Yj as yj,Y as zj,Lj as Aj,Aj as Bj,s as Cj,xj as Dj,Mj as Ej,fj as Fj,hj as Gj,$j as Hj,y as Ij,Sj as Jj,_j as Kj,Hj as Lj,Tj as Mj,a as Nj,Vj as Oj};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Yh as A,Zh as w,_h as c,hi as x}from"./vm-hands-entry-lite-5kgvss4p.js";import{ni as l}from"./vm-hands-entry-lite-r6pap1kh.js";import{randomUUID as y}from"crypto";import{chmodSync as o,existsSync as u,mkdirSync as jJ,readlinkSync as YJ,readFileSync as GJ,renameSync as OJ,unlinkSync as VJ,writeFileSync as FJ}from"fs";import{homedir as m}from"os";import{basename as P,dirname as H,isAbsolute as d,join as I,normalize as p,relative as HJ,resolve as LJ}from"path";import{unlinkSync as WJ}from"fs";import{dirname as XJ,join as ZJ}from"path";function $J(J){return ZJ(XJ(J),"future-device-grant.json")}function s(J){try{WJ($J(J))}catch(Q){if(!(Q instanceof Error&&("code"in Q)&&Q.code==="ENOENT"))throw Q}}var N=3,NJ=1,TJ=2,K=1,n=1,a="Reason may read and write files and run commands in this signed-in OS account, subject to saved restrictions and operating system permissions.",b="Reason may later execute on this computer inside a Reason sandbox, limited to folders explicitly attached by the user.",zJ=[b,"Ara may later execute on this computer inside an Ara sandbox, limited to folders explicitly attached by the user."];function r(J){return typeof J==="string"&&zJ.includes(J)}var BJ=["future_device","updates_only","cli_only"];function v(J){return typeof J==="string"&&BJ.some((Q)=>Q===J)}function SJ(J=process.env,Q=m()){return J.XDG_CONFIG_HOME?.trim()||I(Q,".config")}function D(J=process.env,Q=m()){let U=w({env:J}),W=SJ(J,Q);return I(W,x(W).state==="kept"?"ara":"reason",...U==="staging"?["staging"]:[],"installation.json")}function Y(J){return typeof J==="string"&&J.trim().length>0}var _J=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function IJ(J){return typeof J==="string"&&_J.test(J)}function C(J){return Y(J)&&d(J)&&p(J)===J}function i(J){if(!J||typeof J!=="object"||Array.isArray(J))return!1;let Q=J;return C(Q.path)&&(Q.role==="launcher"&&(Q.kind==="file"||Q.kind==="symlink")||Q.role==="worker_root"&&Q.kind==="directory"||Q.role==="alias"&&Q.kind==="symlink"&&C(Q.target))}function h(J){return J.owned_paths?.every((Q)=>Q.role!=="alias"||J.installer==="shell"&&Q.path===I(J.install_dir,J.channel==="staging"?"reason-staging":"reason")&&Q.target===I(J.install_dir,J.channel==="staging"?"ara-staging":"ara")&&J.owned_paths?.some((U)=>U.role==="launcher"&&U.path===Q.target))??!1}function t(J,Q){try{return LJ(H(J),YJ(J))===Q}catch{return!1}}function vJ(J){let Q=P(J),U=Q==="ara"?"reason":Q==="ara-staging"?"reason-staging":null;if(!U)return J;let W=I(H(J),U);return t(W,J)?W:J}function M(J,Q){let U=HJ(J,Q);return U.length>0&&!U.startsWith("..")&&!d(U)}function e(J){if(J===null)return!0;if(!J||typeof J!=="object"||Array.isArray(J))return!1;let Q=J;return Q.kind==="shell_profile"&&Y(Q.location)&&Y(Q.value)&&(typeof Q.added_by_installer==="boolean"||typeof Q.added_by_ara==="boolean")&&(Q.added_by_installer===void 0||typeof Q.added_by_installer==="boolean")&&(Q.added_by_ara===void 0||typeof Q.added_by_ara==="boolean")}function q(J){return J.added_by_installer??J.added_by_ara??!1}function JJ(J,Q){if(Q===null)return J==="cli_only";if(!Q||typeof Q!=="object"||Array.isArray(Q))return!1;let U=Q;if(U.version!==K||!Y(U.recorded_at))return!1;if(J==="future_device")return U.decision==="authorized"&&r(U.scope);return U.scope===null&&U.decision===(J==="updates_only"?"ask":"disabled")}function AJ(J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let Q=J;if(Q.schema_version!==NJ||!A.includes(Q.channel)||Q.install_method!=="curl"||Q.installer!=="shell"||!Y(Q.installed_at)||!Y(Q.version)||!Y(Q.target)||!C(Q.install_dir)||!Array.isArray(Q.owned_paths)||!Q.owned_paths.every(i)||!Q.owned_paths.every((U)=>M(Q.install_dir,U.path))||!h(Q)||!e(Q.path_entry))return null;return{...Q,schema_version:N,installation_id:null,background_mode:"cli_only",device_consent:null}}function KJ(J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let Q=J;if(Q.schema_version!==TJ||!QJ(Q)||!v(Q.background_mode)||!JJ(Q.background_mode,Q.device_consent))return null;return{...Q,schema_version:N,installation_id:null}}function QJ(J){return A.includes(J.channel)&&(J.install_method==="curl"&&J.installer==="shell"||J.install_method==="desktop"&&J.installer==="desktop"&&Array.isArray(J.owned_paths)&&J.owned_paths.length===0&&J.path_entry===null)&&Y(J.installed_at)&&Y(J.version)&&Y(J.target)&&C(J.install_dir)&&Array.isArray(J.owned_paths)&&J.owned_paths.every(i)&&J.owned_paths.every((Q)=>M(J.install_dir,Q.path))&&h(J)&&e(J.path_entry)}function DJ(J){let Q=AJ(J);if(Q)return Q;let U=KJ(J);if(U)return U;if(!J||typeof J!=="object"||Array.isArray(J))return null;let W=J;if(W.schema_version!==N||!IJ(W.installation_id)||!QJ(W)||!v(W.background_mode)||!JJ(W.background_mode,W.device_consent)||W.desktop_account_access!==void 0&&(W.desktop_account_access===null||typeof W.desktop_account_access!=="object"||Array.isArray(W.desktop_account_access)||W.desktop_account_access.version!==n||W.desktop_account_access.scope!==a||!Y(W.desktop_account_access.recorded_at)||!Number.isFinite(Date.parse(W.desktop_account_access.recorded_at))))return null;return W}function E(J=D()){if(!u(J))return null;try{return DJ(JSON.parse(GJ(J,"utf8")))}catch{return null}}function f(J){return Boolean(J?.installation_id&&J.background_mode==="future_device"&&J.device_consent?.version===K&&J.device_consent.decision==="authorized"&&r(J.device_consent.scope))}function g(J,Q){let U=E(Q);if(!(f(U)&&f(J)&&U.installation_id===J.installation_id&&U.channel===J.channel))s(Q);jJ(H(Q),{recursive:!0,mode:448}),o(H(Q),448);let X=`${Q}.${process.pid}.${y()}.tmp`;try{FJ(X,`${JSON.stringify(J,null,2)}
2
+ import{$h as c,Zh as A,_h as w,ii as x}from"./vm-hands-entry-lite-p1nb6n3r.js";import{oi as l}from"./vm-hands-entry-lite-4xfs7y6w.js";import{randomUUID as y}from"crypto";import{chmodSync as o,existsSync as u,mkdirSync as jJ,readlinkSync as YJ,readFileSync as GJ,renameSync as OJ,unlinkSync as VJ,writeFileSync as FJ}from"fs";import{homedir as m}from"os";import{basename as P,dirname as H,isAbsolute as d,join as I,normalize as p,relative as HJ,resolve as LJ}from"path";import{unlinkSync as WJ}from"fs";import{dirname as XJ,join as ZJ}from"path";function $J(J){return ZJ(XJ(J),"future-device-grant.json")}function s(J){try{WJ($J(J))}catch(Q){if(!(Q instanceof Error&&("code"in Q)&&Q.code==="ENOENT"))throw Q}}var N=3,NJ=1,TJ=2,K=1,n=1,a="Reason may read and write files and run commands in this signed-in OS account, subject to saved restrictions and operating system permissions.",b="Reason may later execute on this computer inside a Reason sandbox, limited to folders explicitly attached by the user.",zJ=[b,"Ara may later execute on this computer inside an Ara sandbox, limited to folders explicitly attached by the user."];function r(J){return typeof J==="string"&&zJ.includes(J)}var BJ=["future_device","updates_only","cli_only"];function v(J){return typeof J==="string"&&BJ.some((Q)=>Q===J)}function SJ(J=process.env,Q=m()){return J.XDG_CONFIG_HOME?.trim()||I(Q,".config")}function D(J=process.env,Q=m()){let U=w({env:J}),W=SJ(J,Q);return I(W,x(W).state==="kept"?"ara":"reason",...U==="staging"?["staging"]:[],"installation.json")}function Y(J){return typeof J==="string"&&J.trim().length>0}var _J=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function IJ(J){return typeof J==="string"&&_J.test(J)}function C(J){return Y(J)&&d(J)&&p(J)===J}function i(J){if(!J||typeof J!=="object"||Array.isArray(J))return!1;let Q=J;return C(Q.path)&&(Q.role==="launcher"&&(Q.kind==="file"||Q.kind==="symlink")||Q.role==="worker_root"&&Q.kind==="directory"||Q.role==="alias"&&Q.kind==="symlink"&&C(Q.target))}function h(J){return J.owned_paths?.every((Q)=>Q.role!=="alias"||J.installer==="shell"&&Q.path===I(J.install_dir,J.channel==="staging"?"reason-staging":"reason")&&Q.target===I(J.install_dir,J.channel==="staging"?"ara-staging":"ara")&&J.owned_paths?.some((U)=>U.role==="launcher"&&U.path===Q.target))??!1}function t(J,Q){try{return LJ(H(J),YJ(J))===Q}catch{return!1}}function vJ(J){let Q=P(J),U=Q==="ara"?"reason":Q==="ara-staging"?"reason-staging":null;if(!U)return J;let W=I(H(J),U);return t(W,J)?W:J}function M(J,Q){let U=HJ(J,Q);return U.length>0&&!U.startsWith("..")&&!d(U)}function e(J){if(J===null)return!0;if(!J||typeof J!=="object"||Array.isArray(J))return!1;let Q=J;return Q.kind==="shell_profile"&&Y(Q.location)&&Y(Q.value)&&(typeof Q.added_by_installer==="boolean"||typeof Q.added_by_ara==="boolean")&&(Q.added_by_installer===void 0||typeof Q.added_by_installer==="boolean")&&(Q.added_by_ara===void 0||typeof Q.added_by_ara==="boolean")}function q(J){return J.added_by_installer??J.added_by_ara??!1}function JJ(J,Q){if(Q===null)return J==="cli_only";if(!Q||typeof Q!=="object"||Array.isArray(Q))return!1;let U=Q;if(U.version!==K||!Y(U.recorded_at))return!1;if(J==="future_device")return U.decision==="authorized"&&r(U.scope);return U.scope===null&&U.decision===(J==="updates_only"?"ask":"disabled")}function AJ(J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let Q=J;if(Q.schema_version!==NJ||!A.includes(Q.channel)||Q.install_method!=="curl"||Q.installer!=="shell"||!Y(Q.installed_at)||!Y(Q.version)||!Y(Q.target)||!C(Q.install_dir)||!Array.isArray(Q.owned_paths)||!Q.owned_paths.every(i)||!Q.owned_paths.every((U)=>M(Q.install_dir,U.path))||!h(Q)||!e(Q.path_entry))return null;return{...Q,schema_version:N,installation_id:null,background_mode:"cli_only",device_consent:null}}function KJ(J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let Q=J;if(Q.schema_version!==TJ||!QJ(Q)||!v(Q.background_mode)||!JJ(Q.background_mode,Q.device_consent))return null;return{...Q,schema_version:N,installation_id:null}}function QJ(J){return A.includes(J.channel)&&(J.install_method==="curl"&&J.installer==="shell"||J.install_method==="desktop"&&J.installer==="desktop"&&Array.isArray(J.owned_paths)&&J.owned_paths.length===0&&J.path_entry===null)&&Y(J.installed_at)&&Y(J.version)&&Y(J.target)&&C(J.install_dir)&&Array.isArray(J.owned_paths)&&J.owned_paths.every(i)&&J.owned_paths.every((Q)=>M(J.install_dir,Q.path))&&h(J)&&e(J.path_entry)}function DJ(J){let Q=AJ(J);if(Q)return Q;let U=KJ(J);if(U)return U;if(!J||typeof J!=="object"||Array.isArray(J))return null;let W=J;if(W.schema_version!==N||!IJ(W.installation_id)||!QJ(W)||!v(W.background_mode)||!JJ(W.background_mode,W.device_consent)||W.desktop_account_access!==void 0&&(W.desktop_account_access===null||typeof W.desktop_account_access!=="object"||Array.isArray(W.desktop_account_access)||W.desktop_account_access.version!==n||W.desktop_account_access.scope!==a||!Y(W.desktop_account_access.recorded_at)||!Number.isFinite(Date.parse(W.desktop_account_access.recorded_at))))return null;return W}function E(J=D()){if(!u(J))return null;try{return DJ(JSON.parse(GJ(J,"utf8")))}catch{return null}}function f(J){return Boolean(J?.installation_id&&J.background_mode==="future_device"&&J.device_consent?.version===K&&J.device_consent.decision==="authorized"&&r(J.device_consent.scope))}function g(J,Q){let U=E(Q);if(!(f(U)&&f(J)&&U.installation_id===J.installation_id&&U.channel===J.channel))s(Q);jJ(H(Q),{recursive:!0,mode:448}),o(H(Q),448);let X=`${Q}.${process.pid}.${y()}.tmp`;try{FJ(X,`${JSON.stringify(J,null,2)}
3
3
  `,{mode:384,flag:"wx"}),o(X,384),OJ(X,Q)}finally{if(u(X))VJ(X)}let j=H(Q),$=P(j)==="staging"?H(j):j;if(P($)==="reason")x(H($));return J}function RJ(J=D(),Q=new Date){let U=E(J);if(!U?.installation_id)throw Error("Reason installation ownership is missing; reinstall the current CLI before enabling Device execution");if(f(U))return U;let W={...U,background_mode:"future_device",device_consent:{version:K,decision:"authorized",scope:b,recorded_at:Q.toISOString()}};return delete W.desktop_account_access,g(W,J)}function hJ(J,Q=D(),U=new Date){if(!A.includes(J.channel))throw Error("invalid installation channel");if(!J.version.trim())throw Error("installation version is required");if(!J.target.trim())throw Error("installation target is required");let W=S(J.installDir,"install directory"),X=E(Q);if(X?.installation_id&&!J.accountAccess)return RJ(Q,U);return g({...X??{schema_version:N,channel:J.channel,install_method:"desktop",installer:"desktop",installed_at:U.toISOString(),version:J.version.trim(),target:J.target.trim(),install_dir:W,owned_paths:[],path_entry:null},schema_version:N,installation_id:X?.installation_id??y(),background_mode:"future_device",...J.accountAccess?{desktop_account_access:{version:n,scope:a,recorded_at:U.toISOString()}}:{},device_consent:{version:K,decision:"authorized",scope:b,recorded_at:U.toISOString()}},Q)}function qJ(J,Q){return J.kind===Q.kind&&J.location===Q.location&&J.value===Q.value}function S(J,Q){let U=p(J);if(!d(U))throw Error(`${Q} must be an absolute path`);return U}function CJ(J,Q=D(),U=new Date){if(!A.includes(J.channel))throw Error("invalid installation channel");if(!J.version.trim())throw Error("installation version is required");if(!J.target.trim())throw Error("installation target is required");let W=S(J.install_dir,"install directory"),X=E(Q),j=J.backgroundMode??"preserve",$=j==="preserve"?X?.background_mode??"cli_only":j,T=X?.channel===J.channel&&f(X)&&$==="future_device",z=j==="preserve"&&!X||X?.channel===J.channel&&(j==="preserve"||T),O={path:S(J.launcherPath,"launcher path"),kind:J.launcherKind,role:"launcher"};if(!M(W,O.path))throw Error("launcher path must be inside the install directory");let V=J.workerRoot?S(J.workerRoot,"worker root"):null;if(V&&!M(W,V))throw Error("worker root must be inside the install directory");let B=[];if(J.aliasPath){let F={path:S(J.aliasPath,"alias path"),kind:"symlink",role:"alias",target:O.path};if(!h({installer:J.installer,channel:J.channel,install_dir:W,owned_paths:[O,F]})||!t(F.path,F.target))throw Error("alias must be the channel's symlink to its canonical launcher");B.push(F)}let R=[...X?.channel===J.channel&&X.install_dir===W?X.owned_paths:[],O,...B,...V?[{path:V,kind:"directory",role:"worker_root"}]:[]],k=Array.from(new Map(R.map((F)=>[F.path,F])).values()),Z=J.pathEntry??null,L=Z?X?.path_entry&&qJ(Z,X.path_entry)?{...Z,added_by_installer:q(Z)||q(X.path_entry),added_by_ara:q(Z)||q(X.path_entry)}:Z:X?.path_entry??null,UJ={schema_version:N,installation_id:X?.installation_id??y(),channel:J.channel,install_method:"curl",installer:J.installer,installed_at:U.toISOString(),version:J.version.trim(),target:J.target.trim(),install_dir:W,owned_paths:k,path_entry:L,background_mode:$,device_consent:z?X?.device_consent??null:{version:K,decision:$==="future_device"?"authorized":$==="updates_only"?"ask":"disabled",scope:$==="future_device"?b:null,recorded_at:U.toISOString()},...T&&X.desktop_account_access?{desktop_account_access:X.desktop_account_access}:{}};return g(UJ,Q)}function _(J,Q){let U=J.indexOf(Q);if(U===-1)return;let W=J[U+1];if(!W||W.startsWith("--"))throw Error(`${Q} needs a value`);return W}function G(J,Q){let U=_(J,Q);if(!U)throw Error(`${Q} is required`);return U}function gJ(J,Q={}){let U=Q.io??{stdout:process.stdout,stderr:process.stderr};try{let W=new Set(["--channel","--installer","--version","--target","--install-dir","--launcher-path","--launcher-kind","--worker-root","--path-kind","--path-location","--path-value","--background-mode"]);for(let Z=0;Z<J.length;Z+=1){let L=J[Z];if(L==="--path-added")continue;if(!W.has(L))throw Error(`unknown option: ${L}`);if(Z+=1,Z>=J.length)throw Error(`${L} needs a value`)}let X=Q.env??process.env,j=G(J,"--channel"),$=w({env:X,executablePath:Q.executablePath});if(j!==$)throw Error(`installer channel ${j} does not match running ${$} CLI`);let T=G(J,"--installer");if(T!=="shell")throw Error("--installer must be shell");let z=G(J,"--launcher-kind");if(z!=="file"&&z!=="symlink")throw Error("--launcher-kind must be file or symlink");let O=_(J,"--path-kind"),V=null;if(O){if(O!=="shell_profile")throw Error("--path-kind must be shell_profile");V={kind:O,location:G(J,"--path-location"),value:G(J,"--path-value"),added_by_installer:J.includes("--path-added"),added_by_ara:J.includes("--path-added")}}else if(J.includes("--path-location")||J.includes("--path-value")||J.includes("--path-added"))throw Error("path entry flags require --path-kind");let B={channel:$,install_method:"curl",installer:T,version:G(J,"--version"),target:G(J,"--target"),install_dir:G(J,"--install-dir"),launcherPath:G(J,"--launcher-path"),launcherKind:z,..._(J,"--worker-root")?{workerRoot:_(J,"--worker-root")}:{},pathEntry:V,backgroundMode:(()=>{let Z=_(J,"--background-mode")??"preserve";if(Z!=="preserve"&&!v(Z))throw Error("--background-mode must be future_device, updates_only, cli_only, or preserve");return Z})()},R=l(X,"REASON_INSTALL_ALIAS_PATH");if(R)B.aliasPath=R;let k=D(c(X,$),Q.home??m());return(Q.writeReceipt??CJ)(B,k,Q.now?.()??new Date),0}catch(W){return U.stderr.write(`Reason installer receipt: ${W instanceof Error?W.message:String(W)}
4
4
  `),1}}
5
- export{N as Xd,K as Yd,n as Zd,a as _d,b as $d,BJ as ae,SJ as be,D as ce,t as de,vJ as ee,q as fe,DJ as ge,E as he,f as ie,RJ as je,hJ as ke,CJ as le,gJ as me};
5
+ export{N as Yd,K as Zd,n as _d,a as $d,b as ae,BJ as be,SJ as ce,D as de,t as ee,vJ as fe,q as ge,DJ as he,E as ie,f as je,RJ as ke,hJ as le,CJ as me,gJ as ne};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Ac as R}from"./vm-hands-entry-lite-gxjxx1r2.js";import{Yc as D}from"./vm-hands-entry-lite-wej1p1ry.js";import{Wj as $}from"./vm-hands-entry-lite-ygx9kj92.js";import{spawn as i,spawnSync as n}from"child_process";import{existsSync as I,mkdtempSync as E,readFileSync as O,readdirSync as t,realpathSync as r,rmSync as y,statSync as o}from"fs";import{platform as b,tmpdir as h}from"os";import{dirname as N,join as Y}from"path";import{fileURLToPath as e,pathToFileURL as M}from"url";var jj=["bwrap","socat","rg"],qj=2000,_=20000,zj=3,S=4000,Gj=new Set([".git",".hg",".svn","node_modules"]),Hj=["runAsHostUid","sysrq-trigger"],Jj=Y(N(N(e(import.meta.url))),"packages/sandbox-runtime/src/index.ts"),l=!1;function Cj(){l=!0}async function g(){let q=l?Y(N(r(process.execPath)),"runtime","srt"):void 0;if(q&&process.platform==="linux"&&!I(Y(q,"vendor","seccomp",process.arch,"apply-seccomp")))throw Error("packaged_sandbox_runtime_vendor_missing");if(q){let H=O(Y(q,"sandbox-runtime.mjs"),"utf8");for(let W of Hj)if(!H.includes(W))throw Error(`packaged_sandbox_runtime_fork_missing:${W}`)}let G=(await import(q?M(Y(q,"sandbox-runtime.mjs")).href:M(Jj).href)).SandboxManager;if(!G||typeof G.initialize!=="function"||typeof G.wrapWithSandboxArgv!=="function")throw Error("sandbox-runtime does not expose the expected SandboxManager API.");return{SandboxManager:G}}function Qj(j={}){if((j.platformName??b())!=="linux")return!1;let z=j.fileExists??I,J=j.readFile??((G)=>O(G,"utf8"));for(let G of["/.dockerenv","/run/.containerenv"])try{if(z(G))return!0}catch{}try{return/docker|containerd|kubepods|lxc|libpod/.test(J("/proc/1/cgroup"))}catch{return!1}}function u(j){return["/bin/true","/usr/bin/true"].find((q)=>j(q))??null}function Vj(j,q){return j==="strict"?["--ro-bind","/","/","--unshare-pid","--unshare-user","--cap-drop","ALL","--proc","/proc","--",q]:["--ro-bind","/","/","--unshare-pid","--unshare-user","--bind","/proc","/proc","--",q]}function Wj(j,q){try{let z=n("bwrap",Vj(j,q),{stdio:"ignore",timeout:qj});return!z.error&&z.status===0}catch{return!1}}function Yj(j){let q=j.platformName??b();if(q!=="linux")return null;let z=j.hasExecutable??D;if(!jj.every((Q)=>z(Q)))return null;let J=j.fileExists??I,G=u(J);if(!G)return null;let H=B??(j.containerized??Qj({platformName:q})?"weak":"strict");return(j.probeNamespaces??((Q)=>Wj(Q,G)))(H)?H:null}var L=null,w=!1,k=null,T=null,f=null,B=null,U=null;function A(){throw F("sandbox_mode_conflict"),new $("sandbox_unavailable","Sandbox process policy conflicts with an existing probe or session. Restart the worker.")}function Mj(j){if(B!==null&&B!==j||w&&L!==null&&L!==j||U!==null&&U!==j)A();B=j}function F(j){k=j}function c(j){if(k)return!1;if(!w){if(L=Yj(j??{}),w=!0,L&&!j)d()}return L!==null}function Zj(){return c()?L:null}var X=null,C=0;function m(j){if(k)throw new $("sandbox_unavailable","Confined execution is unavailable in this worker process.");if(B&&j.sandboxMode&&B!==j.sandboxMode)A();let q=B??j.sandboxMode??Zj();if(!q)throw new $("sandbox_unavailable","Confined command execution is unavailable on this operating system.");if(U&&U!==q)A();return U=q,X??=(async()=>{let{SandboxManager:z}=await(j.loadSandboxRuntime??g)();return await z.initialize(Kj(q)),z})().catch((z)=>{throw X=null,F(`initialize_failed: ${String(z)}`),z instanceof $?z:new $("sandbox_unavailable","The confined execution sandbox failed to start.")}),X.then((z)=>{if(k)throw new $("sandbox_unavailable","Confined execution became unavailable during sandbox initialization.");return z})}async function $j(){let j=X;if(X=null,!j)return;try{await(await j).reset()}catch{}}async function d(j={}){if(k)return!1;if(j.loadSandboxRuntime)return P(j.loadSandboxRuntime);if(!c())return!1;return T??=P(g),T}async function P(j){try{let{SandboxManager:q}=await j(),z=q.checkDependencies().errors;if(z.length>0)return F(`dependencies_missing: ${z.join(", ")}`),!1;return!k}catch(q){return F(`load_failed: ${String(q)}`),!1}}async function _j(j={}){if(!j.loadSandboxRuntime&&!j.sandboxMode){if(!await d())return!1;return f??=x({}),f}return x(j)}async function x(j){let q;try{q=await m(j)}catch{return!1}let z=await Bj(q);if(!z)F("confined_command_failed");if(C===0)await $j();return z}async function Bj(j){let q=u(I);if(!q)return!1;let z=E(Y(h(),"reason-device-probe-"));try{let{argv:J}=await j.wrapWithSandboxArgv(s([q]),p(),{filesystem:a({root:z,allowWrite:!1,temporaryDirectory:z,protectedPaths:[]})},void 0,z),[G,...H]=J;if(!G)return!1;return await Lj(G,H,z)}catch{return!1}finally{try{j.cleanupAfterCommand()}catch{}y(z,{recursive:!0,force:!0})}}function Lj(j,q,z,J={}){return new Promise((G)=>{let H=!1,W,Q=(K)=>{if(H)return;H=!0,clearTimeout(W),G(K)},V;try{V=(J.spawnChild??i)(j,q,{cwd:z,env:{PATH:R,HOME:z,TMPDIR:z},stdio:"ignore"})}catch{Q(!1);return}V.once("error",()=>Q(!1));let Z=(K,v)=>Q(K===0&&v===null);if(V.once("exit",Z),V.once("close",Z),V.exitCode!==null||V.signalCode!==null)Z(V.exitCode,V.signalCode);if(H)return;W=setTimeout(()=>{Q(!1);try{V.kill("SIGKILL")}catch{}},Math.min(J.timeoutMs??_,_))})}function p(j=I){return["/bin/bash","/bin/sh"].find((q)=>j(q))??"/bin/sh"}function s(j){return j.map((q)=>`'${q.replaceAll("'","'\\''")}'`).join(" ")}function kj(j,q,z=(J)=>t(J,{withFileTypes:!0}).filter((G)=>G.isDirectory()||G.isFile()).map((G)=>G.name)){let J=[],G=[{path:j,depth:0}],H=0;while(G.length>0&&H<S){let W=G.pop(),Q;try{Q=z(W.path)}catch{continue}for(let V of Q){if(H+=1,H>S)break;let Z=Y(W.path,V);if(q(Z)){J.push(Z);continue}if(W.depth+1<zj&&!Gj.has(V))G.push({path:Z,depth:W.depth+1})}}return J}function a(j){let q=Y(j.root,".git"),z=[];try{if(o(q).isDirectory())z=[Y(q,"config"),Y(q,"hooks")]}catch{}return{denyRead:["/home","/root","/tmp","/tmp/.X11-unix",...j.protectedPaths],allowRead:[j.root,j.temporaryDirectory],allowWrite:[...j.allowWrite?[j.root]:[],j.temporaryDirectory],denyWrite:[...j.protectedPaths,...z]}}function Kj(j){return{network:{allowedDomains:[],deniedDomains:[]},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},...j==="weak"?{enableWeakerNestedSandbox:!0}:{}}}function Sj(j){let q=j.createTemporaryDirectory??(()=>E(Y(h(),"reason-device-"))),z=j.removeTemporaryDirectory??((J)=>y(J,{recursive:!0,force:!0}));return async(J,G,H)=>{let W=await m(j),Q=q();C+=1;try{let V;try{V=await W.wrapWithSandboxArgv(s([J,...G]),j.shell??p(),{filesystem:a({root:H.root,allowWrite:H.allowWrite,temporaryDirectory:Q,protectedPaths:kj(H.root,j.isProtectedPath)})},H.signal,H.cwd)}catch(v){throw v instanceof $?v:new $("sandbox_unavailable","The confined execution sandbox could not wrap the command.")}let[Z,...K]=V.argv;if(!Z)throw new $("sandbox_unavailable","The confined execution sandbox produced no command.");return await j.spawnCaptured(Z,K,{cwd:H.cwd,timeoutMs:H.timeoutMs,signal:H.signal,env:j.scrubEnvironment(H.root,Q)})}finally{C-=1;try{W.cleanupAfterCommand()}catch{}z(Q)}}}
2
+ import{Ac as R}from"./vm-hands-entry-lite-gxjxx1r2.js";import{Yc as D}from"./vm-hands-entry-lite-wej1p1ry.js";import{Xj as $}from"./vm-hands-entry-lite-kxtjkzzh.js";import{spawn as i,spawnSync as n}from"child_process";import{existsSync as I,mkdtempSync as E,readFileSync as O,readdirSync as t,realpathSync as r,rmSync as y,statSync as o}from"fs";import{platform as b,tmpdir as h}from"os";import{dirname as N,join as Y}from"path";import{fileURLToPath as e,pathToFileURL as M}from"url";var jj=["bwrap","socat","rg"],qj=2000,_=20000,zj=3,S=4000,Gj=new Set([".git",".hg",".svn","node_modules"]),Hj=["runAsHostUid","sysrq-trigger"],Jj=Y(N(N(e(import.meta.url))),"packages/sandbox-runtime/src/index.ts"),l=!1;function Cj(){l=!0}async function g(){let q=l?Y(N(r(process.execPath)),"runtime","srt"):void 0;if(q&&process.platform==="linux"&&!I(Y(q,"vendor","seccomp",process.arch,"apply-seccomp")))throw Error("packaged_sandbox_runtime_vendor_missing");if(q){let H=O(Y(q,"sandbox-runtime.mjs"),"utf8");for(let W of Hj)if(!H.includes(W))throw Error(`packaged_sandbox_runtime_fork_missing:${W}`)}let G=(await import(q?M(Y(q,"sandbox-runtime.mjs")).href:M(Jj).href)).SandboxManager;if(!G||typeof G.initialize!=="function"||typeof G.wrapWithSandboxArgv!=="function")throw Error("sandbox-runtime does not expose the expected SandboxManager API.");return{SandboxManager:G}}function Qj(j={}){if((j.platformName??b())!=="linux")return!1;let z=j.fileExists??I,J=j.readFile??((G)=>O(G,"utf8"));for(let G of["/.dockerenv","/run/.containerenv"])try{if(z(G))return!0}catch{}try{return/docker|containerd|kubepods|lxc|libpod/.test(J("/proc/1/cgroup"))}catch{return!1}}function u(j){return["/bin/true","/usr/bin/true"].find((q)=>j(q))??null}function Vj(j,q){return j==="strict"?["--ro-bind","/","/","--unshare-pid","--unshare-user","--cap-drop","ALL","--proc","/proc","--",q]:["--ro-bind","/","/","--unshare-pid","--unshare-user","--bind","/proc","/proc","--",q]}function Wj(j,q){try{let z=n("bwrap",Vj(j,q),{stdio:"ignore",timeout:qj});return!z.error&&z.status===0}catch{return!1}}function Yj(j){let q=j.platformName??b();if(q!=="linux")return null;let z=j.hasExecutable??D;if(!jj.every((Q)=>z(Q)))return null;let J=j.fileExists??I,G=u(J);if(!G)return null;let H=B??(j.containerized??Qj({platformName:q})?"weak":"strict");return(j.probeNamespaces??((Q)=>Wj(Q,G)))(H)?H:null}var L=null,w=!1,k=null,T=null,f=null,B=null,U=null;function A(){throw F("sandbox_mode_conflict"),new $("sandbox_unavailable","Sandbox process policy conflicts with an existing probe or session. Restart the worker.")}function Mj(j){if(B!==null&&B!==j||w&&L!==null&&L!==j||U!==null&&U!==j)A();B=j}function F(j){k=j}function c(j){if(k)return!1;if(!w){if(L=Yj(j??{}),w=!0,L&&!j)d()}return L!==null}function Zj(){return c()?L:null}var X=null,C=0;function m(j){if(k)throw new $("sandbox_unavailable","Confined execution is unavailable in this worker process.");if(B&&j.sandboxMode&&B!==j.sandboxMode)A();let q=B??j.sandboxMode??Zj();if(!q)throw new $("sandbox_unavailable","Confined command execution is unavailable on this operating system.");if(U&&U!==q)A();return U=q,X??=(async()=>{let{SandboxManager:z}=await(j.loadSandboxRuntime??g)();return await z.initialize(Kj(q)),z})().catch((z)=>{throw X=null,F(`initialize_failed: ${String(z)}`),z instanceof $?z:new $("sandbox_unavailable","The confined execution sandbox failed to start.")}),X.then((z)=>{if(k)throw new $("sandbox_unavailable","Confined execution became unavailable during sandbox initialization.");return z})}async function $j(){let j=X;if(X=null,!j)return;try{await(await j).reset()}catch{}}async function d(j={}){if(k)return!1;if(j.loadSandboxRuntime)return P(j.loadSandboxRuntime);if(!c())return!1;return T??=P(g),T}async function P(j){try{let{SandboxManager:q}=await j(),z=q.checkDependencies().errors;if(z.length>0)return F(`dependencies_missing: ${z.join(", ")}`),!1;return!k}catch(q){return F(`load_failed: ${String(q)}`),!1}}async function _j(j={}){if(!j.loadSandboxRuntime&&!j.sandboxMode){if(!await d())return!1;return f??=x({}),f}return x(j)}async function x(j){let q;try{q=await m(j)}catch{return!1}let z=await Bj(q);if(!z)F("confined_command_failed");if(C===0)await $j();return z}async function Bj(j){let q=u(I);if(!q)return!1;let z=E(Y(h(),"reason-device-probe-"));try{let{argv:J}=await j.wrapWithSandboxArgv(s([q]),p(),{filesystem:a({root:z,allowWrite:!1,temporaryDirectory:z,protectedPaths:[]})},void 0,z),[G,...H]=J;if(!G)return!1;return await Lj(G,H,z)}catch{return!1}finally{try{j.cleanupAfterCommand()}catch{}y(z,{recursive:!0,force:!0})}}function Lj(j,q,z,J={}){return new Promise((G)=>{let H=!1,W,Q=(K)=>{if(H)return;H=!0,clearTimeout(W),G(K)},V;try{V=(J.spawnChild??i)(j,q,{cwd:z,env:{PATH:R,HOME:z,TMPDIR:z},stdio:"ignore"})}catch{Q(!1);return}V.once("error",()=>Q(!1));let Z=(K,v)=>Q(K===0&&v===null);if(V.once("exit",Z),V.once("close",Z),V.exitCode!==null||V.signalCode!==null)Z(V.exitCode,V.signalCode);if(H)return;W=setTimeout(()=>{Q(!1);try{V.kill("SIGKILL")}catch{}},Math.min(J.timeoutMs??_,_))})}function p(j=I){return["/bin/bash","/bin/sh"].find((q)=>j(q))??"/bin/sh"}function s(j){return j.map((q)=>`'${q.replaceAll("'","'\\''")}'`).join(" ")}function kj(j,q,z=(J)=>t(J,{withFileTypes:!0}).filter((G)=>G.isDirectory()||G.isFile()).map((G)=>G.name)){let J=[],G=[{path:j,depth:0}],H=0;while(G.length>0&&H<S){let W=G.pop(),Q;try{Q=z(W.path)}catch{continue}for(let V of Q){if(H+=1,H>S)break;let Z=Y(W.path,V);if(q(Z)){J.push(Z);continue}if(W.depth+1<zj&&!Gj.has(V))G.push({path:Z,depth:W.depth+1})}}return J}function a(j){let q=Y(j.root,".git"),z=[];try{if(o(q).isDirectory())z=[Y(q,"config"),Y(q,"hooks")]}catch{}return{denyRead:["/home","/root","/tmp","/tmp/.X11-unix",...j.protectedPaths],allowRead:[j.root,j.temporaryDirectory],allowWrite:[...j.allowWrite?[j.root]:[],j.temporaryDirectory],denyWrite:[...j.protectedPaths,...z]}}function Kj(j){return{network:{allowedDomains:[],deniedDomains:[]},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},...j==="weak"?{enableWeakerNestedSandbox:!0}:{}}}function Sj(j){let q=j.createTemporaryDirectory??(()=>E(Y(h(),"reason-device-"))),z=j.removeTemporaryDirectory??((J)=>y(J,{recursive:!0,force:!0}));return async(J,G,H)=>{let W=await m(j),Q=q();C+=1;try{let V;try{V=await W.wrapWithSandboxArgv(s([J,...G]),j.shell??p(),{filesystem:a({root:H.root,allowWrite:H.allowWrite,temporaryDirectory:Q,protectedPaths:kj(H.root,j.isProtectedPath)})},H.signal,H.cwd)}catch(v){throw v instanceof $?v:new $("sandbox_unavailable","The confined execution sandbox could not wrap the command.")}let[Z,...K]=V.argv;if(!Z)throw new $("sandbox_unavailable","The confined execution sandbox produced no command.");return await j.spawnCaptured(Z,K,{cwd:H.cwd,timeoutMs:H.timeoutMs,signal:H.signal,env:j.scrubEnvironment(H.root,Q)})}finally{C-=1;try{W.cleanupAfterCommand()}catch{}z(Q)}}}
3
3
  export{Cj as uc,Mj as vc,c as wc,_j as xc,p as yc,Sj as zc};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var U=".reason/workspace",T="workspace_base",y="sessions",W="workspace_layout",g=".reason/workspace/sessions",B=/^[0-9a-f]{8}$/;function C(j){if(!J(j))return!1;let q=".reason/workspace/sessions/";if(!j.startsWith(q))return!1;let z=j.slice(q.length).split("/");return z.length===2&&B.test(z[0])}var G=4096,X="workspaces/pi";function J(j){if(typeof j!=="string"||!j||j.length>G)return!1;if(j.startsWith("/")||j.includes("\x00")||j.includes("\\"))return!1;return j.split("/").every((q)=>q!==""&&q!=="."&&q!=="..")}function Z(j){if(j.kind==="root"){if(j.path===void 0)return".";if(!J(j.path))throw Error("invalid_device_workspace_identity");return j.path}if(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/.test(j.workspaceId)||j.workspaceId==="."||j.workspaceId==="..")throw Error("invalid_device_workspace_identity");let q=j.layout==="sessions"?"sessions":X;return`${j.base?`${j.base}/`:""}${q}/${j.workspaceId}/repo`}function L(j){if(!j||typeof j!=="object"||Array.isArray(j))return null;let q=j;if(q.kind==="root"&&Object.keys(q).length===1)return{kind:"root"};if(q.kind==="root"&&Object.keys(q).length===2&&J(q.path))return{kind:"root",path:q.path};if(q.kind!=="managed"||typeof q.workspaceId!=="string"||Object.keys(q).length!==2+(q.base===void 0?0:1)+(q.layout===void 0?0:1)||q.base!==void 0&&q.base!==".reason/workspace"||q.layout!==void 0&&q.layout!=="sessions")return null;let z={kind:"managed",workspaceId:q.workspaceId,...q.base===".reason/workspace"?{base:".reason/workspace"}:{},...q.layout==="sessions"?{layout:"sessions"}:{}};try{return Z(z),z}catch{return null}}var b="/home/runner",P=10001,x="/run/reason/sessions",f=/^(?:\/[A-Za-z0-9._-]+)+$/,M=/-sidechat-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/,H=/^(.+)-repository-[a-z0-9][a-z0-9._-]*-[0-9a-f]{12}$/;function K(j){return M.exec(j)?.[1]??H.exec(j)?.[1]??j}var $=/^((?:\/[A-Za-z0-9._-]+)+)\/\.reason\/workspace\/(workspaces\/pi|sessions)\/([^/]+)$/,A="*/.reason/workspace/workspaces/pi/*|*/.reason/workspace/sessions/*";function N(j,q=b,z="sessions"){if(!f.test(q)||q.split("/").some((V)=>V==="."||V===".."))throw Error("invalid_cloud_payload_home");let Q=`${q}/${Z({kind:"managed",workspaceId:j,base:".reason/workspace",...z?{layout:z}:{}})}`,F=`${x}/${K(j)}`;return{home:q,root:Q.slice(0,-5),checkout:Q,control:F,jobEnv:`${F}/job.env`,cloudAccess:`${F}/cloud-access`,logs:`${F}/logs`,pin:`${F}/ws`}}function Y(j){return $.exec(j.replace(/\/+$/,""))?.[2]==="sessions"?"sessions":null}function D(j){return{kind:"managed",workspaceId:j,layout:"sessions"}}function R(j){let q=$.exec(j.replace(/\/+$/,""));if(!q)return null;try{let z=N(q[3],q[1],Y(j));return z.root===j.replace(/\/+$/,"")?z:null}catch{return null}}
3
- export{U as Wi,T as Xi,y as Yi,W as Zi,g as _i,B as $i,C as aj,J as bj,Z as cj,L as dj,b as ej,P as fj,x as gj,M as hj,H as ij,$ as jj,A as kj,N as lj,Y as mj,D as nj,R as oj};
3
+ export{U as Xi,T as Yi,y as Zi,W as _i,g as $i,B as aj,C as bj,J as cj,Z as dj,L as ej,b as fj,P as gj,x as hj,M as ij,H as jj,$ as kj,A as lj,N as mj,Y as nj,D as oj,R as pj};