@reason-machines/cli-linux-arm64-musl 0.2.364 → 0.2.366

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 +1 -1
  2. package/bin/vm-hands/api-13266c99.js +2 -0
  3. package/bin/vm-hands/api-credentials-q6vq26w0.js +2 -0
  4. package/bin/vm-hands/{ask-relay-7yw62yzw.js → ask-relay-ar561trh.js} +3 -3
  5. package/bin/vm-hands/connect-cli-gjf47h7z.js +2 -0
  6. package/bin/vm-hands/custom-endpoint-device-m1kn3rkk.js +2 -0
  7. package/bin/vm-hands/desktop-account-vfbchnax.js +2 -0
  8. package/bin/vm-hands/{device-workspace-c05vq771.js → device-workspace-nvcschtn.js} +1 -1
  9. package/bin/vm-hands/{hands-worker-source-wfv9csj2.js → hands-worker-source-k9k2vj4y.js} +1 -1
  10. package/bin/vm-hands/{index-80ep9259.js → index-ae8w22py.js} +1 -1
  11. package/bin/vm-hands/{install-receipt-pbfhgaxc.js → install-receipt-4cnygt5g.js} +1 -1
  12. package/bin/vm-hands/local-automation-0j57c21p.js +2 -0
  13. package/bin/vm-hands/local-capabilities-6pqbn5wm.js +2 -0
  14. package/bin/vm-hands/local-desktop-users-nwyzyc05.js +2 -0
  15. package/bin/vm-hands/local-display-mac-ewqyyxk5.js +2 -0
  16. package/bin/vm-hands/local-display-session-a3rr41av.js +2 -0
  17. package/bin/vm-hands/local-pty-session-8k64gfn8.js +2 -0
  18. package/bin/vm-hands/{managed-runtime-vkw66kvt.js → managed-runtime-3fkrr7cf.js} +1 -1
  19. package/bin/vm-hands/{network-contract-zjq3w2n3.js → network-contract-wep9fv9j.js} +1 -1
  20. package/bin/vm-hands/package-pfdm6awy.js +2 -0
  21. package/bin/vm-hands/permissions-d87nq1as.js +2 -0
  22. package/bin/vm-hands/{reason-hands-protocol-aj1zwpk0.js → reason-hands-protocol-78nr9pzf.js} +1 -1
  23. package/bin/vm-hands/serve-service-tzdt63z3.js +2 -0
  24. package/bin/vm-hands/{status-edb6wpzh.js → status-9420cxy5.js} +2 -2
  25. package/bin/vm-hands/version-ss8wa2cx.js +2 -0
  26. package/bin/vm-hands/{vm-hands-entry-lite-1hv536wk.js → vm-hands-entry-lite-01sqtryp.js} +1 -1
  27. package/bin/vm-hands/{vm-hands-entry-lite-62x9nv6n.js → vm-hands-entry-lite-1k23f7ja.js} +3 -3
  28. package/bin/vm-hands/{vm-hands-entry-lite-4xfs7y6w.js → vm-hands-entry-lite-1mrkcz0p.js} +1 -1
  29. package/bin/vm-hands/{vm-hands-entry-lite-dqnhebfx.js → vm-hands-entry-lite-2fpxf6vm.js} +1 -1
  30. package/bin/vm-hands/{vm-hands-entry-lite-jjkkee8q.js → vm-hands-entry-lite-630eqwb4.js} +2 -2
  31. package/bin/vm-hands/{vm-hands-entry-lite-cety9pka.js → vm-hands-entry-lite-7jhh57qs.js} +2 -2
  32. package/bin/vm-hands/{vm-hands-entry-lite-jpkf3569.js → vm-hands-entry-lite-7wgbj1kg.js} +2 -2
  33. package/bin/vm-hands/{vm-hands-entry-lite-qy9xzp2m.js → vm-hands-entry-lite-8a1zycjh.js} +2 -2
  34. package/bin/vm-hands/{vm-hands-entry-lite-t50b2jyp.js → vm-hands-entry-lite-8crh75hs.js} +2 -2
  35. package/bin/vm-hands/{vm-hands-entry-lite-hfq6jjnh.js → vm-hands-entry-lite-arhbwrn1.js} +1 -1
  36. package/bin/vm-hands/{vm-hands-entry-lite-7nk0873d.js → vm-hands-entry-lite-ay6sk3xm.js} +1 -1
  37. package/bin/vm-hands/{vm-hands-entry-lite-cwf21py1.js → vm-hands-entry-lite-bhgsayph.js} +1 -1
  38. package/bin/vm-hands/{vm-hands-entry-lite-vcm4389c.js → vm-hands-entry-lite-cas0c9qd.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-pkjkgy7n.js → vm-hands-entry-lite-cvc79v3m.js} +1 -1
  40. package/bin/vm-hands/{vm-hands-entry-lite-fr2k6eah.js → vm-hands-entry-lite-cvft83sx.js} +2 -2
  41. package/bin/vm-hands/{vm-hands-entry-lite-tf1tkqkw.js → vm-hands-entry-lite-d0f4kbc8.js} +2 -2
  42. package/bin/vm-hands/{vm-hands-entry-lite-e95w4ea8.js → vm-hands-entry-lite-es39m2mg.js} +2 -2
  43. package/bin/vm-hands/{vm-hands-entry-lite-avstvbbc.js → vm-hands-entry-lite-g63y988w.js} +2 -2
  44. package/bin/vm-hands/{vm-hands-entry-lite-0p3438xe.js → vm-hands-entry-lite-gs8cpdfw.js} +2 -2
  45. package/bin/vm-hands/{vm-hands-entry-lite-xhr0m9r0.js → vm-hands-entry-lite-h6qss80e.js} +1 -1
  46. package/bin/vm-hands/{vm-hands-entry-lite-k7fkfytm.js → vm-hands-entry-lite-hzsk6tpw.js} +2 -2
  47. package/bin/vm-hands/{vm-hands-entry-lite-p1nb6n3r.js → vm-hands-entry-lite-jd49j573.js} +2 -2
  48. package/bin/vm-hands/{vm-hands-entry-lite-vfn61qq2.js → vm-hands-entry-lite-m2h8vdr0.js} +2 -2
  49. package/bin/vm-hands/{vm-hands-entry-lite-tbps80f1.js → vm-hands-entry-lite-m57kpdgb.js} +2 -2
  50. package/bin/vm-hands/{vm-hands-entry-lite-kxtjkzzh.js → vm-hands-entry-lite-p24kmysw.js} +1 -1
  51. package/bin/vm-hands/{vm-hands-entry-lite-xj0p1ax7.js → vm-hands-entry-lite-p7hxm3hc.js} +2 -2
  52. package/bin/vm-hands/{vm-hands-entry-lite-hw8vgsmm.js → vm-hands-entry-lite-pby299bv.js} +1 -1
  53. package/bin/vm-hands/{vm-hands-entry-lite-25rpwc1k.js → vm-hands-entry-lite-pcavxb2v.js} +2 -2
  54. package/bin/vm-hands/{vm-hands-entry-lite-0763vz5v.js → vm-hands-entry-lite-pd4gdky1.js} +1 -1
  55. package/bin/vm-hands/{vm-hands-entry-lite-5y2kfnv2.js → vm-hands-entry-lite-pk2xd13q.js} +2 -2
  56. package/bin/vm-hands/{vm-hands-entry-lite-6fvjbwqq.js → vm-hands-entry-lite-qxnzwjrp.js} +1 -1
  57. package/bin/vm-hands/{vm-hands-entry-lite-vb4nyef6.js → vm-hands-entry-lite-rax2e8y2.js} +1 -1
  58. package/bin/vm-hands/{vm-hands-entry-lite-v65nk88n.js → vm-hands-entry-lite-saqwe5sm.js} +2 -2
  59. package/bin/vm-hands/{vm-hands-entry-lite-zn303jrg.js → vm-hands-entry-lite-vebspwdp.js} +1 -1
  60. package/bin/vm-hands/{vm-hands-entry-lite-t5kt2wff.js → vm-hands-entry-lite-wdsk86sk.js} +2 -2
  61. package/bin/vm-hands/{vm-hands-entry-lite-w3cfhkv2.js → vm-hands-entry-lite-y9mpztzd.js} +2 -2
  62. package/bin/vm-hands/{vm-hands-entry-lite-w3xhwb5h.js → vm-hands-entry-lite-zam0fx58.js} +1 -1
  63. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  64. package/bin/vm-hands/{vm-hands-executor-8s1c63v3.js → vm-hands-executor-3h6qvnbd.js} +1 -1
  65. package/bin/vm-hands/vm-hands-op-runner-awbk4j07.js +2 -0
  66. package/bin/vm-hands/{vm-hands-runtime-1342fjjh.js → vm-hands-runtime-n31ghckd.js} +3 -3
  67. package/bin/vm-hands/worker-sandbox-72e3y7bk.js +2 -0
  68. package/package.json +1 -1
  69. package/bin/vm-hands/api-credentials-vtpssnm1.js +0 -2
  70. package/bin/vm-hands/api-dvwzjwmh.js +0 -2
  71. package/bin/vm-hands/connect-cli-9v34nh0s.js +0 -2
  72. package/bin/vm-hands/custom-endpoint-device-8v87dhjx.js +0 -2
  73. package/bin/vm-hands/desktop-account-q57958y1.js +0 -2
  74. package/bin/vm-hands/local-automation-cbajffkk.js +0 -2
  75. package/bin/vm-hands/local-capabilities-q6g78bqk.js +0 -2
  76. package/bin/vm-hands/local-desktop-users-m7rexsex.js +0 -2
  77. package/bin/vm-hands/local-display-mac-9de01n3r.js +0 -2
  78. package/bin/vm-hands/local-display-session-1np79m1h.js +0 -2
  79. package/bin/vm-hands/local-pty-session-e7j0kj19.js +0 -2
  80. package/bin/vm-hands/package-44a3p8yk.js +0 -2
  81. package/bin/vm-hands/permissions-0apqx19h.js +0 -2
  82. package/bin/vm-hands/serve-service-g3410yvm.js +0 -2
  83. package/bin/vm-hands/version-q2x36es9.js +0 -2
  84. package/bin/vm-hands/vm-hands-op-runner-k2jpqmzw.js +0 -2
  85. package/bin/vm-hands/worker-sandbox-wb5thd4n.js +0 -2
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Pj as w}from"./vm-hands-entry-lite-k7fkfytm.js";var E="inference.custom.v1",K=32768,P=67108864,Q=16384,S=204800,R=600000,T=["content-type","anthropic-version","user-agent"],L=w.enum(["openai-completions","openai-responses","anthropic-messages"]),U=new Set(T),V=w.record(w.string(),w.string().max(2048)).refine((j)=>Object.keys(j).every((A)=>U.has(A))&&Object.values(j).every((A)=>!/[\r\n\0]/.test(A)),"Only non-secret custom endpoint request headers are permitted");function F(j){try{let A=new URL(j);return["http:","https:"].includes(A.protocol)&&!A.username&&!A.password&&!A.search&&!A.hash?A:null}catch{return null}}function W(j,A){let B=F(j.baseUrl),H=F(A.baseUrl),D=F(j.url);if(!B||!H||!D||j.method!=="POST"||A.execution!=="device")return!1;let I=(J)=>J.origin+J.pathname.replace(/\/+$/,"");if(I(B)!==I(H)||D.origin!==B.origin)return!1;let O=A.api==="openai-completions"?"/chat/completions":A.api==="openai-responses"?"/responses":"/v1/messages";return D.pathname===B.pathname.replace(/\/+$/,"")+O}var z=w.object({baseUrl:w.string().max(2048),url:w.string().max(4096),method:w.literal("POST"),body:w.string().refine((j)=>new TextEncoder().encode(j).byteLength<=S).optional(),headers:V,credentialOrganizationId:w.string().uuid(),accountKey:w.string().min(1).max(256).optional()}).strict().refine((j)=>L.options.some((A)=>W(j,{baseUrl:j.baseUrl,api:A,execution:"device"})),"Invalid custom endpoint inference URL"),b=w.object({status:w.number().int().min(200).max(599),statusText:w.string().max(256).refine((j)=>!/[\r\n\0]/.test(j)),headers:w.record(w.string(),w.string().max(4096)).refine((j)=>Object.keys(j).every((A)=>["content-type","retry-after","x-request-id","request-id"].includes(A))&&Object.values(j).every((A)=>!/[\r\n\0]/.test(A)))}).strict(),k=w.union([w.object({eof:w.literal(!0)}).strict(),w.object({eof:w.literal(!1),data:w.string().max(Math.ceil(K/3)*4).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/).refine((j)=>j.length>0&&j.length*3/4-(j.endsWith("==")?2:j.endsWith("=")?1:0)<=K)}).strict()]),y=w.object({bytes:w.number().int().min(0).max(P),chunks:w.number().int().min(0).max(Q)}).strict(),M=w.object({apiKey:w.string().min(1).max(16384).refine((j)=>!/[\r\n\0]/.test(j)),api:L}).strict(),X=["custom_endpoint_host_not_found","custom_endpoint_connection_failed","custom_endpoint_tls_failed"];function p(j){return typeof j==="string"&&X.includes(j)}var Y="Ollama listens only on 127.0.0.1 unless it is started with OLLAMA_HOST=0.0.0.0.",G={custom_endpoint_host_not_found:"Your computer couldn't resolve your model server's hostname. Check the hostname in the Base URL, and that this computer is on the network or tailnet that resolves it.",custom_endpoint_connection_failed:`Your computer's connection to your model server was refused or timed out. Check that the server is running and listening on the Base URL's address and port. ${Y}`,custom_endpoint_tls_failed:"Your computer couldn't make a secure (TLS) connection to your model server. Check the server's https certificate, or use an http:// Base URL for a server on your computer or private network.",401:"Your model server refused the request (HTTP 401). Check the API key saved for it in Models.",403:"Your model server refused the request (HTTP 403). Ollama refuses requests addressed to a hostname other than localhost, such as a *.ts.net name from tailscale serve or funnel: restart it with OLLAMA_HOST=0.0.0.0, or use http://localhost:11434/v1 when it runs on the session's computer. For another server, check the API key and its access rules.",404:"Your model server answered HTTP 404 (not found). Check that the Base URL is the API root (for Ollama, http://localhost:11434/v1) and that each model ID is one the server lists."},Z=new Set(Object.values(G));function q(j){return Object.hasOwn(G,j)?G[j]:null}function c(j){return typeof j==="string"&&Z.has(j)}var N="returned HTTP 403: its firewall blocked Reason cloud",_=/^Your model endpoint \S+ (?:returned HTTP 40[34]|returned HTTP 403: its firewall blocked Reason cloud|was unreachable: it refused the connection)\.$/,$=/Attention Required! \| Cloudflare|Sorry, you have been blocked|cf-error-details/i;function h(j,A,B){if(!/^[a-z0-9.-]+$/i.test(j))return null;if(A==="connection_refused")return`Your model endpoint ${j} was unreachable: it refused the connection.`;if(A===403&&B&&$.test(B))return`Your model endpoint ${j} ${N}.`;return A===403||A===404?`Your model endpoint ${j} returned HTTP ${A}.`:null}function x(j){return typeof j==="string"&&_.test(j)}function v(j){return x(j)&&j.includes(N)}
3
- export{E as $c,K as ad,P as bd,Q as cd,S as dd,R as ed,T as fd,W as gd,z as hd,b as id,k as jd,y as kd,M as ld,X as md,p as nd,q as od,c as pd,h as qd,x as rd,v as sd};
2
+ import{Qj as w}from"./vm-hands-entry-lite-hzsk6tpw.js";var R="inference.custom.v1",K=32768,P=67108864,Q=16384,S=204800,z=600000,T=["content-type","anthropic-version","user-agent"],L=w.enum(["openai-completions","openai-responses","anthropic-messages"]),U=new Set(T),V=w.record(w.string(),w.string().max(2048)).refine((j)=>Object.keys(j).every((A)=>U.has(A))&&Object.values(j).every((A)=>!/[\r\n\0]/.test(A)),"Only non-secret custom endpoint request headers are permitted");function F(j){try{let A=new URL(j);return["http:","https:"].includes(A.protocol)&&!A.username&&!A.password&&!A.search&&!A.hash?A:null}catch{return null}}function W(j,A){let B=F(j.baseUrl),H=F(A.baseUrl),D=F(j.url);if(!B||!H||!D||j.method!=="POST"||A.execution!=="device")return!1;let I=(J)=>J.origin+J.pathname.replace(/\/+$/,"");if(I(B)!==I(H)||D.origin!==B.origin)return!1;let O=A.api==="openai-completions"?"/chat/completions":A.api==="openai-responses"?"/responses":"/v1/messages";return D.pathname===B.pathname.replace(/\/+$/,"")+O}var b=w.object({baseUrl:w.string().max(2048),url:w.string().max(4096),method:w.literal("POST"),body:w.string().refine((j)=>new TextEncoder().encode(j).byteLength<=S).optional(),headers:V,credentialOrganizationId:w.string().uuid(),accountKey:w.string().min(1).max(256).optional()}).strict().refine((j)=>L.options.some((A)=>W(j,{baseUrl:j.baseUrl,api:A,execution:"device"})),"Invalid custom endpoint inference URL"),k=w.object({status:w.number().int().min(200).max(599),statusText:w.string().max(256).refine((j)=>!/[\r\n\0]/.test(j)),headers:w.record(w.string(),w.string().max(4096)).refine((j)=>Object.keys(j).every((A)=>["content-type","retry-after","x-request-id","request-id"].includes(A))&&Object.values(j).every((A)=>!/[\r\n\0]/.test(A)))}).strict(),y=w.union([w.object({eof:w.literal(!0)}).strict(),w.object({eof:w.literal(!1),data:w.string().max(Math.ceil(K/3)*4).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/).refine((j)=>j.length>0&&j.length*3/4-(j.endsWith("==")?2:j.endsWith("=")?1:0)<=K)}).strict()]),M=w.object({bytes:w.number().int().min(0).max(P),chunks:w.number().int().min(0).max(Q)}).strict(),p=w.object({apiKey:w.string().min(1).max(16384).refine((j)=>!/[\r\n\0]/.test(j)),api:L}).strict(),X=["custom_endpoint_host_not_found","custom_endpoint_connection_failed","custom_endpoint_tls_failed"];function q(j){return typeof j==="string"&&X.includes(j)}var Y="Ollama listens only on 127.0.0.1 unless it is started with OLLAMA_HOST=0.0.0.0.",G={custom_endpoint_host_not_found:"Your computer couldn't resolve your model server's hostname. Check the hostname in the Base URL, and that this computer is on the network or tailnet that resolves it.",custom_endpoint_connection_failed:`Your computer's connection to your model server was refused or timed out. Check that the server is running and listening on the Base URL's address and port. ${Y}`,custom_endpoint_tls_failed:"Your computer couldn't make a secure (TLS) connection to your model server. Check the server's https certificate, or use an http:// Base URL for a server on your computer or private network.",401:"Your model server refused the request (HTTP 401). Check the API key saved for it in Models.",403:"Your model server refused the request (HTTP 403). Ollama refuses requests addressed to a hostname other than localhost, such as a *.ts.net name from tailscale serve or funnel: restart it with OLLAMA_HOST=0.0.0.0, or use http://localhost:11434/v1 when it runs on the session's computer. For another server, check the API key and its access rules.",404:"Your model server answered HTTP 404 (not found). Check that the Base URL is the API root (for Ollama, http://localhost:11434/v1) and that each model ID is one the server lists."},Z="Local custom endpoints require a session on your connected computer. Select your Mac or CLI device, or use a public HTTPS endpoint for cloud sessions.",_=new Set([...Object.values(G),Z]);function c(j){return Object.hasOwn(G,j)?G[j]:null}function h(j){return typeof j==="string"&&_.has(j)}var N="returned HTTP 403: its firewall blocked Reason cloud",$=/^Your model endpoint \S+ (?:returned HTTP 40[34]|returned HTTP 403: its firewall blocked Reason cloud|was unreachable: it refused the connection)\.$/,x=/Attention Required! \| Cloudflare|Sorry, you have been blocked|cf-error-details/i;function v(j,A,B){if(!/^[a-z0-9.-]+$/i.test(j))return null;if(A==="connection_refused")return`Your model endpoint ${j} was unreachable: it refused the connection.`;if(A===403&&B&&x.test(B))return`Your model endpoint ${j} ${N}.`;return A===403||A===404?`Your model endpoint ${j} returned HTTP ${A}.`:null}function C(j){return typeof j==="string"&&$.test(j)}function d(j){return C(j)&&j.includes(N)}
3
+ export{R as $c,K as ad,P as bd,Q as cd,S as dd,z as ed,T as fd,W as gd,b as hd,k as id,y as jd,M as kd,p as ld,X as md,q as nd,Z as od,c as pd,h as qd,v as rd,C as sd,d as td};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{zg as m}from"./vm-hands-entry-lite-xj0p1ax7.js";import{Ng as w}from"./vm-hands-entry-lite-vcm4389c.js";import{Ti as h}from"./vm-hands-entry-lite-tbps80f1.js";import{ej as x}from"./vm-hands-entry-lite-dqnhebfx.js";import{Xj as Q}from"./vm-hands-entry-lite-kxtjkzzh.js";import{existsSync as B,realpathSync as k,statSync as s}from"fs";import{platform as p}from"os";import{isAbsolute as y,sep as d}from"path";var r=43200000,A=w,l=4,u=/^[A-Za-z0-9._:-]{1,160}$/,a=1000;function v(z){return Boolean(z)&&typeof z==="object"&&!Array.isArray(z)}function q(z,H){if(typeof z!=="number"||!Number.isFinite(z)||z<=0)return H;return Math.min(a,Math.max(1,Math.floor(z)))}function n(z,H=Date.now()){let V=["relay_url","session_id","expires_at"],J=new Set([...V,"cols","rows","cwd","workspace"]);if(!v(z)||V.some((L)=>!(L in z))||Object.keys(z).some((L)=>!J.has(L)))throw new Q("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:j,session_id:Y,expires_at:C}=z;if(typeof j!=="string")throw new Q("invalid_pty_request","Reason terminal relay URL is missing.");let D;try{D=new URL(j)}catch{throw new Q("invalid_pty_request","Reason terminal relay URL is invalid.")}if(D.protocol!=="wss:"&&D.protocol!=="ws:"||D.username||D.password)throw new Q("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof Y!=="string"||!u.test(Y))throw new Q("invalid_pty_request","Reason terminal session identity is invalid.");let R=typeof C==="string"?Date.parse(C):Number.NaN;if(!Number.isFinite(R)||R<=H)throw new Q("invalid_pty_request","Reason terminal session has already expired.");if(z.cwd!==void 0&&typeof z.cwd!=="string")throw new Q("invalid_pty_request","Reason terminal working directory is invalid.");let Z=z.workspace===void 0?void 0:x(z.workspace);if(Z===null||Z&&z.cwd!==void 0)throw new Q("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:j,session_id:Y,expires_at:new Date(Math.min(R,H+r)).toISOString(),cols:q(z.cols,80),rows:q(z.rows,24),...z.cwd===void 0?{}:{cwd:z.cwd},...Z?{workspace:Z}:{}}}function o(z,H){return H===z||H.startsWith(z+d)}function U(z,H){if(H===void 0)return z;if(!y(H))throw new Q("pty_cwd_invalid","Reason terminal working directory must be absolute.");let V;try{V=k(H)}catch{throw new Q("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!o(z,V))throw new Q("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!s(V).isDirectory())throw new Q("pty_cwd_invalid","Reason terminal working directory is not a directory.");return V}function t(z=process.env){let H=z.SHELL;if(H&&y(H)&&B(H))return H;for(let V of p()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(B(V))return V;return"/bin/sh"}function e(){let z=globalThis.Bun;if(!z)throw new Q("pty_unavailable","Reason terminals require the Bun runtime.");return z.spawn}function Dz(){return typeof globalThis.Bun<"u"}var zz=(z)=>{let H=e()({cmd:[z.shell,"-i","-l"],cwd:z.cwd,env:{...z.environment,TERM:"xterm-256color"},terminal:{cols:z.cols,rows:z.rows,data:(J,j)=>{z.onData(j)}}}),V=H.terminal;if(!V){try{H.kill()}catch{}throw new Q("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(J)=>V.write(J),resize:(J,j)=>V.resize(J,j),kill:()=>{try{H.kill()}catch{}},exited:H.exited.then((J)=>typeof J==="number"?J:null,()=>null)}},Hz=(z,H)=>{return H===void 0?new WebSocket(z):new WebSocket(z,{proxy:H})},S=new Set;function Jz(z){if(S.size>=l||S.has(z))return null;S.add(z);let H=!1;return()=>{if(H)return;H=!0,S.delete(z)}}async function Kz(z,H={}){let V=H.now??Date.now,J=n(z.payload,V()),j=Jz(z.operationId);if(!j)throw new Q("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let Y=V(),C,D,R;try{let Z=J.workspace?h(z.root,J.workspace):void 0;C=Z?U(B(Z.boundary)?k(Z.boundary):Z.boundary,Z.path):U(z.root,J.cwd),D=H.environment??process.env,R=H.shellPath??t(D)}catch(Z){throw j(),Z}return await new Promise((Z,L)=>{let X=null,W=null,M=!1,f=!1,K=!1,T=null,_=0,b=0,O=[],P=0,g=null,$=(N)=>{if(K)return;if(K=!0,g)clearTimeout(g);z.signal.removeEventListener("abort",I);try{X?.kill()}catch{}try{W?.close(1000,"pty_session_over")}catch{}if(j(),N.kind==="rejected"){L(N.error);return}let G={reason:N.reason,exit_code:T,output_bytes:_,input_bytes:b,duration_ms:Math.max(0,V()-Y)};z.emitEvent("pty.stopped",{...G}).catch(()=>{return}),Z({...G})},I=()=>{let N=z.signal.reason;$({kind:"rejected",error:N instanceof Q?N:new Q("cancelled","Reason closed the terminal session.")})};if(z.signal.aborted){I();return}z.signal.addEventListener("abort",I,{once:!0}),g=setTimeout(()=>$({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(J.expires_at)-V()));let i=(N)=>{if(_+=N.byteLength,!M||!W){if(O.push(N),P+=N.byteLength,P>A)$({kind:"resolved",reason:"output_backpressure"});return}try{W.send(N)}catch{$({kind:"resolved",reason:"relay_closed"});return}if(W.bufferedAmount>A)$({kind:"resolved",reason:"output_backpressure"})};try{X=(H.spawnPty??zz)({shell:R,args:["-i","-l"],cwd:C,cols:J.cols,rows:J.rows,environment:D,onData:(N)=>{if(!K)i(N)}})}catch(N){$({kind:"rejected",error:N instanceof Q?N:new Q("pty_spawn_failed","Reason could not start the terminal shell.")});return}X.exited.then((N)=>{if(K)return;if(T=N,M&&W)try{W.send(JSON.stringify({t:"exit",code:N}))}catch{}$({kind:"resolved",reason:"shell_exited"})});let c=(H.loadProxy??m)()?.url;try{W=(H.connect??Hz)(J.relay_url,c)}catch{$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}W.binaryType="arraybuffer",W.onopen=()=>{if(K||!W)return;M=!0;try{W.send(JSON.stringify({t:"open",cols:J.cols,rows:J.rows}));for(let N of O.splice(0))W.send(N);P=0}catch{$({kind:"resolved",reason:"relay_closed"});return}f=!0,z.emitEvent("pty.ready",{session_id:J.session_id,cols:J.cols,rows:J.rows}).catch(()=>{return})},W.onmessage=(N)=>{if(K||!X)return;let G=N.data;if(typeof G==="string"){let F;try{F=JSON.parse(G)}catch{return}if(!v(F))return;if(F.t==="resize"){try{X.resize(q(F.cols,J.cols),q(F.rows,J.rows))}catch{}return}if(F.t==="close")$({kind:"resolved",reason:"client_closed"});return}let E=G instanceof ArrayBuffer?new Uint8Array(G):ArrayBuffer.isView(G)?new Uint8Array(G.buffer,G.byteOffset,G.byteLength):null;if(!E||E.byteLength===0)return;b+=E.byteLength;try{X.write(E)}catch{}},W.onclose=()=>{if(K)return;if(!f){$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}$({kind:"resolved",reason:"relay_closed"})},W.onerror=()=>{if(K||f)return;$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
3
- export{r as ag,A as bg,l as cg,n as dg,U as eg,t as fg,Dz as gg,zz as hg,Hz as ig,Kz as jg};
2
+ import{Ag as m}from"./vm-hands-entry-lite-p7hxm3hc.js";import{Og as w}from"./vm-hands-entry-lite-cas0c9qd.js";import{Ui as h}from"./vm-hands-entry-lite-m57kpdgb.js";import{fj as x}from"./vm-hands-entry-lite-2fpxf6vm.js";import{Yj as Q}from"./vm-hands-entry-lite-p24kmysw.js";import{existsSync as B,realpathSync as k,statSync as s}from"fs";import{platform as p}from"os";import{isAbsolute as y,sep as d}from"path";var r=43200000,A=w,l=4,u=/^[A-Za-z0-9._:-]{1,160}$/,a=1000;function v(z){return Boolean(z)&&typeof z==="object"&&!Array.isArray(z)}function q(z,H){if(typeof z!=="number"||!Number.isFinite(z)||z<=0)return H;return Math.min(a,Math.max(1,Math.floor(z)))}function n(z,H=Date.now()){let V=["relay_url","session_id","expires_at"],J=new Set([...V,"cols","rows","cwd","workspace"]);if(!v(z)||V.some((L)=>!(L in z))||Object.keys(z).some((L)=>!J.has(L)))throw new Q("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:j,session_id:Y,expires_at:C}=z;if(typeof j!=="string")throw new Q("invalid_pty_request","Reason terminal relay URL is missing.");let D;try{D=new URL(j)}catch{throw new Q("invalid_pty_request","Reason terminal relay URL is invalid.")}if(D.protocol!=="wss:"&&D.protocol!=="ws:"||D.username||D.password)throw new Q("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof Y!=="string"||!u.test(Y))throw new Q("invalid_pty_request","Reason terminal session identity is invalid.");let R=typeof C==="string"?Date.parse(C):Number.NaN;if(!Number.isFinite(R)||R<=H)throw new Q("invalid_pty_request","Reason terminal session has already expired.");if(z.cwd!==void 0&&typeof z.cwd!=="string")throw new Q("invalid_pty_request","Reason terminal working directory is invalid.");let Z=z.workspace===void 0?void 0:x(z.workspace);if(Z===null||Z&&z.cwd!==void 0)throw new Q("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:j,session_id:Y,expires_at:new Date(Math.min(R,H+r)).toISOString(),cols:q(z.cols,80),rows:q(z.rows,24),...z.cwd===void 0?{}:{cwd:z.cwd},...Z?{workspace:Z}:{}}}function o(z,H){return H===z||H.startsWith(z+d)}function U(z,H){if(H===void 0)return z;if(!y(H))throw new Q("pty_cwd_invalid","Reason terminal working directory must be absolute.");let V;try{V=k(H)}catch{throw new Q("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!o(z,V))throw new Q("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!s(V).isDirectory())throw new Q("pty_cwd_invalid","Reason terminal working directory is not a directory.");return V}function t(z=process.env){let H=z.SHELL;if(H&&y(H)&&B(H))return H;for(let V of p()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(B(V))return V;return"/bin/sh"}function e(){let z=globalThis.Bun;if(!z)throw new Q("pty_unavailable","Reason terminals require the Bun runtime.");return z.spawn}function Dz(){return typeof globalThis.Bun<"u"}var zz=(z)=>{let H=e()({cmd:[z.shell,"-i","-l"],cwd:z.cwd,env:{...z.environment,TERM:"xterm-256color"},terminal:{cols:z.cols,rows:z.rows,data:(J,j)=>{z.onData(j)}}}),V=H.terminal;if(!V){try{H.kill()}catch{}throw new Q("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(J)=>V.write(J),resize:(J,j)=>V.resize(J,j),kill:()=>{try{H.kill()}catch{}},exited:H.exited.then((J)=>typeof J==="number"?J:null,()=>null)}},Hz=(z,H)=>{return H===void 0?new WebSocket(z):new WebSocket(z,{proxy:H})},S=new Set;function Jz(z){if(S.size>=l||S.has(z))return null;S.add(z);let H=!1;return()=>{if(H)return;H=!0,S.delete(z)}}async function Kz(z,H={}){let V=H.now??Date.now,J=n(z.payload,V()),j=Jz(z.operationId);if(!j)throw new Q("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let Y=V(),C,D,R;try{let Z=J.workspace?h(z.root,J.workspace):void 0;C=Z?U(B(Z.boundary)?k(Z.boundary):Z.boundary,Z.path):U(z.root,J.cwd),D=H.environment??process.env,R=H.shellPath??t(D)}catch(Z){throw j(),Z}return await new Promise((Z,L)=>{let X=null,W=null,M=!1,f=!1,K=!1,T=null,_=0,b=0,O=[],P=0,g=null,$=(N)=>{if(K)return;if(K=!0,g)clearTimeout(g);z.signal.removeEventListener("abort",I);try{X?.kill()}catch{}try{W?.close(1000,"pty_session_over")}catch{}if(j(),N.kind==="rejected"){L(N.error);return}let G={reason:N.reason,exit_code:T,output_bytes:_,input_bytes:b,duration_ms:Math.max(0,V()-Y)};z.emitEvent("pty.stopped",{...G}).catch(()=>{return}),Z({...G})},I=()=>{let N=z.signal.reason;$({kind:"rejected",error:N instanceof Q?N:new Q("cancelled","Reason closed the terminal session.")})};if(z.signal.aborted){I();return}z.signal.addEventListener("abort",I,{once:!0}),g=setTimeout(()=>$({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(J.expires_at)-V()));let i=(N)=>{if(_+=N.byteLength,!M||!W){if(O.push(N),P+=N.byteLength,P>A)$({kind:"resolved",reason:"output_backpressure"});return}try{W.send(N)}catch{$({kind:"resolved",reason:"relay_closed"});return}if(W.bufferedAmount>A)$({kind:"resolved",reason:"output_backpressure"})};try{X=(H.spawnPty??zz)({shell:R,args:["-i","-l"],cwd:C,cols:J.cols,rows:J.rows,environment:D,onData:(N)=>{if(!K)i(N)}})}catch(N){$({kind:"rejected",error:N instanceof Q?N:new Q("pty_spawn_failed","Reason could not start the terminal shell.")});return}X.exited.then((N)=>{if(K)return;if(T=N,M&&W)try{W.send(JSON.stringify({t:"exit",code:N}))}catch{}$({kind:"resolved",reason:"shell_exited"})});let c=(H.loadProxy??m)()?.url;try{W=(H.connect??Hz)(J.relay_url,c)}catch{$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}W.binaryType="arraybuffer",W.onopen=()=>{if(K||!W)return;M=!0;try{W.send(JSON.stringify({t:"open",cols:J.cols,rows:J.rows}));for(let N of O.splice(0))W.send(N);P=0}catch{$({kind:"resolved",reason:"relay_closed"});return}f=!0,z.emitEvent("pty.ready",{session_id:J.session_id,cols:J.cols,rows:J.rows}).catch(()=>{return})},W.onmessage=(N)=>{if(K||!X)return;let G=N.data;if(typeof G==="string"){let F;try{F=JSON.parse(G)}catch{return}if(!v(F))return;if(F.t==="resize"){try{X.resize(q(F.cols,J.cols),q(F.rows,J.rows))}catch{}return}if(F.t==="close")$({kind:"resolved",reason:"client_closed"});return}let E=G instanceof ArrayBuffer?new Uint8Array(G):ArrayBuffer.isView(G)?new Uint8Array(G.buffer,G.byteOffset,G.byteLength):null;if(!E||E.byteLength===0)return;b+=E.byteLength;try{X.write(E)}catch{}},W.onclose=()=>{if(K)return;if(!f){$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}$({kind:"resolved",reason:"relay_closed"})},W.onerror=()=>{if(K||f)return;$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
3
+ export{r as bg,A as cg,l as dg,n as eg,U as fg,t as gg,Dz as hg,zz as ig,Hz as jg,Kz as kg};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{uj as $}from"./vm-hands-entry-lite-w3cfhkv2.js";var O=$.version,Z=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function S(B,D){if(!Z.test(B)||!Z.test(D))throw Error("cannot compare invalid CLI versions");let J=(q)=>{let y=q.indexOf("-");return y===-1?[q,void 0]:[q.slice(0,y),q.slice(y+1)]},[j,F]=J(B),[w,G]=J(D),K=j.split(".").map(BigInt),M=w.split(".").map(BigInt);for(let q=0;q<3;q+=1){if(K[q]===M[q])continue;return K[q]<M[q]?-1:1}if(F===void 0||G===void 0){if(F===G)return 0;return F===void 0?1:-1}let Q=F.split("."),U=G.split("."),A=Math.max(Q.length,U.length);for(let q=0;q<A;q+=1){let y=Q[q],z=U[q];if(y===void 0||z===void 0){if(y===z)return 0;return y===void 0?-1:1}if(y===z)continue;let H=/^\d+$/.test(y),W=/^\d+$/.test(z);if(H&&W){let X=BigInt(y),Y=BigInt(z);if(X===Y)continue;return X<Y?-1:1}if(H!==W)return H?-1:1;return y<z?-1:1}return 0}function k(B,D){return D?`cli ${B} \xB7 agent ${D}`:`cli ${B}`}
3
- export{O as qj,Z as rj,S as sj,k as tj};
2
+ import{vj as $}from"./vm-hands-entry-lite-y9mpztzd.js";var O=$.version,Z=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function S(B,D){if(!Z.test(B)||!Z.test(D))throw Error("cannot compare invalid CLI versions");let J=(q)=>{let y=q.indexOf("-");return y===-1?[q,void 0]:[q.slice(0,y),q.slice(y+1)]},[j,F]=J(B),[w,G]=J(D),K=j.split(".").map(BigInt),M=w.split(".").map(BigInt);for(let q=0;q<3;q+=1){if(K[q]===M[q])continue;return K[q]<M[q]?-1:1}if(F===void 0||G===void 0){if(F===G)return 0;return F===void 0?1:-1}let Q=F.split("."),U=G.split("."),A=Math.max(Q.length,U.length);for(let q=0;q<A;q+=1){let y=Q[q],z=U[q];if(y===void 0||z===void 0){if(y===z)return 0;return y===void 0?-1:1}if(y===z)continue;let H=/^\d+$/.test(y),W=/^\d+$/.test(z);if(H&&W){let X=BigInt(y),Y=BigInt(z);if(X===Y)continue;return X<Y?-1:1}if(H!==W)return H?-1:1;return y<z?-1:1}return 0}function k(B,D){return D?`cli ${B} \xB7 agent ${D}`:`cli ${B}`}
3
+ export{O as rj,Z as sj,S as tj,k as uj};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{D as T,F as U}from"./vm-hands-entry-lite-zn303jrg.js";import{Xc as V}from"./vm-hands-entry-lite-wry37am5.js";import{_h as M,ai as Q}from"./vm-hands-entry-lite-p1nb6n3r.js";import{oi as G}from"./vm-hands-entry-lite-4xfs7y6w.js";function W(j,B){let k=G(j,"REASON_API_URL")?.trim();if(!k)return Q(B);let z=new URL(k);if(z.protocol!=="https:"&&!(z.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(z.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return z.origin}function X(j){return G(j,"REASON_API_URL")?.trim()?W(j,"production"):void 0}function $(j){return G(j,"REASON_API_KEY")?.trim()||void 0}async function N(j,B){let k=j.env??process.env,z=$(k);if(!z)return(j.getCredentials??T)({apiOrigin:X(k),signal:B});let J=W(k,j.channel??M({env:k})),D=await(j.fetchImpl??fetch)(J+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+z,accept:"application/json"},signal:B}),L=await D.json().catch(()=>({})),w=V(L)?L:{};if(!D.ok){let H=typeof w.detail==="string"?w.detail:typeof w.message==="string"?w.message:"API key authentication failed ("+D.status+")";throw new U(D.status,typeof w.error==="string"?w.error:"api_key_auth_failed",H)}if(typeof w.org_id!=="string"||!w.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let Z=Array.isArray(w.scopes)?w.scopes.filter((H)=>typeof H==="string"):[];return{credentialKind:"api_key",apiOrigin:J,accessToken:z,orgId:w.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:Z}}async function P(j){let B=await N(j),k=X(j.env??process.env);if(!B)throw Error(k?`Not signed in to ${k}. Set REASON_API_KEY, or run \`reason login --api-url ${k}\`.`:"Not signed in. Run `reason login`, or set REASON_API_KEY.");return B}
2
+ import{D as T,F as U}from"./vm-hands-entry-lite-vebspwdp.js";import{Xc as V}from"./vm-hands-entry-lite-wry37am5.js";import{$h as M,bi as Q}from"./vm-hands-entry-lite-jd49j573.js";import{pi as G}from"./vm-hands-entry-lite-1mrkcz0p.js";function W(j,B){let k=G(j,"REASON_API_URL")?.trim();if(!k)return Q(B);let z=new URL(k);if(z.protocol!=="https:"&&!(z.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(z.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return z.origin}function X(j){return G(j,"REASON_API_URL")?.trim()?W(j,"production"):void 0}function $(j){return G(j,"REASON_API_KEY")?.trim()||void 0}async function N(j,B){let k=j.env??process.env,z=$(k);if(!z)return(j.getCredentials??T)({apiOrigin:X(k),signal:B});let J=W(k,j.channel??M({env:k})),D=await(j.fetchImpl??fetch)(J+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+z,accept:"application/json"},signal:B}),L=await D.json().catch(()=>({})),w=V(L)?L:{};if(!D.ok){let H=typeof w.detail==="string"?w.detail:typeof w.message==="string"?w.message:"API key authentication failed ("+D.status+")";throw new U(D.status,typeof w.error==="string"?w.error:"api_key_auth_failed",H)}if(typeof w.org_id!=="string"||!w.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let Z=Array.isArray(w.scopes)?w.scopes.filter((H)=>typeof H==="string"):[];return{credentialKind:"api_key",apiOrigin:J,accessToken:z,orgId:w.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:Z}}async function P(j){let B=await N(j),k=X(j.env??process.env);if(!B)throw Error(k?`Not signed in to ${k}. Set REASON_API_KEY, or run \`reason login --api-url ${k}\`.`:"Not signed in. Run `reason login`, or set REASON_API_KEY.");return B}
3
3
  export{W as v,X as w,$ as x,N as y,P as z};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{_j as e}from"./vm-hands-entry-lite-hw8vgsmm.js";var i=e((o,t)=>{t.exports={name:"playwright-core",version:"1.60.0",description:"A high-level API to automate web browsers",repository:{type:"git",url:"git+https://github.com/microsoft/playwright.git"},homepage:"https://playwright.dev",engines:{node:">=18"},author:{name:"Microsoft Corporation"},license:"Apache-2.0",exports:{".":{types:"./index.d.ts",import:"./index.mjs",require:"./index.js",default:"./index.js"},"./package.json":"./package.json","./lib/bootstrap":"./lib/bootstrap.js","./lib/coreBundle":"./lib/coreBundle.js","./lib/utilsBundle":"./lib/utilsBundle.js","./lib/tools/cli-client/program":"./lib/tools/cli-client/program.js"},bin:{"playwright-core":"cli.js"},types:"types/types.d.ts"}});
2
+ import{$j as e}from"./vm-hands-entry-lite-pby299bv.js";var i=e((o,t)=>{t.exports={name:"playwright-core",version:"1.60.0",description:"A high-level API to automate web browsers",repository:{type:"git",url:"git+https://github.com/microsoft/playwright.git"},homepage:"https://playwright.dev",engines:{node:">=18"},author:{name:"Microsoft Corporation"},license:"Apache-2.0",exports:{".":{types:"./index.d.ts",import:"./index.mjs",require:"./index.js",default:"./index.js"},"./package.json":"./package.json","./lib/bootstrap":"./lib/bootstrap.js","./lib/coreBundle":"./lib/coreBundle.js","./lib/utilsBundle":"./lib/utilsBundle.js","./lib/tools/cli-client/program":"./lib/tools/cli-client/program.js"},bin:{"playwright-core":"cli.js"},types:"types/types.d.ts"}});
3
3
  export{i as Aa};
@@ -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{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)}}}
2
+ import{Ac as R}from"./vm-hands-entry-lite-gxjxx1r2.js";import{Yc as D}from"./vm-hands-entry-lite-wej1p1ry.js";import{Yj as $}from"./vm-hands-entry-lite-p24kmysw.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,4 +1,4 @@
1
1
  // @bun
2
- import{ej as f}from"./vm-hands-entry-lite-dqnhebfx.js";var j=["Click browser element","Double click browser element","Type text","Clear browser field","Press key","Scroll browser element into view","Drag on computer","Select browser option","Check browser control","Uncheck browser control","Hover browser element","Focus browser element","Open browser page","Reload browser page","Go back in browser","Go forward in browser","Take browser screenshot"],$A=32;function R(x){if(!Array.isArray(x)||x.length>32||!x.every((A)=>typeof A==="string"&&j.includes(A)))return;return x.slice()}var KA="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",QA=262144;function Y(x){if(!x||typeof x!=="object"||Array.isArray(x))return!1;let A=x,W=Object.keys(A);return W.length===2&&W.includes("template")&&W.includes("quoteDepth")&&typeof A.template==="string"&&A.template.length<=262144&&!A.template.includes("\x00")&&A.template.split("__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__").length===2&&(A.quoteDepth===1||A.quoteDepth===2||A.quoteDepth===3)}var I=2,b=33554432,K=200000,D=4000000,_=240000,YA=`
2
+ import{fj as f}from"./vm-hands-entry-lite-2fpxf6vm.js";var j=["Click browser element","Double click browser element","Type text","Clear browser field","Press key","Scroll browser element into view","Drag on computer","Select browser option","Check browser control","Uncheck browser control","Hover browser element","Focus browser element","Open browser page","Reload browser page","Go back in browser","Go forward in browser","Take browser screenshot"],$A=32;function R(x){if(!Array.isArray(x)||x.length>32||!x.every((A)=>typeof A==="string"&&j.includes(A)))return;return x.slice()}var KA="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",QA=262144;function Y(x){if(!x||typeof x!=="object"||Array.isArray(x))return!1;let A=x,W=Object.keys(A);return W.length===2&&W.includes("template")&&W.includes("quoteDepth")&&typeof A.template==="string"&&A.template.length<=262144&&!A.template.includes("\x00")&&A.template.split("__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__").length===2&&(A.quoteDepth===1||A.quoteDepth===2||A.quoteDepth===3)}var I=2,b=33554432,K=200000,D=4000000,_=240000,YA=`
3
3
  ...[executor output truncated]`,p=2000,k=1,i=16384,d=32768,y=128,LA=64,s=2097152,H=1,m=16384,c=32768,OA=8388608,n=1000,t=2500,r=2000,zA=t+r,o=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/,v=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,l={text_only:4430,invalid_json:4431,invalid_cancel_request:4432,invalid_sdk_response:4433,claim_required:4434,invalid_claim:4435,executor_mismatch:4436,stale_generation:4437,fence_conflict:4438,frame_too_large:4439,result_too_large:4440,progress_too_large:4441,terminal_cleanup_started:4442,job_journal_unavailable:4443},u=new Map(Object.entries(l).map(([x,A])=>[A,x]));function SA(x,A){return A||(u.get(x)??"")}var a=["cancelled","command_failed","duplicate_request_id","duplicate_result_evicted","invalid_repl_response","invalid_request","process_group_cleanup_unconfirmed","repl_failed","result_too_large","repl_response_too_large","repl_transport_failed","request_ledger_full","request_journal_unavailable","request_outcome_uncertain","maintenance_held","request_not_found","resume_digest_mismatch","spawn_failed","stale_generation","timeout"],e=new Set(a),w=16384,AA=200,xA=2000,WA=["maintenance_held","invalid_job_request","jobs_disabled","job_not_found","job_conflict","job_capacity","job_journal_unavailable","job_not_running","job_lease_expired","job_input_sequence","job_input_backpressure","stale_generation","pty_unsupported","job_mode_mismatch"];class G extends Error{code;constructor(x){super(x);this.name="HandsProtocolError",this.code=x}}function g(x){return new TextEncoder().encode(x).byteLength}function U(x){return typeof x==="object"&&x!==null&&!Array.isArray(x)}function B(x,A){let W=new Set(A);return Object.keys(x).every((N)=>W.has(N))}function M(x){return typeof x==="string"&&o.test(x)}function Z(x){return Number.isSafeInteger(x)&&Number(x)>=1}function J(x){return typeof x==="string"&&v.test(x)}function C(x){return typeof x==="string"&&x.startsWith("pty-")&&J(x.slice(4))}function z(x){return[x.cols,x.rows].every((A)=>Number.isSafeInteger(A)&&Number(A)>=1&&Number(A)<=n)}function E(x){if(typeof x!=="string"||x.length>Math.ceil(m/3)*4||x.length%4!==0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(x))return-1;let A=x.endsWith("==")?2:x.endsWith("=")?1:0;if(A&&"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(x[x.length-A-1])&(A===2?15:3))return-1;let N=x.length/4*3-A;return N<=m?N:-1}function S(x){return typeof x==="string"&&/^[0-9a-f]{64}$/.test(x)}function $(x){if(g(x)>b)throw new G("frame_too_large");try{return JSON.parse(x)}catch{throw new G("invalid_json")}}function BA(x){let A=$(x);if(!U(A)||!B(A,["version","generation","id","tool","input","semanticDigest","lifecycleLeaseId","workspaceBefore"])||A.version!==I||!Z(A.generation)||!M(A.id)||!["bash","repl","resume","read","edit","write","pi_tool"].includes(String(A.tool))||!U(A.input)||A.lifecycleLeaseId!==void 0&&(A.tool!=="bash"||!J(A.lifecycleLeaseId))||A.workspaceBefore!==void 0&&(!(A.tool==="bash"||A.tool==="repl"||A.tool==="pi_tool"&&A.input.tool==="bash")||!U(A.workspaceBefore)||!B(A.workspaceBefore,["script"])||typeof A.workspaceBefore.script!=="string"||A.workspaceBefore.script.length>K))throw new G("invalid_request");let W=U(A.workspaceBefore)&&typeof A.workspaceBefore.script==="string"?{workspaceBefore:{script:A.workspaceBefore.script}}:{};if(A.tool==="bash"){if(!B(A.input,["script","retainBackground","machineSdk"])||typeof A.input.script!=="string"||A.input.script.length>K||A.input.retainBackground!==void 0&&A.input.retainBackground!==!0||A.input.machineSdk!==void 0&&A.input.machineSdk!==!0||A.semanticDigest!==void 0&&!S(A.semanticDigest))throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"bash",input:{script:A.input.script,...A.input.retainBackground===!0?{retainBackground:!0}:{},...A.input.machineSdk===!0?{machineSdk:!0}:{}},...A.semanticDigest===void 0?{}:{semanticDigest:A.semanticDigest},...A.lifecycleLeaseId===void 0?{}:{lifecycleLeaseId:A.lifecycleLeaseId},...W}}if(A.tool==="resume"){if(A.semanticDigest!==void 0||!B(A.input,["semanticDigest"])||!S(A.input.semanticDigest))throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"resume",input:{semanticDigest:A.input.semanticDigest}}}if(A.tool==="repl"){if(!B(A.input,["code"])||typeof A.input.code!=="string"||A.input.code.length>K||A.semanticDigest!==void 0)throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"repl",input:{code:A.input.code},...W}}if(A.tool==="pi_tool"){let N=A.semanticDigest===void 0?GA(A.input):null;if(!N)throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"pi_tool",input:N,...W}}if(A.tool==="read"){if(!B(A.input,["path","offset","limit"])||typeof A.input.path!=="string"||A.input.path.length<1||A.input.path.length>K||A.semanticDigest!==void 0||A.input.offset!==void 0&&(!Number.isSafeInteger(A.input.offset)||Number(A.input.offset)<1)||A.input.limit!==void 0&&(!Number.isSafeInteger(A.input.limit)||Number(A.input.limit)<1||Number(A.input.limit)>2000))throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"read",input:{path:A.input.path,...A.input.offset===void 0?{}:{offset:Number(A.input.offset)},...A.input.limit===void 0?{}:{limit:Number(A.input.limit)}}}}if(A.tool==="edit"){if(!B(A.input,["path","edits"])||typeof A.input.path!=="string"||A.input.path.length<1||!Array.isArray(A.input.edits)||A.input.edits.length<1||A.input.edits.length>128||A.semanticDigest!==void 0)throw new G("invalid_request");let N=A.input.path.length,X=[];for(let V of A.input.edits){if(!U(V)||!B(V,["oldText","newText"])||typeof V.oldText!=="string"||V.oldText.length<1||typeof V.newText!=="string")throw new G("invalid_request");if(N+=V.oldText.length+V.newText.length,N>D)throw new G("invalid_request");X.push({oldText:V.oldText,newText:V.newText})}return{version:I,generation:A.generation,id:A.id,tool:"edit",input:{path:A.input.path,edits:X}}}if(A.tool!=="write"||!B(A.input,["path","content"])||typeof A.input.path!=="string"||A.input.path.length<1||typeof A.input.content!=="string"||A.input.path.length+A.input.content.length>D||A.semanticDigest!==void 0)throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"write",input:{path:A.input.path,content:A.input.content}}}function L(x){return x===void 0||typeof x==="number"&&Number.isFinite(x)}function GA(x){let A=x.args;if(!B(x,["tool","args"])||!U(A))return null;if(x.tool==="bash")return B(A,["command","timeout"])&&typeof A.command==="string"&&A.command.length<=K&&L(A.timeout)?{tool:"bash",args:{command:A.command,...A.timeout===void 0?{}:{timeout:Number(A.timeout)}}}:null;if(typeof A.path!=="string"||A.path.length>K)return null;if(x.tool==="read")return B(A,["path","offset","limit"])&&L(A.offset)&&L(A.limit)?{tool:"read",args:{path:A.path,...A.offset===void 0?{}:{offset:Number(A.offset)},...A.limit===void 0?{}:{limit:Number(A.limit)}}}:null;if(x.tool==="write")return B(A,["path","content"])&&typeof A.content==="string"&&A.path.length+A.content.length<=D?{tool:"write",args:{path:A.path,content:A.content}}:null;if(x.tool!=="edit"||!B(A,["path","edits"])||!Array.isArray(A.edits))return null;let W=A.path.length,N=[];for(let X of A.edits){if(!U(X)||!B(X,["oldText","newText"])||typeof X.oldText!=="string"||typeof X.newText!=="string")return null;if(W+=X.oldText.length+X.newText.length,W>D)return null;N.push({oldText:X.oldText,newText:X.newText})}return{tool:"edit",args:{path:A.path,edits:N}}}function NA(x){if(!U(x))return null;if("thrown"in x)return B(x,["thrown"])&&typeof x.thrown==="string"?{thrown:x.thrown}:null;let A=x.structuredContent;if(!B(x,["content","details","structuredContent","isError"])||!Array.isArray(x.content)||x.isError!==void 0&&x.isError!==!0||A!==void 0&&(!U(A)||!B(A,["output","truncated","full_output_path","exit_code","wall_time_seconds"])||typeof A.output!=="string"||typeof A.truncated!=="boolean"||A.full_output_path!==void 0&&typeof A.full_output_path!=="string"||typeof A.exit_code!=="number"||typeof A.wall_time_seconds!=="number"))return null;let W=[];for(let N of x.content)if(U(N)&&N.type==="text"&&B(N,["type","text"])&&typeof N.text==="string")W.push({type:"text",text:N.text});else if(U(N)&&N.type==="image"&&B(N,["type","data","mimeType"])&&typeof N.data==="string"&&typeof N.mimeType==="string")W.push({type:"image",data:N.data,mimeType:N.mimeType});else return null;return{content:W,...x.details===void 0?{}:{details:x.details},...U(A)?{structuredContent:{output:String(A.output),truncated:A.truncated===!0,...typeof A.full_output_path==="string"?{full_output_path:A.full_output_path}:{},exit_code:Number(A.exit_code),wall_time_seconds:Number(A.wall_time_seconds)}}:{},...x.isError===!0?{isError:!0}:{}}}function UA(x){let A=$(x);if(!U(A)||!B(A,["version","generation","id","ok","exitCode","stdout","stderr","cwd","error","resumed","browserActions","automaticProgressImage","piToolOutcome","workerElapsedMs","environmentWaitMs","workspaceBefore"])||A.version!==I||!Z(A.generation)||!M(A.id)||typeof A.ok!=="boolean"||!Number.isSafeInteger(A.exitCode)||Number(A.exitCode)<0||Number(A.exitCode)>255||typeof A.stdout!=="string"||A.stdout.length>_||typeof A.stderr!=="string"||A.stderr.length>_||A.cwd!==void 0&&(typeof A.cwd!=="string"||A.cwd.length<1||A.cwd.length>4096||!A.cwd.startsWith("/")||A.cwd.includes("\x00"))||A.error!==void 0&&(typeof A.error!=="string"||A.error.length<1||A.error.length>p||!e.has(A.error))||A.browserActions!==void 0&&!R(A.browserActions)||A.automaticProgressImage!==void 0&&(A.automaticProgressImage!==!0||!A.ok)||A.resumed!==void 0&&A.resumed!==!0||A.workerElapsedMs!==void 0&&(!Number.isSafeInteger(A.workerElapsedMs)||Number(A.workerElapsedMs)<0)||A.environmentWaitMs!==void 0&&(!Number.isSafeInteger(A.environmentWaitMs)||Number(A.environmentWaitMs)<0)||A.workspaceBefore!==void 0&&!h(A.workspaceBefore)||A.ok&&(A.exitCode!==0||A.error!==void 0)||!A.ok&&A.exitCode===0)throw new G("invalid_result");let W=A.piToolOutcome===void 0?void 0:NA(A.piToolOutcome);if(W===null||W&&!A.ok)throw new G("invalid_result");return{version:I,generation:A.generation,id:A.id,ok:A.ok,exitCode:Number(A.exitCode),stdout:A.stdout,stderr:A.stderr,...typeof A.cwd==="string"?{cwd:A.cwd}:{},...A.browserActions!==void 0?{browserActions:R(A.browserActions)}:{},...typeof A.error==="string"?{error:A.error}:{},...A.automaticProgressImage===!0?{automaticProgressImage:!0}:{},...A.resumed===!0?{resumed:!0}:{},...W?{piToolOutcome:W}:{},...A.workerElapsedMs!==void 0?{workerElapsedMs:Number(A.workerElapsedMs)}:{},...A.environmentWaitMs!==void 0?{environmentWaitMs:Number(A.environmentWaitMs)}:{},...h(A.workspaceBefore)?{workspaceBefore:{exitCode:A.workspaceBefore.exitCode,stdout:A.workspaceBefore.stdout,stderr:A.workspaceBefore.stderr}}:{}}}function h(x){return U(x)&&B(x,["exitCode","stdout","stderr"])&&Number.isSafeInteger(x.exitCode)&&Number(x.exitCode)>=0&&Number(x.exitCode)<=255&&typeof x.stdout==="string"&&x.stdout.length<=w&&typeof x.stderr==="string"&&x.stderr.length<=w}function FA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","sequence","stdout","stderr"])||A.type!=="progress"||A.version!==I||!Z(A.generation)||!M(A.id)||!Number.isSafeInteger(A.sequence)||Number(A.sequence)<1||typeof A.stdout!=="string"||A.stdout.length>_||typeof A.stderr!=="string"||A.stderr.length>_)throw new G("invalid_progress");return{type:"progress",version:I,generation:Number(A.generation),id:A.id,sequence:Number(A.sequence),stdout:A.stdout,stderr:A.stderr}}function IA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","fenceId","executorLaunchId","requestCancelVersion","managedJobsVersion","browserRunEnvelopeVersion","terminalCleanupVersion","guestMemoryVersion","guestMemoryDiagnosticsVersion","piToolsVersion","piToolsConfinement","backgroundBashVersion","machineSdkVersion","executionTimingVersion","environmentWaitVersion","workspaceBeforeVersion"])||A.type!=="claim"||A.version!==I||!Z(A.generation)||!J(A.fenceId)||!J(A.executorLaunchId)||A.requestCancelVersion!==void 0&&A.requestCancelVersion!==1||A.managedJobsVersion!==void 0&&A.managedJobsVersion!==k||A.guestMemoryVersion!==void 0&&A.guestMemoryVersion!==1||A.guestMemoryDiagnosticsVersion!==void 0&&(A.guestMemoryDiagnosticsVersion!==1||A.guestMemoryVersion!==1)||A.terminalCleanupVersion!==void 0&&A.terminalCleanupVersion!==1||A.browserRunEnvelopeVersion!==void 0&&A.browserRunEnvelopeVersion!==1||A.piToolsVersion!==void 0&&A.piToolsVersion!==1||A.piToolsConfinement!==void 0&&(!Y(A.piToolsConfinement)||A.piToolsVersion!==1)||A.backgroundBashVersion!==void 0&&A.backgroundBashVersion!==1||A.machineSdkVersion!==void 0&&A.machineSdkVersion!==1||A.executionTimingVersion!==void 0&&A.executionTimingVersion!==1||A.environmentWaitVersion!==void 0&&(A.environmentWaitVersion!==1||A.executionTimingVersion!==1)||A.workspaceBeforeVersion!==void 0&&A.workspaceBeforeVersion!==1)throw new G("invalid_claim");return{type:"claim",version:I,generation:A.generation,fenceId:A.fenceId,executorLaunchId:A.executorLaunchId,...A.requestCancelVersion===1?{requestCancelVersion:1}:{},...A.managedJobsVersion===1?{managedJobsVersion:1}:{},...A.guestMemoryVersion===1?{guestMemoryVersion:1}:{},...A.guestMemoryDiagnosticsVersion===1?{guestMemoryDiagnosticsVersion:1}:{},...A.terminalCleanupVersion===1?{terminalCleanupVersion:1}:{},...A.browserRunEnvelopeVersion===1?{browserRunEnvelopeVersion:1}:{},...A.piToolsVersion===1?{piToolsVersion:1}:{},...Y(A.piToolsConfinement)?{piToolsConfinement:{template:A.piToolsConfinement.template,quoteDepth:A.piToolsConfinement.quoteDepth}}:{},...A.backgroundBashVersion===1?{backgroundBashVersion:1}:{},...A.machineSdkVersion===1?{machineSdkVersion:1}:{},...A.executionTimingVersion===1?{executionTimingVersion:1}:{},...A.environmentWaitVersion===1?{environmentWaitVersion:1}:{},...A.workspaceBeforeVersion===1?{workspaceBeforeVersion:1}:{}}}function XA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","fenceId","executorLaunchId","workerVersion","workerArtifactSha256","requestCancelVersion","managedJobsVersion","lifecycleVersion","browserRunEnvelopeVersion","terminalCleanupVersion","guestMemoryVersion","guestMemoryDiagnosticsVersion","piToolsVersion","piToolsConfinementVersion","backgroundBashVersion","machineSdkVersion","executionTimingVersion","environmentWaitVersion","workspaceBeforeVersion"])||A.lifecycleVersion!==void 0&&A.lifecycleVersion!==1||A.workspaceBeforeVersion!==void 0&&A.workspaceBeforeVersion!==1||A.piToolsVersion!==void 0&&A.piToolsVersion!==1||A.piToolsConfinementVersion!==void 0&&(A.piToolsConfinementVersion!==1||A.piToolsVersion!==1)||A.backgroundBashVersion!==void 0&&A.backgroundBashVersion!==1||A.machineSdkVersion!==void 0&&A.machineSdkVersion!==1||A.executionTimingVersion!==void 0&&A.executionTimingVersion!==1||A.environmentWaitVersion!==void 0&&(A.environmentWaitVersion!==1||A.executionTimingVersion!==1)||A.guestMemoryVersion!==void 0&&A.guestMemoryVersion!==1||A.guestMemoryDiagnosticsVersion!==void 0&&(A.guestMemoryDiagnosticsVersion!==1||A.guestMemoryVersion!==1)||A.terminalCleanupVersion!==void 0&&A.terminalCleanupVersion!==1||A.browserRunEnvelopeVersion!==void 0&&A.browserRunEnvelopeVersion!==1||A.type!=="claim_ack"||A.version!==I||!Z(A.generation)||!J(A.fenceId)||!J(A.executorLaunchId)||!Number.isSafeInteger(A.workerVersion)||Number(A.workerVersion)<1||!S(A.workerArtifactSha256)||A.requestCancelVersion!==void 0&&A.requestCancelVersion!==1||A.managedJobsVersion!==void 0&&A.managedJobsVersion!==k)throw new G("invalid_claim_ack");return{type:"claim_ack",...A.guestMemoryVersion===1?{guestMemoryVersion:1}:{},...A.guestMemoryDiagnosticsVersion===1?{guestMemoryDiagnosticsVersion:1}:{},...A.terminalCleanupVersion===1?{terminalCleanupVersion:1}:{},...A.browserRunEnvelopeVersion===1?{browserRunEnvelopeVersion:1}:{},...A.lifecycleVersion===1?{lifecycleVersion:1}:{},...A.piToolsVersion===1?{piToolsVersion:1}:{},...A.piToolsConfinementVersion===1?{piToolsConfinementVersion:1}:{},...A.backgroundBashVersion===1?{backgroundBashVersion:1}:{},...A.machineSdkVersion===1?{machineSdkVersion:1}:{},...A.executionTimingVersion===1?{executionTimingVersion:1}:{},...A.environmentWaitVersion===1?{environmentWaitVersion:1}:{},...A.workspaceBeforeVersion===1?{workspaceBeforeVersion:1}:{},version:I,generation:A.generation,fenceId:A.fenceId,executorLaunchId:A.executorLaunchId,workerVersion:Number(A.workerVersion),workerArtifactSha256:A.workerArtifactSha256,...A.requestCancelVersion===1?{requestCancelVersion:1}:{},...A.managedJobsVersion===1?{managedJobsVersion:1}:{}}}function TA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","jobId","action","input"])||A.type!=="job"||A.version!==I||!Z(A.generation)||!M(A.id)||!M(A.jobId)||!U(A.input))throw new G("invalid_job_request");let W=A.input,N=Number.isSafeInteger(W.leaseExpiresAtMs)&&Number(W.leaseExpiresAtMs)>0,X=Number.isSafeInteger(W.sequence)&&Number(W.sequence)>=1;if(!(A.action==="start"?W.mode==="pty"?B(W,["mode","cols","rows","leaseExpiresAtMs"])&&C(A.jobId)&&z(W)&&N:B(W,["script","leaseExpiresAtMs"])&&typeof W.script==="string"&&W.script.length<=K&&N:A.action==="inspect"?B(W,["after"])&&Number.isSafeInteger(W.after)&&Number(W.after)>=0:A.action==="input"?"dataBase64"in W?B(W,["sequence","dataBase64"])&&C(A.jobId)&&X&&E(W.dataBase64)>0:B(W,["sequence","data","eof"])&&X&&typeof W.data==="string"&&W.data.length<=i&&typeof W.eof==="boolean":A.action==="resize"?B(W,["sequence","cols","rows"])&&C(A.jobId)&&X&&z(W):A.action==="renew"?B(W,["leaseExpiresAtMs"])&&N:A.action==="cancel"&&B(W,[])))throw new G("invalid_job_request");return A}function MA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","ok","job","error"])||A.type!=="job_result"||A.version!==I||!Z(A.generation)||!M(A.id))throw new G("invalid_job_result");if(A.ok===!1&&A.job===void 0&&typeof A.error==="string"&&WA.some((F)=>F===A.error))return A;let W=A.job;if(A.ok!==!0||A.error!==void 0||!U(W)||!B(W,["jobId","state","startedAtMs","finishedAtMs","leaseExpiresAtMs","exitCode","inputSequence","output","firstCursor","nextCursor","truncated","process","environmentRevision","environmentSnapshotId","pty"])||!M(W.jobId)||!["starting","running","exited","cancelled","expired","uncertain"].includes(String(W.state))||!Number.isSafeInteger(W.startedAtMs)||Number(W.startedAtMs)<1||!Number.isSafeInteger(W.leaseExpiresAtMs)||Number(W.leaseExpiresAtMs)<1||W.finishedAtMs!==null&&(!Number.isSafeInteger(W.finishedAtMs)||Number(W.finishedAtMs)<Number(W.startedAtMs))||W.exitCode!==null&&(!Number.isSafeInteger(W.exitCode)||Number(W.exitCode)<0||Number(W.exitCode)>255)||!Number.isSafeInteger(W.inputSequence)||Number(W.inputSequence)<0||!Number.isSafeInteger(W.firstCursor)||Number(W.firstCursor)<1||!Number.isSafeInteger(W.nextCursor)||Number(W.nextCursor)<Number(W.firstCursor)-1||typeof W.truncated!=="boolean"||!Array.isArray(W.output)||W.output.length>y)throw new G("invalid_job_result");if(W.environmentRevision===void 0!==(W.environmentSnapshotId===void 0)||W.environmentRevision!==void 0&&(!Number.isSafeInteger(W.environmentRevision)||Number(W.environmentRevision)<1||!J(W.environmentSnapshotId)))throw new G("invalid_job_result");let N=Number(W.firstCursor)-1,X=0;for(let F of W.output){if(!U(F)||!B(F,["cursor","stream","text"])||!Number.isSafeInteger(F.cursor)||Number(F.cursor)<=N||Number(F.cursor)>Number(W.nextCursor)||!["stdout","stderr"].includes(String(F.stream))||typeof F.text!=="string")throw new G("invalid_job_result");X+=F.text.length,N=Number(F.cursor)}if(X>d)throw new G("invalid_job_result");let V=W.state==="starting"||W.state==="running";if(V&&(W.finishedAtMs!==null||W.exitCode!==null)||!V&&W.finishedAtMs===null||W.state==="uncertain"&&W.exitCode!==null||W.state==="exited"&&W.exitCode===null||W.state==="cancelled"&&W.exitCode!==130||W.state==="expired"&&W.exitCode!==124)throw new G("invalid_job_result");if(W.process!==void 0){let F=W.process;if(!U(F)||!B(F,["pid","processGroupId","executorLaunchId"])||!Number.isSafeInteger(F.pid)||Number(F.pid)<1||F.processGroupId!==F.pid||!J(F.executorLaunchId)||!["starting","running"].includes(String(W.state)))throw new G("invalid_job_result")}if(W.pty!==void 0){let F=W.pty;if(!U(F)||!B(F,["version","cols","rows","output","cleanup"])||F.version!==H||!C(W.jobId)||!z(F)||W.output.length!==0||!Array.isArray(F.output)||F.output.length>y||(V?F.cleanup!=="pending":W.state==="uncertain"?F.cleanup!=="unconfirmed":F.cleanup!=="confirmed")||W.state==="running"&&(W.process===void 0||W.environmentRevision===void 0))throw new G("invalid_job_result");let T=Number(W.firstCursor)-1,P=0;for(let Q of F.output){if(!U(Q)||!B(Q,["cursor","dataBase64"])||!Number.isSafeInteger(Q.cursor)||Number(Q.cursor)<=T||Number(Q.cursor)>Number(W.nextCursor))throw new G("invalid_job_result");let q=E(Q.dataBase64);if(q<=0||(P+=q)>c)throw new G("invalid_job_result");T=Number(Q.cursor)}}return A}function qA(x){if(g(x)>s)throw new G("frame_too_large");let A=$(x);if(!U(A)||!B(A,["version","sessionId","operationId","runId","deviceId","rootId","workspace","binding","targetRevision","rootGrantRevision","generation","fenceId","executorLaunchId","job"])||A.version!==H||![A.sessionId,A.operationId,A.runId].every(M)||![A.deviceId,A.rootId,A.fenceId,A.executorLaunchId].every(J)||!Z(A.generation)||!Number.isSafeInteger(A.rootGrantRevision)||Number(A.rootGrantRevision)<1||!["workspace_source","mcp_control"].includes(String(A.binding))||!Number.isSafeInteger(A.targetRevision)||Number(A.targetRevision)<0||A.binding==="workspace_source"&&A.targetRevision!==0||!U(A.workspace))throw new G("invalid_pty_receipt");if(!f(A.workspace))throw new G("invalid_pty_receipt");let W=MA(JSON.stringify({type:"job_result",version:I,generation:A.generation,id:A.operationId,ok:!0,job:A.job}));if(!W.ok||!W.job.pty||W.job.pty.output.length!==0||W.job.process&&W.job.process.executorLaunchId!==A.executorLaunchId)throw new G("invalid_pty_receipt");return A}function yA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","targetId"])||A.type!=="cancel_request"||A.version!==I||!Z(A.generation)||!M(A.id)||!M(A.targetId))throw new G("invalid_cancel_request");return A}function mA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","targetId","status"])||A.type!=="cancel_ack"||A.version!==I||!Z(A.generation)||!M(A.id)||!M(A.targetId)||!["cancelled","settled","not_found","unsupported","unconfirmed"].includes(String(A.status)))throw new G("invalid_cancel_ack");return A}function wA(x){let A=JSON.stringify(x);return BA(A),A}function hA(x){let A=JSON.stringify(x);return UA(A),A}function fA(x){let A=JSON.stringify(x);return FA(A),A}function kA(x){let A=JSON.stringify(x);return IA(A),A}function HA(x){let A=JSON.stringify(x);return XA(A),A}function O(x){return typeof x==="string"&&x.length>=1&&x.length<=AA&&!x.includes("\x00")}function VA(x){let A=["type","version","generation","id","jobRequestId","verb"];if(x.verb==="help")return B(x,A)?{verb:"help"}:null;if(x.verb==="describe"||x.verb==="namespace")return B(x,[...A,"name"])&&O(x.name)?{verb:x.verb,name:x.name}:null;if(x.verb==="search"){let W=x.args;if(!B(x,[...A,"query","args"])||typeof x.query!=="string"||x.query.trim().length<1||x.query.length>xA)return null;if(W===void 0)return{verb:"search",query:x.query};if(!U(W)||!B(W,["namespace","limit"])||W.namespace!==void 0&&!O(W.namespace)||W.limit!==void 0&&(!Number.isSafeInteger(W.limit)||Number(W.limit)<1||Number(W.limit)>50))return null;return{verb:"search",query:x.query,args:{...typeof W.namespace==="string"?{namespace:W.namespace}:{},...W.limit===void 0?{}:{limit:Number(W.limit)}}}}if(x.verb!=="call"||!B(x,[...A,"name","args"])||!O(x.name)||!U(x.args)||JSON.stringify(x.args).length>K)return null;return{verb:"call",name:x.name,args:x.args}}function gA(x){let A=$(x);if(!U(A)||A.type!=="sdk_request"||A.version!==I||!Z(A.generation)||!M(A.id)||!M(A.jobRequestId))throw new G("invalid_sdk_request");let W=VA(A);if(!W)throw new G("invalid_sdk_request");return{type:"sdk_request",version:I,generation:Number(A.generation),id:A.id,jobRequestId:A.jobRequestId,...W}}function ZA(x){let A=$(x);if(!U(A)||A.type!=="sdk_response"||A.version!==I||!Z(A.generation)||!M(A.id))throw new G("invalid_sdk_response");let W={type:"sdk_response",version:I,generation:Number(A.generation),id:A.id},N=["type","version","generation","id","ok"];if(A.ok===!0&&B(A,[...N,"result"])&&typeof A.result==="string"&&A.result.length<=_)return{...W,ok:!0,result:A.result};if(A.ok===!1&&B(A,[...N,"error"])&&typeof A.error==="string"&&A.error.length>=1&&A.error.length<=_)return{...W,ok:!1,error:A.error};throw new G("invalid_sdk_response")}function EA(x){let A=JSON.stringify(x);return ZA(A),A}
4
- export{$A as Gg,KA as Hg,QA as Ig,I as Jg,b as Kg,K as Lg,D as Mg,_ as Ng,YA as Og,p as Pg,k as Qg,i as Rg,d as Sg,y as Tg,LA as Ug,s as Vg,H as Wg,m as Xg,c as Yg,OA as Zg,n as _g,t as $g,r as ah,zA as bh,l as ch,SA as dh,a as eh,w as fh,AA as gh,xA as hh,WA as ih,G as jh,M as kh,Z as lh,J as mh,C as nh,S as oh,BA as ph,UA as qh,FA as rh,IA as sh,XA as th,TA as uh,MA as vh,qA as wh,yA as xh,mA as yh,wA as zh,hA as Ah,fA as Bh,kA as Ch,HA as Dh,gA as Eh,ZA as Fh,EA as Gh};
4
+ export{$A as Hg,KA as Ig,QA as Jg,I as Kg,b as Lg,K as Mg,D as Ng,_ as Og,YA as Pg,p as Qg,k as Rg,i as Sg,d as Tg,y as Ug,LA as Vg,s as Wg,H as Xg,m as Yg,c as Zg,OA as _g,n as $g,t as ah,r as bh,zA as ch,l as dh,SA as eh,a as fh,w as gh,AA as hh,xA as ih,WA as jh,G as kh,M as lh,Z as mh,J as nh,C as oh,S as ph,BA as qh,UA as rh,FA as sh,IA as th,XA as uh,TA as vh,MA as wh,qA as xh,yA as yh,mA as zh,wA as Ah,hA as Bh,fA as Ch,kA as Dh,HA as Eh,gA as Fh,ZA as Gh,EA as Hh};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ee as LJ,Me as _J,qf as CJ}from"./vm-hands-entry-lite-fr2k6eah.js";import{createHash as I,randomBytes as zJ}from"crypto";import{closeSync as qJ,fsyncSync as NJ,mkdirSync as fJ,openSync as DJ,renameSync as mJ,rmSync as bJ,statSync as AJ,writeSync as xJ,constants as y}from"fs";import{join as i}from"path";var cJ=1;var r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function QJ(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 UJ(J,Z){let{payload:z,authority:Q}=J;if(!z||typeof z!=="object"||Array.isArray(z)||!Q||typeof Q!=="object"||Array.isArray(Q)||!Z.deviceId||!Z.rootId||z.run_id!==Z.runId||z.device_id!==Z.deviceId||Q.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 MJ(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"&&r.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:QJ(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 jZ(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),Q=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),j=new Uint8Array(await crypto.subtle.exportKey("spki",Q.publicKey)),q=I("sha256").update(z).digest("base64url");return{signing:{privateKey:Z},agreement:Q,signingSpki:z,agreementSpki:j,fingerprint:q}}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,Q){this.init=J;this.keys=Z;this.hooks=z;this.options=Q;if(!r.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 Q=Date.now()+Z;;){let j=this.bound.get(J);if(!j)return!1;if(j.envInstalled)return!0;if(Date.now()>=Q||z?.aborted)return!1;await new Promise((q)=>setTimeout(q,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)()),Q=v(zJ(32)),j=CJ({method:"GET",pathAndQuery:LJ,timestamp:z,nonce:Q,challenge:J,bodySha256:I("sha256").update("").digest("hex")}),q=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(j)));return{t:"hello",timestamp:z,nonce:Q,signature:v(uJ(q)),...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(!r.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,Q=!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,Q=!0;let{launchId:j,applied:q,readyData:B}=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}),O=this.hooks.restatLayout(),N=null,h=null;if(J.env){let D=J.claim?.owner??{},_=UJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof D.device_id==="string"?D.device_id:"",rootId:J.claim?.root_id??""});this.commandsSinceVerified=!0,N=this.hooks.installEnvironment(J.bind_id,_),h=typeof _.snapshot_id==="string"&&_.snapshot_id?_.snapshot_id:null,z=this.writeJobEnvRootOnly(J.bind_id,_)}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:j,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:j,snapshot_revision:N,snapshot_id:h,layout:O,...B?{ready_data:B}:{},policy_digest:I("sha256").update(f({hands_confinement:q.hands_confinement??null,browser_egress:q.browser_egress??null})).digest("hex")}}catch(j){if(z)KJ(z);if(Q){let B=[...this.bound.keys()];await this.hooks.killAndVerifyPayload({bindId:J.bind_id,keep:B,own:!0}).catch(()=>{this.unverified.add(J.bind_id)})}this.binding.delete(J.bind_id);let q=j&&typeof j==="object"&&"code"in j&&typeof j.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(j.code)?j.code:"vm_hands_bind_failed";throw j instanceof W?j:new W(q,"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(!r.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 Q=UJ(await this.openSealed(J.sealed,z),{runId:Z.runId,deviceId:J.deviceId,rootId:Z.rootId,snapshotId:J.snapshotId});this.commandsSinceVerified=!0;let j=this.hooks.installEnvironment(Z.bindId,Q);if(Z.envInstalled=!0,Z.envDirectory)KJ(Z.envDirectory);return Z.envDirectory=null,Z.envDirectory=this.writeJobEnvRootOnly(`${Z.bindId}-r${j}`,Q),{snapshot_id:J.snapshotId,installed_revision:j,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((j)=>j!==J),Q=!z.length&&!this.commandsSinceVerified;try{await this.hooks.killAndVerifyPayload(z.length?{bindId:J,keep:z}:Q?{bindId:J,own:!0}:void 0)}catch(j){throw this.unverified.add(J),j}if(!z.length)this.unverified.clear(),this.commandsSinceVerified=!1;if(Z?.envDirectory)KJ(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")},Q=await crypto.subtle.importKey("spki",R(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(z),j=await crypto.subtle.deriveKey({name:"ECDH",public:Q},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),q=await crypto.subtle.decrypt({name:"AES-GCM",iv:R(J.iv),additionalData:new TextEncoder().encode(Z)},j,R(J.ct)).catch(z),B=JSON.parse(new TextDecoder().decode(q));if(!B||typeof B!=="object"||Array.isArray(B))throw new W("vm_hands_env_invalid","env not an object");return B}writeJobEnvRootOnly(J,Z){let z=i(this.options.envRoot,`bind-${J}`);fJ(z,{mode:448});let Q=AJ(z);if(!Q.isDirectory()||(Q.mode&63)!==0||Q.uid!==(process.getuid?.()??-1))throw new W("vm_hands_env_dir_unsafe","env directory is not root's 0700");let j=Z.variables&&typeof Z.variables==="object"?Z.variables:{},q=Object.entries(j).filter(([N,h])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(N)&&typeof h==="string").map(([N,h])=>`export ${N}='${String(h).replaceAll("'","'\\''")}'`).join(`
2
+ import{Fe as LJ,Ne as _J,rf as CJ}from"./vm-hands-entry-lite-cvft83sx.js";import{createHash as I,randomBytes as zJ}from"crypto";import{closeSync as qJ,fsyncSync as NJ,mkdirSync as fJ,openSync as DJ,renameSync as mJ,rmSync as bJ,statSync as AJ,writeSync as xJ,constants as y}from"fs";import{join as i}from"path";var cJ=1;var r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function QJ(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 UJ(J,Z){let{payload:z,authority:Q}=J;if(!z||typeof z!=="object"||Array.isArray(z)||!Q||typeof Q!=="object"||Array.isArray(Q)||!Z.deviceId||!Z.rootId||z.run_id!==Z.runId||z.device_id!==Z.deviceId||Q.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 MJ(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"&&r.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:QJ(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 jZ(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),Q=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),j=new Uint8Array(await crypto.subtle.exportKey("spki",Q.publicKey)),q=I("sha256").update(z).digest("base64url");return{signing:{privateKey:Z},agreement:Q,signingSpki:z,agreementSpki:j,fingerprint:q}}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,Q){this.init=J;this.keys=Z;this.hooks=z;this.options=Q;if(!r.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 Q=Date.now()+Z;;){let j=this.bound.get(J);if(!j)return!1;if(j.envInstalled)return!0;if(Date.now()>=Q||z?.aborted)return!1;await new Promise((q)=>setTimeout(q,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)()),Q=v(zJ(32)),j=CJ({method:"GET",pathAndQuery:LJ,timestamp:z,nonce:Q,challenge:J,bodySha256:I("sha256").update("").digest("hex")}),q=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(j)));return{t:"hello",timestamp:z,nonce:Q,signature:v(uJ(q)),...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(!r.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,Q=!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,Q=!0;let{launchId:j,applied:q,readyData:B}=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}),O=this.hooks.restatLayout(),N=null,h=null;if(J.env){let D=J.claim?.owner??{},_=UJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof D.device_id==="string"?D.device_id:"",rootId:J.claim?.root_id??""});this.commandsSinceVerified=!0,N=this.hooks.installEnvironment(J.bind_id,_),h=typeof _.snapshot_id==="string"&&_.snapshot_id?_.snapshot_id:null,z=this.writeJobEnvRootOnly(J.bind_id,_)}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:j,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:j,snapshot_revision:N,snapshot_id:h,layout:O,...B?{ready_data:B}:{},policy_digest:I("sha256").update(f({hands_confinement:q.hands_confinement??null,browser_egress:q.browser_egress??null})).digest("hex")}}catch(j){if(z)KJ(z);if(Q){let B=[...this.bound.keys()];await this.hooks.killAndVerifyPayload({bindId:J.bind_id,keep:B,own:!0}).catch(()=>{this.unverified.add(J.bind_id)})}this.binding.delete(J.bind_id);let q=j&&typeof j==="object"&&"code"in j&&typeof j.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(j.code)?j.code:"vm_hands_bind_failed";throw j instanceof W?j:new W(q,"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(!r.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 Q=UJ(await this.openSealed(J.sealed,z),{runId:Z.runId,deviceId:J.deviceId,rootId:Z.rootId,snapshotId:J.snapshotId});this.commandsSinceVerified=!0;let j=this.hooks.installEnvironment(Z.bindId,Q);if(Z.envInstalled=!0,Z.envDirectory)KJ(Z.envDirectory);return Z.envDirectory=null,Z.envDirectory=this.writeJobEnvRootOnly(`${Z.bindId}-r${j}`,Q),{snapshot_id:J.snapshotId,installed_revision:j,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((j)=>j!==J),Q=!z.length&&!this.commandsSinceVerified;try{await this.hooks.killAndVerifyPayload(z.length?{bindId:J,keep:z}:Q?{bindId:J,own:!0}:void 0)}catch(j){throw this.unverified.add(J),j}if(!z.length)this.unverified.clear(),this.commandsSinceVerified=!1;if(Z?.envDirectory)KJ(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")},Q=await crypto.subtle.importKey("spki",R(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(z),j=await crypto.subtle.deriveKey({name:"ECDH",public:Q},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),q=await crypto.subtle.decrypt({name:"AES-GCM",iv:R(J.iv),additionalData:new TextEncoder().encode(Z)},j,R(J.ct)).catch(z),B=JSON.parse(new TextDecoder().decode(q));if(!B||typeof B!=="object"||Array.isArray(B))throw new W("vm_hands_env_invalid","env not an object");return B}writeJobEnvRootOnly(J,Z){let z=i(this.options.envRoot,`bind-${J}`);fJ(z,{mode:448});let Q=AJ(z);if(!Q.isDirectory()||(Q.mode&63)!==0||Q.uid!==(process.getuid?.()??-1))throw new W("vm_hands_env_dir_unsafe","env directory is not root's 0700");let j=Z.variables&&typeof Z.variables==="object"?Z.variables:{},q=Object.entries(j).filter(([N,h])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(N)&&typeof h==="string").map(([N,h])=>`export ${N}='${String(h).replaceAll("'","'\\''")}'`).join(`
3
3
  `)+`
4
4
  `,B=i(z,`.job.env.${zJ(8).toString("hex")}`),O=DJ(B,y.O_WRONLY|y.O_CREAT|y.O_EXCL|y.O_NOFOLLOW,384);try{xJ(O,q),NJ(O)}finally{qJ(O)}return mJ(B,i(z,"job.env")),z}}function KJ(J){try{let Z=i(J,"job.env"),z=AJ(Z).size,Q=DJ(Z,y.O_WRONLY|y.O_NOFOLLOW);try{xJ(Q,Buffer.alloc(z)),NJ(Q)}finally{qJ(Q)}}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=(j)=>{let q=0;while(q<j.length-1&&j[q]===0)q++;let B=j.subarray(q),O=B[0]&128?Uint8Array.of(0,...B):B;return Uint8Array.of(2,O.length,...O)},z=Z(J.subarray(0,32)),Q=Z(J.subarray(32));return Uint8Array.of(48,z.length+Q.length,...z,...Q)}import{randomUUID as oJ}from"crypto";var dJ="/app/local-runtime/session?register=vm_hands_v1",iJ="/app/local-runtime",OJ=25000,rJ=20000,sJ=1e4,TJ=5000,wJ=new Set(["pty.start","jobs.control","preview.serve.v1","display.stream.v1"]),FJ=75000,aJ=2000,nJ=1e4,tJ=new Set(["vm_hands_no_register","vm_hands_register_failed"]),eJ=3,JZ=20000,ZZ=250,$Z=2000,s=20000;function hJ(J,Z){return typeof J==="string"&&/^[A-Za-z0-9._:-]{1,160}$/.test(J)?J:Z}class g extends Error{}var zZ=64;async function kJ(J,Z){let z=[...J.modelOps.get(Z)??[]];for(let Q of z)Q.abort.abort();await Promise.race([Promise.all(z.map((Q)=>Q.settled)),new Promise((Q)=>setTimeout(Q,TJ))])}async function KZ(J){let Z=[...J.personTerminals];for(let z of Z)z.abort.abort();if(Z.length)await Promise.race([Promise.all(Z.map((z)=>z.settled)),new Promise((z)=>setTimeout(z,TJ))]);return Z.length}async function m(J,Z,z){return await kJ(J,z),Z.unbind(z)}function a(J){for(let Z of J.outbox?.splice(0)??[])Z.reject(Error("vm_hands_attempt_ended"))}var EJ=15000,QZ=1e4,FZ=1000;async function NZ(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},Q=J.log??(()=>{}),j=async(O)=>{for(let[N,h]of[...z.turns]){z.turns.delete(N),J.onTurn?.(N,null),a(h);let D=await m(z,J.agent,N).catch(()=>null);if(D)z.receipts.push({turn:h,failure:"vm_hands_bind_lost",unbound:D});Q("vm_hands.bound_dropped",{reason:O})}},q=0,B=0;try{for(let O=0;!J.signal.aborted;O++){let N=await XZ(J,z).catch((D)=>{if(D instanceof W&&z.deviceId===null&&D.code==="vm_hands_no_session"&&Date.now()-Z<nJ)return{closeCode:0,closeReason:"vm_hands_no_session"};if(D instanceof W&&z.deviceId===null&&tJ.has(D.code)&&q<eJ&&Date.now()-Z<JZ){q++;let _=Math.min(ZZ*2**(q-1),$Z);return B=Math.round(_/2+Math.random()*_/2),Q("vm_hands.register_retry",{attempt:q,code:D.code,delay_ms:B}),{closeCode:0,closeReason:"vm_hands_register_retry"}}if(D instanceof W&&z.deviceId===null)throw D;return{closeCode:0,closeReason:D instanceof Error?D.message:String(D)}});if(Q("vm_hands.session_closed",{close_code:N.closeCode,reason:N.closeReason.slice(0,120),registered:z.deviceId!==null}),N.closeCode===4401||z.attest==="refused")return;if(J.signal.aborted)return;if(z.turns.size&&Date.now()-z.lostAt>=FJ)await j("reconnect_deadline");if(z.served)z.served=!1,O=0;let h=N.closeReason==="drain_reconnect"?0:N.closeReason==="vm_hands_register_retry"?B:N.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(O,5),2000):z.turns.size?Math.min(250*2**Math.min(O,5),5000,Math.max(0,z.lostAt+FJ-Date.now())):Math.min(500*2**O,30000);if(await new Promise((D)=>setTimeout(D,h)),z.turns.size&&Date.now()-z.lostAt>=FJ)await j("reconnect_deadline")}}finally{await j("session_ended")}}async function XZ(J,Z){let z=Z.deviceId,Q=J.log??(()=>{}),j=z?`/app/local-runtime/session?device_id=${encodeURIComponent(z)}`:dJ,q=`${J.apiOrigin.replace(/^http/,"ws")}${j}`,B=new WebSocket(q),O=0,N="",h=new Map,D=[],_=null,XJ=new Promise(($)=>{B.onclose=(X)=>{O=X.code,N=X.reason;for(let K of h.values())K.reject(new g(`session closed ${X.code}`));for(let K of Z.attestWaiters.splice(0))K(!1);h.clear(),$()}});B.onmessage=($)=>{let X;try{X=JSON.parse(String($.data))}catch{B.close(4400);return}if(X.t==="res"){let K=X;h.get(K.id)?.resolve({status:K.status,body:K.body}),h.delete(K.id);return}if(X.t==="reconnect"){let K=Math.max(0,Math.min(Number(X.after_ms)||0,FZ));Q("vm_hands.drain_reconnect",{after_ms:K}),setTimeout(()=>{try{B.close(4001,"drain_reconnect")}catch{}},K).unref?.();return}if(!_?.(X))D.push(X)};let b=($,X)=>new Promise((K,G)=>{let U=D.findIndex((L)=>$.includes(L.t));if(U>=0){K(D.splice(U,1)[0]);return}let C=setTimeout(()=>{_=null,G(new W("vm_hands_no_register",`no ${$.join("/")} in ${X} ms`))},X);_=(L)=>{if(!$.includes(L.t))return!1;return clearTimeout(C),_=null,K(L),!0}}),c=($)=>B.send(JSON.stringify($)),H=($,X)=>new Promise((K,G)=>{if(B.readyState!==WebSocket.OPEN){G(new g("session closed"));return}let U=oJ(),C=typeof X.wait_ms==="number"?X.wait_ms:0,L=setTimeout(()=>{if(!h.delete(U))return;G(new g(`no answer to ${$.split("/").pop()} in ${C+EJ} ms`)),B.close(4000,"request_timeout")},C+EJ);h.set(U,{reject:(F)=>{clearTimeout(L),G(F)},resolve:({status:F,body:Y})=>{clearTimeout(L);let P=null;try{P=Y?JSON.parse(Y):null}catch{}K({status:F,json:P})}}),c({t:"req",id:U,path:`${iJ}${$}`,body:JSON.stringify(X)})}),GJ=()=>B.close(1001,"stopping");J.signal.addEventListener("abort",GJ,{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((F,Y)=>{let P=setTimeout(()=>Y(Error("session open timeout")),QZ);B.onopen=()=>{clearTimeout(P),Q("vm_hands.ws_open",{}),F()},B.onerror=()=>{clearTimeout(P),Y(Error("session socket error"))}});let $=await b(["challenge"],5000);Q("vm_hands.challenge",{});let X=[],K=null,G;if(z){c(await J.agent.helloFrame($.challenge,Z.connection));let F=await b(["ready"],1e4);if(typeof F.vm_hands_connection==="string")Z.connection=F.vm_hands_connection;if(G={device_id:z,...F.cadence?{cadence:F.cadence}:{}},typeof F.vm_hands_probe_script==="string"){if(K=F.vm_hands_probe_script,u=!0,J.agent.phase==="registered"&&!Z.turns.size)Z.attest="pending"}Z.served=!0,Q("vm_hands.reconnected",{device_id:z});let Y=Array.isArray(F.vm_hands_binds)?F.vm_hands_binds:F.vm_hands_bind?[F.vm_hands_bind]:[];for(let[P,A]of[...Z.turns]){if(Y.some((E)=>E&&E.operation_id===A.claim.operation_id&&E.attempt_id===A.claim.attempt_id)){X.push(A),Q("vm_hands.bound_resumed",{operation_id:A.claim.operation_id});continue}Z.turns.delete(P),J.onTurn?.(P,null),a(A);let M=await m(Z,J.agent,P).catch(()=>null);if(M)Z.receipts.push({turn:A,failure:"vm_hands_bind_lost",unbound:M});Q("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}else{c(await J.agent.registerFrame($.challenge)),Q("vm_hands.register_sent",{});let F=await Promise.race([b(["registered","register_refused"],1e4),XJ.then(()=>{throw new W(N==="register_failed"?"vm_hands_register_failed":"vm_hands_register_closed","session closed before the register was answered")})]);if(F.t==="register_refused")throw new W(F.code,"register refused");J.agent.registered();let Y=F;if(G=Y,Z.deviceId=Y.device_id,typeof Y.vm_hands_connection==="string")Z.connection=Y.vm_hands_connection;if(typeof Y.vm_hands_probe_script==="string"){if(K=Y.vm_hands_probe_script,u=!0,J.agent.phase==="registered"&&!Z.turns.size)Z.attest="pending"}Z.served=!0,Q("vm_hands.registered",{device_id:G.device_id})}let U=async()=>{let F=await H("/heartbeat",await J.heartbeat());if(F.status>=300)throw Error(`heartbeat ${F.status}`)};await U();let C=G.cadence?.presence_interval_ms??30000;if(n=setInterval(()=>{U().catch(()=>B.close())},C),K&&Z.attest!=="accepted"&&J.agent.phase==="registered"&&!Z.turns.size)HJ(K,$.challenge);let L=(F,Y)=>{l.set(F,Y().catch(async(P)=>{if(await YJ(P,F),P instanceof g)B.close();else await $J().catch(()=>{return})}).finally(()=>{l.delete(F)}))};try{await $J();for(let F of X)F.flush=()=>WJ(F),F.flush(),L(F.claim.attempt_id,()=>PJ(F));while(!J.signal.aborted&&B.readyState===WebSocket.OPEN){let F=await H("/operations/claim",{wait_ms:Math.min(G.cadence?.claim_wait_ms??OJ,OJ)});if(F.status===204||!F.json)continue;if(F.status>=300)throw Error(`claim ${F.status}`);let Y=F.json;if(Y.capability==="hands.connect"){if(l.has(Y.attempt_id)){T({claim:Y,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}L(Y.attempt_id,()=>VJ(Y))}else SJ(Y).catch(()=>{return})}}catch(F){await YJ(F,null)}}finally{if(n)clearInterval(n);J.signal.removeEventListener("abort",GJ);for(let $ of Z.turns.values())$.flush=null;B.close(),await XJ,await Promise.all([...l.values()]);for(let $ of J.agent.liveBindIds){if(Z.turns.has($))continue;let X=await m(Z,J.agent,$).catch(()=>null),K=p.get($);if(X&&K)Z.receipts.push({turn:{...K,eventSeq:K.eventSeq+1},failure:"vm_hands_bind_lost",unbound:X});Q("vm_hands.bound_dropped",{reason:"bound_after_loss"})}for(let $ of e)$.abort()}return{closeCode:O,closeReason:N};async function YJ($,X){if($ instanceof g){if(!t&&Z.turns.size)Z.lostAt=Date.now();t=!0}else{let K=X!==null?[X]:[...new Set([...Z.turns.keys(),...J.agent.liveBindIds])];if(X===null)t=!0;for(let G of K){let U=Z.turns.get(G);if(Z.turns.delete(G),U)a(U),J.onTurn?.(G,null);if(J.agent.liveBindIds.includes(G)){let C=await m(Z,J.agent,G).catch(()=>null),L=p.get(G)??U;if(C&&L)Z.receipts.push({turn:{...L,eventSeq:L.eventSeq+1},failure:"vm_hands_bind_lost",unbound:C})}}}Q("vm_hands.session_lost",{error:$ instanceof Error?$.message:String($),bound_kept:Z.turns.size})}function T($){let X=$.claim,K={attempt_id:X.attempt_id,attempt_token:X.attempt_token},G=encodeURIComponent(X.operation_id);return{fence:K,op:G,complete:(C,L={})=>H(`/operations/${G}/complete`,{...K,status:C,...L}),emit:(C,L)=>{let F=($.chain??Promise.resolve()).catch(()=>{return}).then(()=>U(C,L));return $.chain=F,F}};async function U(C,L){let F=$.eventSeq,Y=(E)=>H(`/operations/${G}/events`,{...K,event_seq_start:E,events:[{kind:C,payload:{sequence:E,capability:String(X.capability??"hands.connect"),data:L}}]}),P=F,A=await Y(P),M=A.status===409?A.json?.expected_event_seq:void 0;if(typeof M==="number"&&M===F+1)A={status:200,json:{duplicate:!0}};else if(typeof M==="number"&&M>=0&&M!==F)P=M,A=await Y(P);if(A.status<300)$.eventSeq=P+1;return A}}function gJ($){return(X,K)=>new Promise((G,U)=>{if(Z.turns.get($.claim.attempt_id)!==$){U(Error("vm_hands_attempt_ended"));return}if($.outbox??=[],$.outbox.length>=zZ){U(Error("vm_hands_outbox_full"));return}$.outbox.push({kind:X,data:K,resolve:G,reject:U}),$.flush?.()})}function WJ($){if(JJ.has($))return;JJ.add($),(async()=>{try{while($.outbox?.length&&Z.turns.get($.claim.attempt_id)===$&&B.readyState===WebSocket.OPEN){let X=$.outbox[0],K;try{K=await T($).emit(X.kind,X.data)}catch(G){if(G instanceof g)return;K={status:500}}if($.outbox.shift(),K.status<300)X.resolve();else X.reject(Error(`${X.kind} refused ${K.status}`))}}finally{JJ.delete($)}})()}async function HJ($,X){try{let K=await J.agent.attestFrame($,X);if(B.readyState!==WebSocket.OPEN)return;c(K);let G=await b(["attested","attest_refused"],15000);Z.attest=G.t==="attested"?"accepted":"refused";for(let U of Z.attestWaiters.splice(0))U(Z.attest==="accepted");if(Q("vm_hands.attest",{result:Z.attest,exit_code:K.exit_code,...G.t==="attest_refused"?{code:String(G.code??"")}:{}}),Z.attest==="refused")B.close(4401,"attest_refused")}catch(K){Q("vm_hands.attest_failed",{code:K instanceof W?K.code:"probe_error"});for(let G of Z.attestWaiters.splice(0))G(!1);if(Z.attest!=="accepted")B.close(4000,"attest_unanswered")}}async function VJ($){let X=u&&Z.attest==="pending",K=$.vm_hands_attest,G=K;if(Z.attest==="refused"){Q("vm_hands.claim_attest_refused",{said:typeof K==="string"?K.slice(0,16):typeof K,local:Z.attest}),await T({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(G==="accepted"){if(!X&&Z.attest!=="accepted"){Z.attest="accepted";for(let w of Z.attestWaiters.splice(0))w(!0)}}else if(G!=="pending"||!X&&Z.attest!=="accepted"){Q("vm_hands.claim_attest_refused",{said:typeof K==="string"?K.slice(0,16):typeof K,local:Z.attest}),await T({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(Z.attest!=="accepted"){let w=Date.parse($.lease_until)-Date.now()-5000,S=Math.max(0,Math.min(s,Number.isFinite(w)?w:s));if(!await new Promise((d)=>{let x=setTimeout(()=>d(!1),S);Z.attestWaiters.push((k)=>{clearTimeout(x),d(k)})})){await T({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let U={claim:$,eventSeq:0},{complete:C,emit:L}=T(U),F;try{if($.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not hands.connect");F=!QJ($)}catch(w){Q("vm_hands.bind_refused",{code:w instanceof W?w.code:"unexpected"}),await C("failed",{error_code:w instanceof W?w.code:"vm_hands_bind_invalid"});return}let Y;Z.bindsStarting++;try{let w=await KZ(Z);if(w)Q("vm_hands.person_terminals_closed",{count:w});Y=await J.agent.bind(MJ($))}catch(w){Q("vm_hands.bind_refused",{code:w instanceof W?w.code:"unexpected"}),await C("failed",{error_code:w instanceof W?w.code:"vm_hands_bind_failed"});return}finally{Z.bindsStarting--}let P={...Y.ready_data??J.readyData({launchId:Y.launch_id,claim:$})};if(F)delete P.environment_installed;let A=!F&&Y.snapshot_revision!==null&&Y.snapshot_id!==null?{environment_installed:{snapshot_id:Y.snapshot_id,installed_revision:Y.snapshot_revision}}:{};p.set($.attempt_id,{claim:$,launchId:Y.launch_id,readyData:P,eventSeq:U.eventSeq,ackSeq:-1});let M=await L("hands.ready",{...P,...A,vm_hands:{layout:Y.layout,policy_digest:Y.policy_digest,launch_id:Y.launch_id}});if(p.delete($.attempt_id),M.status>=300){await kJ(Z,$.attempt_id),await J.agent.boundRefused($.attempt_id),await C("failed",{error_code:hJ(M.json?.error,"vm_hands_probe_failed")});return}let E={claim:$,launchId:Y.launch_id,readyData:P,eventSeq:U.eventSeq,ackSeq:-1};Z.turns.set($.attempt_id,E),E.flush=()=>WJ(E),J.onTurn?.($.attempt_id,gJ(E)),await PJ(E)}async function PJ($){let{fence:X,op:K}=T($),G=null,U=null,C=J.agent.executorExited($.claim.attempt_id).then((L)=>{return U=L,null});J:for(;;){let L=await Promise.race([C,H(`/operations/${K}/heartbeat`,{...X,control_ack_seq:$.ackSeq,wait_ms:rJ})]);if(!L){G="vm_hands_executor_exited",Q("vm_hands.executor_exited",{reason:U});break}if(L.status>=300)break;let F=(L.json?.controls??[]).slice().sort((Y,P)=>Y.seq-P.seq);for(let Y of F){if(Y.seq<=$.ackSeq)continue;if(Y.kind==="operation.cancel"||Y.kind==="cancel"){$.ackSeq=Y.seq;break J}if(Y.kind===_J)try{await yJ($,Y.payload??{})}catch(P){if(P instanceof g)throw P;G=P instanceof W?P.code:"environment_unavailable";let A=P&&typeof P==="object"&&"code"in P&&typeof P.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(P.code)?P.code:null;Q("vm_hands.environment_refused",{code:G,cause:A});break J}$.ackSeq=Y.seq}}await vJ($,G)}async function SJ($){let X=$,K={claim:X,eventSeq:0},{complete:G,emit:U,fence:C,op:L}={...T(K)},F=$.vm_hands_origin==="person"?"person":"model",Y=String($.capability??"");if(!J.executeOp){await G("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 x of Z.attestWaiters.splice(0))x(!0)}if(Z.attest!=="accepted"){let x=Date.parse(String($.lease_until??""))-Date.now()-5000,k=Z.attest==="refused"?0:Math.max(0,Math.min(s,Number.isFinite(x)?x:s));if(!(k>0&&await new Promise((BJ)=>{let IJ=setTimeout(()=>BJ(!1),k);Z.attestWaiters.push((RJ)=>{clearTimeout(IJ),BJ(RJ)})}))){await G("failed",{error_code:"vm_hands_unattested"});return}}let P=J.agent.bindIdForRun(X.run_id);if(F==="model"&&P===null){await G("failed",{error_code:"vm_hands_not_bound"});return}let A=Y==="pty.start"&&F==="person"&&!$.authority;if(A&&(J.agent.liveBindIds.length>0||Z.bindsStarting>0)){await G("failed",{error_code:"vm_hands_bound"});return}if(wJ.has(Y)&&!A&&J.agent.liveBindIds.length===0){await G("failed",{error_code:"vm_hands_not_bound"});return}if(F==="model"&&P||wJ.has(Y)&&!A)J.agent.opServed();let M=new AbortController;e.add(M);let E,w=new Promise((x)=>{E=x}),S={abort:M,settled:w};if(A)Z.personTerminals.add(S);if(F==="model"&&P){let x=Z.modelOps.get(P)??new Set;x.add(S),Z.modelOps.set(P,x),await J.agent.environmentInstalled(P,aJ,M.signal)}let o=-1,d=setInterval(()=>{H(`/operations/${L}/heartbeat`,{...C,control_ack_seq:o,wait_ms:0}).then((x)=>{if(x.status>=300){M.abort();return}let k=x.json?.controls??[];for(let V of k)if(o=Math.max(o,V.seq),V.kind==="operation.cancel"||V.kind==="cancel")M.abort()},()=>M.abort())},sJ);try{let x=await J.executeOp({kind:F,claim:$,...F==="model"&&P?{bindId:P}:{},signal:M.signal,emit:async(V)=>{await U(V.kind,V.data??{})}}),k=await G(x.status,{...x.result?{result:x.result}:{},...x.error_code?{error_code:hJ(x.error_code,"vm_hands_op_failed")}:{}});Q("vm_hands.op",{capability:Y,kind:F,status:x.status,code:x.error_code??null,...k.status>=300?{complete_status:k.status,complete_error:String(k.json?.error??"").slice(0,64)}:{}})}finally{if(clearInterval(d),e.delete(M),P)Z.modelOps.get(P)?.delete(S);Z.personTerminals.delete(S),E()}}async function vJ($,X){let K=$.claim.attempt_id;if(Z.turns.get(K)===$)Z.turns.delete(K);J.onTurn?.(K,null),a($);let G=await m(Z,J.agent,K);Z.receipts.push({turn:$,failure:X,unbound:G}),await $J()}function $J(){return ZJ=ZJ.then(jJ,jJ),ZJ}async function jJ(){while(Z.receipts.length){let{turn:$,failure:X,unbound:K}=Z.receipts[0],{complete:G,emit:U}=T($);try{if(await U("hands.stopped",{...$.readyData,reason_code:X?"failed":"cancelled",killed_verified:K.killed_verified,shredded:K.shredded,...K.srt_fallbacks?{vm_hands_srt_fallbacks:K.srt_fallbacks}:{}}),X)await G("failed",{error_code:X});else await G("cancelled",{error_code:"driver_stopped"})}catch(C){if(C instanceof g)return}Z.receipts.shift()}}async function yJ($,X){let{fence:K,op:G}=T($),U=X.snapshot_id;if(X.version!==1||typeof U!=="string"||Object.keys(X).length!==2)throw new W("vm_hands_env_invalid","invalid environment delivery");let C=await H(`/operations/${G}/environment`,{...K,snapshot_id:U}),L=C.json?.environment_sealed;if(C.status!==200||!L||C.json?.payload!==void 0)throw new W("vm_hands_env_invalid","environment not delivered sealed");let F=await J.agent.deliverEnvironment({attemptId:$.claim.attempt_id,snapshotId:U,deviceId:Z.deviceId??"",sealed:L});if((await H(`/operations/${G}/environment-ack`,{...K,...F})).status>=300)throw new W("vm_hands_env_ack_refused","environment ack refused")}}
5
5
  export{jZ as xa,lJ as ya,NZ as za};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Pj as W}from"./vm-hands-entry-lite-k7fkfytm.js";var T=W.string().max(201).regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/).refine((Q)=>Q.split("/").every((Z)=>Z!=="."&&Z!=="..")),G=W.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_./-]*$/).refine((Q)=>!Q.includes("..")&&!Q.includes("//")&&!Q.endsWith("/")&&!Q.endsWith(".lock")),M=W.string().regex(/^[a-f0-9]{40}$/),q=W.number().int().positive(),C=W.string().min(1).max(256),A=W.string().max(60000),B={version:W.literal(1),repoFullName:T},J=W.array(W.string().max(1024).regex(/^(?:Co-authored-by: [^<>\r\n\x00]+ <[^<>\s]+@[^<>\s]+>|Reason-Contributor-ID: rc_[a-f0-9]{32})$/)).max(1000),c=W.strictObject({expectedTrailers:J,missingFromHead:J}),y=W.discriminatedUnion("action",[W.strictObject({action:W.literal("edit"),title:C.optional(),body:A.optional(),base:G.optional()}),W.strictObject({action:W.enum(["ready","draft","close"])}),W.strictObject({action:W.literal("metadata"),field:W.enum(["reviewer","assignee","label"]),change:W.enum(["add","remove"]),value:W.string().min(1).max(100).refine((Q)=>!/[\r\n\0]/.test(Q))})]),d=W.discriminatedUnion("kind",[W.strictObject({...B,kind:W.literal("read"),path:W.string().min(1).max(2048),accept:W.enum(["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"]).optional()}),W.strictObject({...B,kind:W.literal("pr_review_context"),number:q,after:W.string().min(1).max(1024).optional()}),W.strictObject({...B,kind:W.literal("prepare"),branch:G,baseSha:M,defaultBranch:G,diagnosticsVersion:W.literal(1).optional()}),W.strictObject({...B,kind:W.literal("publish"),branch:G,defaultBranch:G,baseSha:M,remoteHeadSha:M.nullable(),contributorTrailers:J.optional()}),W.strictObject({...B,kind:W.literal("pr_create"),head:G,base:G,title:C,body:A,draft:W.boolean()}),W.strictObject({...B,kind:W.literal("pr_mutation"),number:q,mutation:y}),W.strictObject({...B,kind:W.literal("pr_merge"),number:q,expectedHeadSha:M,expectedBaseRef:G,method:W.enum(["merge","squash","rebase"]),commitBody:W.string().max(65536).optional()})]),O=["local_device_gh_prepare_setup","local_device_gh_prepare_metadata","local_device_gh_prepare_private_init","local_device_gh_prepare_fetch","local_device_gh_prepare_base_mismatch","local_device_gh_prepare_checkout_validation","local_device_gh_prepare_checkout_init","local_device_gh_prepare_materialization"];function h(Q){return O.some((Z)=>Z===Q)}class R extends Error{code;constructor(Q){super(Q);this.code=Q}}function ZQ(Q,Z,$){let z=d.safeParse(Q);return Z==="failed"&&z.success&&z.data.kind==="prepare"&&z.data.diagnosticsVersion===1&&h($)}var x=245760,$Q=W.discriminatedUnion("kind",[W.strictObject({kind:W.literal("pr_review_context"),body:W.string().max(x)}),W.strictObject({kind:W.literal("prepare"),headSha:M}),W.strictObject({kind:W.literal("read"),status:W.number().int().min(200).max(599),headers:W.record(W.string(),W.string().max(8192)).refine((Q)=>Object.keys(Q).every((Z)=>Z==="link"||Z==="content-type")),body:W.string().max(x)}),W.strictObject({kind:W.literal("publish"),headSha:M,scannedObjectCount:W.number().int().min(0).max(5000),attribution:c.optional()}),W.strictObject({kind:W.literal("pr_create"),url:W.string().max(1024).regex(/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/)}),W.strictObject({kind:W.literal("pr_mutation"),number:q,applied:W.literal(!0)}),W.strictObject({kind:W.literal("pr_merge"),number:q,merged:W.literal(!0)})]).refine((Q)=>new TextEncoder().encode(JSON.stringify(Q)).byteLength<=x,"local_device_gh_result_too_large"),r=W.strictObject({source:W.enum(["agent","human"]),operationId:W.uuid()}),m=W.strictObject({version:W.literal(1),userId:W.guid(),deviceId:W.guid(),rootId:W.guid(),runId:W.guid(),merge:r.optional(),contributorRefresh:W.guid().optional(),repoFullName:T.nullable(),rootRevision:W.string().regex(/^[1-9][0-9]*$/),readOnly:W.boolean(),generation:W.number().int().positive().nullable(),fenceId:W.guid().nullable()}).refine((Q)=>Q.generation===null===(Q.fenceId===null));function P(Q){return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(Q)&&Q.split("/").every((Z)=>Z!=="."&&Z!=="..")}function KQ(Q,Z,$={},z="read"){if(P(Q)&&(Z==="/search/issues"||Z.startsWith("/search/issues?")))return p(Q,Z,$);if(!P(Q)||!Z.startsWith(`/repos/${Q}/`)&&Z!==`/repos/${Q}`)throw Error("local_device_gh_repository_mismatch");if(/[\\#\u0000-\u001f]/.test(Z)||/%(?:2e|5c|00)/i.test(Z))throw Error("local_device_gh_path_denied");let V=new URL(Z,"https://api.github.com");if(V.pathname!==Z.split("?")[0]||V.username||V.password)throw Error("local_device_gh_path_denied");let Y;try{Y=decodeURIComponent(V.pathname.slice(`/repos/${Q}`.length))}catch{throw Error("local_device_gh_path_denied")}if(Y.includes("%")||Y.split("/").some((D)=>D==="."||D===".."))throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");if(![/^$/,/^\/commits$/,/^\/pulls$/,/^\/pulls\/[1-9][0-9]*(?:\/(?:commits|files|reviews|comments))?$/,/^\/issues\/[1-9][0-9]*(?:\/comments)?$/,/^\/issues\/comments\/[1-9][0-9]*\/reactions$/,/^\/commits\/[A-Za-z0-9_./-]+(?:\/(?:check-runs|status))?$/,/^\/check-runs\/[1-9][0-9]*(?:\/annotations)?$/,/^\/branches\/[A-Za-z0-9_./-]+$/,/^\/git\/ref\/heads\/[A-Za-z0-9_./-]+$/,/^\/compare\/[A-Za-z0-9_./-]+\.\.\.[A-Za-z0-9_./-]+$/].some((D)=>D.test(Y)))throw Error("local_device_gh_path_denied");if(V.searchParams.forEach((D,X)=>{if(X==="per_page"&&/^[1-9][0-9]*$/.test(D)&&Number(D)<=100)return;if(X==="page"&&/^[1-9][0-9]*$/.test(D)&&Number(D)<=100)return;if(Y==="/pulls"&&X==="state"&&["open","closed","all"].includes(D))return;if(Y==="/pulls"&&X==="sort"&&D==="updated")return;if(Y==="/pulls"&&X==="direction"&&D==="desc")return;if(Y==="/pulls"&&["head","base"].includes(X)&&/^[A-Za-z0-9_./:-]{1,255}$/.test(D))return;throw Error("local_device_gh_query_denied")}),$.headers)new Headers($.headers).forEach((X,_)=>{if(_!=="accept"||!["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"].includes(X))throw Error("local_device_gh_header_denied")})}function p(Q,Z,$){if(/[\\#\u0000-\u001f]/.test(Z))throw Error("local_device_gh_path_denied");let z=new URL(Z,"https://api.github.com");if(z.pathname!=="/search/issues"||z.username||z.password)throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");let V=null;z.searchParams.forEach((H,D)=>{if(D==="q"&&V===null){V=H;return}if(D==="per_page"&&/^[1-9][0-9]*$/.test(H)&&Number(H)<=100)return;if(D==="page"&&/^[1-9][0-9]*$/.test(H)&&Number(H)<=100)return;throw Error("local_device_gh_query_denied")});let Y=`repo:${Q.toLowerCase()} `,N=V?.toLowerCase()??"";if(N.length>512||!(N+" ").startsWith(Y)||/(?:^|\s)(?:repo|org|user):/.test(N.slice(Y.length)))throw Error("local_device_gh_query_denied");if($.headers)new Headers($.headers).forEach((H,D)=>{if(D!=="accept"||H!=="application/vnd.github+json")throw Error("local_device_gh_header_denied")})}var DQ=`query PullRequestReviewContext($owner: String!, $repo: String!, $number: Int!, $after: String) {
2
+ import{Qj as W}from"./vm-hands-entry-lite-hzsk6tpw.js";var T=W.string().max(201).regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/).refine((Q)=>Q.split("/").every((Z)=>Z!=="."&&Z!=="..")),G=W.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_./-]*$/).refine((Q)=>!Q.includes("..")&&!Q.includes("//")&&!Q.endsWith("/")&&!Q.endsWith(".lock")),M=W.string().regex(/^[a-f0-9]{40}$/),q=W.number().int().positive(),C=W.string().min(1).max(256),A=W.string().max(60000),B={version:W.literal(1),repoFullName:T},J=W.array(W.string().max(1024).regex(/^(?:Co-authored-by: [^<>\r\n\x00]+ <[^<>\s]+@[^<>\s]+>|Reason-Contributor-ID: rc_[a-f0-9]{32})$/)).max(1000),c=W.strictObject({expectedTrailers:J,missingFromHead:J}),y=W.discriminatedUnion("action",[W.strictObject({action:W.literal("edit"),title:C.optional(),body:A.optional(),base:G.optional()}),W.strictObject({action:W.enum(["ready","draft","close"])}),W.strictObject({action:W.literal("metadata"),field:W.enum(["reviewer","assignee","label"]),change:W.enum(["add","remove"]),value:W.string().min(1).max(100).refine((Q)=>!/[\r\n\0]/.test(Q))})]),d=W.discriminatedUnion("kind",[W.strictObject({...B,kind:W.literal("read"),path:W.string().min(1).max(2048),accept:W.enum(["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"]).optional()}),W.strictObject({...B,kind:W.literal("pr_review_context"),number:q,after:W.string().min(1).max(1024).optional()}),W.strictObject({...B,kind:W.literal("prepare"),branch:G,baseSha:M,defaultBranch:G,diagnosticsVersion:W.literal(1).optional()}),W.strictObject({...B,kind:W.literal("publish"),branch:G,defaultBranch:G,baseSha:M,remoteHeadSha:M.nullable(),contributorTrailers:J.optional()}),W.strictObject({...B,kind:W.literal("pr_create"),head:G,base:G,title:C,body:A,draft:W.boolean()}),W.strictObject({...B,kind:W.literal("pr_mutation"),number:q,mutation:y}),W.strictObject({...B,kind:W.literal("pr_merge"),number:q,expectedHeadSha:M,expectedBaseRef:G,method:W.enum(["merge","squash","rebase"]),commitBody:W.string().max(65536).optional()})]),O=["local_device_gh_prepare_setup","local_device_gh_prepare_metadata","local_device_gh_prepare_private_init","local_device_gh_prepare_fetch","local_device_gh_prepare_base_mismatch","local_device_gh_prepare_checkout_validation","local_device_gh_prepare_checkout_init","local_device_gh_prepare_materialization"];function h(Q){return O.some((Z)=>Z===Q)}class R extends Error{code;constructor(Q){super(Q);this.code=Q}}function ZQ(Q,Z,$){let z=d.safeParse(Q);return Z==="failed"&&z.success&&z.data.kind==="prepare"&&z.data.diagnosticsVersion===1&&h($)}var x=245760,$Q=W.discriminatedUnion("kind",[W.strictObject({kind:W.literal("pr_review_context"),body:W.string().max(x)}),W.strictObject({kind:W.literal("prepare"),headSha:M}),W.strictObject({kind:W.literal("read"),status:W.number().int().min(200).max(599),headers:W.record(W.string(),W.string().max(8192)).refine((Q)=>Object.keys(Q).every((Z)=>Z==="link"||Z==="content-type")),body:W.string().max(x)}),W.strictObject({kind:W.literal("publish"),headSha:M,scannedObjectCount:W.number().int().min(0).max(5000),attribution:c.optional()}),W.strictObject({kind:W.literal("pr_create"),url:W.string().max(1024).regex(/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/)}),W.strictObject({kind:W.literal("pr_mutation"),number:q,applied:W.literal(!0)}),W.strictObject({kind:W.literal("pr_merge"),number:q,merged:W.literal(!0)})]).refine((Q)=>new TextEncoder().encode(JSON.stringify(Q)).byteLength<=x,"local_device_gh_result_too_large"),r=W.strictObject({source:W.enum(["agent","human"]),operationId:W.uuid()}),m=W.strictObject({version:W.literal(1),userId:W.guid(),deviceId:W.guid(),rootId:W.guid(),runId:W.guid(),merge:r.optional(),contributorRefresh:W.guid().optional(),repoFullName:T.nullable(),rootRevision:W.string().regex(/^[1-9][0-9]*$/),readOnly:W.boolean(),generation:W.number().int().positive().nullable(),fenceId:W.guid().nullable()}).refine((Q)=>Q.generation===null===(Q.fenceId===null));function P(Q){return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(Q)&&Q.split("/").every((Z)=>Z!=="."&&Z!=="..")}function KQ(Q,Z,$={},z="read"){if(P(Q)&&(Z==="/search/issues"||Z.startsWith("/search/issues?")))return p(Q,Z,$);if(!P(Q)||!Z.startsWith(`/repos/${Q}/`)&&Z!==`/repos/${Q}`)throw Error("local_device_gh_repository_mismatch");if(/[\\#\u0000-\u001f]/.test(Z)||/%(?:2e|5c|00)/i.test(Z))throw Error("local_device_gh_path_denied");let V=new URL(Z,"https://api.github.com");if(V.pathname!==Z.split("?")[0]||V.username||V.password)throw Error("local_device_gh_path_denied");let Y;try{Y=decodeURIComponent(V.pathname.slice(`/repos/${Q}`.length))}catch{throw Error("local_device_gh_path_denied")}if(Y.includes("%")||Y.split("/").some((D)=>D==="."||D===".."))throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");if(![/^$/,/^\/commits$/,/^\/pulls$/,/^\/pulls\/[1-9][0-9]*(?:\/(?:commits|files|reviews|comments))?$/,/^\/issues\/[1-9][0-9]*(?:\/comments)?$/,/^\/issues\/comments\/[1-9][0-9]*\/reactions$/,/^\/commits\/[A-Za-z0-9_./-]+(?:\/(?:check-runs|status))?$/,/^\/check-runs\/[1-9][0-9]*(?:\/annotations)?$/,/^\/branches\/[A-Za-z0-9_./-]+$/,/^\/git\/ref\/heads\/[A-Za-z0-9_./-]+$/,/^\/compare\/[A-Za-z0-9_./-]+\.\.\.[A-Za-z0-9_./-]+$/].some((D)=>D.test(Y)))throw Error("local_device_gh_path_denied");if(V.searchParams.forEach((D,X)=>{if(X==="per_page"&&/^[1-9][0-9]*$/.test(D)&&Number(D)<=100)return;if(X==="page"&&/^[1-9][0-9]*$/.test(D)&&Number(D)<=100)return;if(Y==="/pulls"&&X==="state"&&["open","closed","all"].includes(D))return;if(Y==="/pulls"&&X==="sort"&&D==="updated")return;if(Y==="/pulls"&&X==="direction"&&D==="desc")return;if(Y==="/pulls"&&["head","base"].includes(X)&&/^[A-Za-z0-9_./:-]{1,255}$/.test(D))return;throw Error("local_device_gh_query_denied")}),$.headers)new Headers($.headers).forEach((X,_)=>{if(_!=="accept"||!["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"].includes(X))throw Error("local_device_gh_header_denied")})}function p(Q,Z,$){if(/[\\#\u0000-\u001f]/.test(Z))throw Error("local_device_gh_path_denied");let z=new URL(Z,"https://api.github.com");if(z.pathname!=="/search/issues"||z.username||z.password)throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");let V=null;z.searchParams.forEach((H,D)=>{if(D==="q"&&V===null){V=H;return}if(D==="per_page"&&/^[1-9][0-9]*$/.test(H)&&Number(H)<=100)return;if(D==="page"&&/^[1-9][0-9]*$/.test(H)&&Number(H)<=100)return;throw Error("local_device_gh_query_denied")});let Y=`repo:${Q.toLowerCase()} `,N=V?.toLowerCase()??"";if(N.length>512||!(N+" ").startsWith(Y)||/(?:^|\s)(?:repo|org|user):/.test(N.slice(Y.length)))throw Error("local_device_gh_query_denied");if($.headers)new Headers($.headers).forEach((H,D)=>{if(D!=="accept"||H!=="application/vnd.github+json")throw Error("local_device_gh_header_denied")})}var DQ=`query PullRequestReviewContext($owner: String!, $repo: String!, $number: Int!, $after: String) {
3
3
  repository(owner: $owner, name: $repo) {
4
4
  nameWithOwner
5
5
  pullRequest(number: $number) {
@@ -39,4 +39,4 @@ import{Pj as W}from"./vm-hands-entry-lite-k7fkfytm.js";var T=W.string().max(201)
39
39
  `)||!/^[a-f0-9]{64}$/.test(Q.bodySha256))throw Error("Invalid Reason Device proof input.");return Buffer.from([Z,$,Q.pathAndQuery,Q.timestamp,Q.nonce,Q.challenge,Q.bodySha256].join(`
40
40
  `),"utf8")}function K(Q){return Boolean(Q)&&typeof Q==="object"&&!Array.isArray(Q)}function t(Q,Z){return typeof Q==="string"&&Z.some(($)=>$===Q)}function k(Q){return K(Q)&&typeof Q.id==="string"&&typeof Q.label==="string"&&typeof Q.path_fingerprint==="string"}function v(Q){return K(Q)&&Number.isInteger(Q.seq)&&Number(Q.seq)>=0&&typeof Q.kind==="string"&&/^[A-Za-z0-9._:-]{1,64}$/.test(Q.kind)&&K(Q.payload)}function w(Q){throw Error(Q)}function QW(Q,Z){let $=K(Q)?Q:{},z=typeof $.error==="string"?$.error:`http_${Z}`,V=typeof $.detail==="string"?$.detail:typeof $.message==="string"?$.message:`Reason Device request failed (${Z})`;return{code:z,message:V}}function l(Q){if(!K(Q)||typeof Q.challenge!=="string"||Q.challenge.length<16||Q.challenge.length>1024||Q.challenge.includes(`
41
41
  `)||typeof Q.expires_at!=="string"||!Number.isFinite(Date.parse(Q.expires_at)))w("Reason returned an invalid Device proof challenge.");return{challenge:Q.challenge,expires_at:Q.expires_at}}function L(Q,Z){if(!K(Q)||typeof Q.device_id!=="string"||Q.auth_scheme!=="p256"||Q.organization_id!==void 0&&typeof Q.organization_id!=="string"||Q.protocol_version!==j||!Array.isArray(Q.roots)||!Q.roots.every(k)||Z&&typeof Q.organization_id!=="string"||Q.device_credential!==void 0)w(Z?"Reason returned an invalid Device enrollment.":"Reason returned an invalid Device registration.");return{...{device_id:Q.device_id,...typeof Q.organization_id==="string"?{organization_id:Q.organization_id}:{},protocol_version:j,roots:Q.roots},auth_scheme:"p256"}}function WW(Q){return L(Q,!1)}function ZW(Q){let Z=L(Q,!0);if(typeof Z.organization_id!=="string")return w("Reason returned an invalid Device enrollment.");return{...Z,organization_id:Z.organization_id}}function $W(Q){if(!K(Q)||typeof Q.server_time!=="string"||typeof Q.drain!=="boolean")return w("Reason returned an invalid Device heartbeat.");return{server_time:Q.server_time,drain:Q.drain,...f(Q),...typeof Q.update_policy==="string"||Q.update_policy===null?{update_policy:Q.update_policy}:{},...typeof Q.supported_protocol_version==="number"?{supported_protocol_version:Q.supported_protocol_version}:{},...a(Q.latest_cli_versions),...Q.hands_prespawn===!0?{hands_prespawn:!0}:{}}}var u=["account_root_metadata_supported","workspace_root_metadata_supported","account_root_path_supported","home_contained_roots_supported","root_paths_supported","startup_supported"];function f(Q){return Object.fromEntries(u.filter((Z)=>Q[Z]===!0).map((Z)=>[Z,!0]))}function KW(Q){if(!K(Q))return;try{return{...l(Q),...f(Q)}}catch{return}}function a(Q){if(!K(Q))return{};let Z={};for(let $ of s){let z=Q[$];if(typeof z==="string"&&/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/.test(z))Z[$]=z}return Object.keys(Z).length>0?{latest_cli_versions:Z}:{}}function DW(Q){if(!K(Q)||!Array.isArray(Q.roots)||!Q.roots.every(k))return w("Reason returned an invalid Device root sync.");return{roots:Q.roots}}function zW(Q){if(!K(Q)||Q.user_id!==void 0&&typeof Q.user_id!=="string"||typeof Q.organization_id!=="string"||typeof Q.organization_name!=="string"||typeof Q.organization_slug!=="string")return w("Reason returned an invalid Device identity.");return{...typeof Q.user_id==="string"?{user_id:Q.user_id}:{},organization_id:Q.organization_id,organization_name:Q.organization_name,organization_slug:Q.organization_slug}}function FW(Q){if(!K(Q)||Q.disconnected!==!0)return w("Reason did not disconnect this Device.");let Z=Q.sessions_moved;return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=0?{disconnected:!0,sessions_moved:Z}:{disconnected:!0}}function wW(Q){if(K(Q)&&Q.ok===!0&&typeof Q.expires==="number")return{ok:!0,expires:Q.expires};if(K(Q)&&Q.ok===!1&&typeof Q.error==="string")return{ok:!1,error:Q.error};return w("Reason did not answer the local login hand-over.")}function VW(Q){if(!K(Q)||Q.accepted!==!0)return w("Reason did not accept the Device lifecycle event.");return{accepted:!0}}function e(Q){return Buffer.byteLength(JSON.stringify(Q),"utf8")}function YW(Q,Z=b){if(!K(Q)||typeof Q.operation_id!=="string"||typeof Q.attempt_id!=="string"||typeof Q.attempt_token!=="string"||!/^(?:reason|ara)_attempt_/.test(Q.attempt_token)||typeof Q.lease_until!=="string"||typeof Q.run_id!=="string"||typeof Q.root_id!=="string"||Q.owner!==void 0&&!E(Q.owner)||!t(Q.capability,Z)||!K(Q.payload)||Q.protocol_version!==j||e(Q.payload)>n||Q.authority!==void 0&&!U(Q.authority)||Q.local_github_authority!==void 0&&!m.safeParse(Q.local_github_authority).success||Q.capability==="github.local.v1"&&!m.safeParse(Q.local_github_authority).success||Q.recording_authority!==void 0&&!S(Q.recording_authority)||Q.capability==="browser.recording.v1"&&(!S(Q.recording_authority)||!E(Q.owner))||Q.capability!=="browser.recording.v1"&&Q.recording_authority!==void 0)return w("Reason returned an invalid Device operation claim.");let $={operation_id:Q.operation_id,attempt_id:Q.attempt_id,attempt_token:Q.attempt_token,lease_until:Q.lease_until,run_id:Q.run_id,root_id:Q.root_id,capability:Q.capability,payload:Q.payload,...U(Q.authority)?{authority:Q.authority}:{},...S(Q.recording_authority)?{recording_authority:Object.freeze({...Q.recording_authority})}:{},...Q.local_github_authority!==void 0?{local_github_authority:m.parse(Q.local_github_authority)}:{},...Q.capability==="hands.connect"&&K(Q.environment)&&K(Q.environment.payload)&&U(Q.environment.authority)?{environment:{payload:Q.environment.payload,authority:Q.environment.authority}}:{},protocol_version:j};if(Q.owner!==void 0)$.owner=Object.freeze({...Q.owner});return $}function HW(Q){if(!K(Q)||typeof Q.lease_until!=="string"||!Array.isArray(Q.controls)||!Q.controls.every(v)||!Number.isInteger(Q.next_control_seq)||Number(Q.next_control_seq)<0)return w("Reason returned an invalid Device operation heartbeat.");return{lease_until:Q.lease_until,controls:Q.controls,next_control_seq:Number(Q.next_control_seq)}}function XW(Q){if(!K(Q)||!Number.isInteger(Q.next_event_seq)||Number(Q.next_event_seq)<0||typeof Q.duplicate!=="boolean"||!Number.isInteger(Q.accepted_count)||Number(Q.accepted_count)<0)return w("Reason returned an invalid Device operation event result.");return{next_event_seq:Number(Q.next_event_seq),duplicate:Q.duplicate,accepted_count:Number(Q.accepted_count)}}function GW(Q){if(!K(Q)||!K(Q.payload)||!U(Q.authority))return w("Reason returned an invalid Device environment delivery.");return{payload:Q.payload,authority:Q.authority}}function QQ(Q){return Q==="succeeded"||Q==="failed"||Q==="cancelled"||Q==="expired"}function BW(Q){if(!K(Q)||!QQ(Q.status)||typeof Q.idempotent!=="boolean")return w("Reason returned an invalid Device operation completion.");return{status:Q.status,idempotent:Q.idempotent}}
42
- export{d as oe,R as pe,ZQ as qe,x as re,$Q as se,m as te,KQ as ue,DQ as ve,zQ as we,b as xe,j as ye,I as ze,n as Ae,HQ as Be,XQ as Ce,GQ as De,BQ as Ee,MQ as Fe,gQ as Ge,qQ as He,NQ as Ie,mQ as Je,UQ as Ke,jQ as Le,xQ as Me,JQ as Ne,SQ as Oe,IQ as Pe,PQ as Qe,TQ as Re,CQ as Se,AQ as Te,bQ as Ue,EQ as Ve,kQ as We,LQ as Xe,fQ as Ye,_Q as Ze,cQ as _e,yQ as $e,dQ as af,OQ as bf,hQ as cf,RQ as df,rQ as ef,pQ as ff,nQ as gf,oQ as hf,sQ as if,iQ as jf,tQ as kf,vQ as lf,lQ as mf,uQ as nf,i as of,aQ as pf,eQ as qf,QW as rf,l as sf,WW as tf,ZW as uf,$W as vf,KW as wf,DW as xf,zW as yf,FW as zf,wW as Af,VW as Bf,YW as Cf,HW as Df,XW as Ef,GW as Ff,BW as Gf};
42
+ export{d as pe,R as qe,ZQ as re,x as se,$Q as te,m as ue,KQ as ve,DQ as we,zQ as xe,b as ye,j as ze,I as Ae,n as Be,HQ as Ce,XQ as De,GQ as Ee,BQ as Fe,MQ as Ge,gQ as He,qQ as Ie,NQ as Je,mQ as Ke,UQ as Le,jQ as Me,xQ as Ne,JQ as Oe,SQ as Pe,IQ as Qe,PQ as Re,TQ as Se,CQ as Te,AQ as Ue,bQ as Ve,EQ as We,kQ as Xe,LQ as Ye,fQ as Ze,_Q as _e,cQ as $e,yQ as af,dQ as bf,OQ as cf,hQ as df,RQ as ef,rQ as ff,pQ as gf,nQ as hf,oQ as if,sQ as jf,iQ as kf,tQ as lf,vQ as mf,lQ as nf,uQ as of,i as pf,aQ as qf,eQ as rf,QW as sf,l as tf,WW as uf,ZW as vf,$W as wf,KW as xf,DW as yf,zW as zf,FW as Af,wW as Bf,VW as Cf,YW as Df,HW as Ef,XW as Ff,GW as Gf,BW as Hf};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{de as p,fe as V,ie as f}from"./vm-hands-entry-lite-cety9pka.js";import{_h as E}from"./vm-hands-entry-lite-p1nb6n3r.js";import{oi as y}from"./vm-hands-entry-lite-4xfs7y6w.js";import{Bi as m,Pi as w,Ri as u}from"./vm-hands-entry-lite-0p3438xe.js";import{spawnSync as F}from"child_process";import{createHash as e,randomUUID as zz}from"crypto";import{chmodSync as Hz,existsSync as P,mkdirSync as Jz,readdirSync as Mz,readFileSync as L,renameSync as Qz,rmSync as T,statSync as Zz,writeFileSync as $z}from"fs";import{dirname as Bz,isAbsolute as v,join as A}from"path";var W="REASON_WORKER_SERVICE",jz="worker_identity_unavailable";function Iz(H){return{platform:process.platform,home:H,uid:process.getuid?.(),command:(z,M)=>F(z,[...M],{stdio:"ignore"}).status??1,read:(z,M)=>{let J=F(z,[...M],{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4});return J.status===0?J.stdout:null},sleep:(z)=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,z),workerIdentity:(z)=>u(H,z),insideService:(z)=>qz(z,process.platform,process.getuid?.())}}function qz(H,z,M){if(process.env[W]===H||process.env.XPC_SERVICE_NAME===H)return!0;if(z==="linux")try{return L("/proc/self/cgroup","utf8").includes(`/${H}.service`)}catch{return!0}if(z!=="darwin")return!1;if(typeof M!=="number")return!0;let J=F("/bin/launchctl",["print",`gui/${M}/${H}`],{encoding:"utf8",timeout:5000});if(J.status===Tz)return!1;if(J.error||J.status!==0)return!0;let Q=Number(/^\s*pid = (\d+)$/m.exec(J.stdout??"")?.[1]??0);if(!Q)return!1;let Z=process.pid;for(let B=0;B<64&&Z>1;B+=1){if(Z===Q)return!0;let $=F("/bin/ps",["-o","ppid=","-p",String(Z)],{encoding:"utf8",timeout:5000}),j=Number($.stdout?.trim());if($.error||$.status!==0||!Number.isSafeInteger(j)||j<=0)return!0;if(j===Z)return!1;Z=j}return Z>1}var Tz=113;class q extends Error{code;constructor(H,z){super(H);this.code=z}}function bz(H,z){if(H.platform!=="darwin"&&H.platform!=="linux")throw new q("A background service needs macOS (launchd) or Linux (systemd --user).");if(H.platform==="darwin")U(H);let J=[f(p(z,H.home))?.owned_paths.find((Q)=>Q.role==="launcher")?.path,y(z,"REASON_CLI_LAUNCHER_PATH")?.trim(),A(H.home,".local","bin",E({env:z})==="staging"?"ara-staging":"ara")];for(let Q of J)try{if(Q&&v(Q)&&Zz(Q).isFile())return V(Q)}catch{}throw new q("A background service runs the installed Reason launcher, which was not found. Install Reason with: curl -fsSL https://reasonmachines.com/install | sh","worker_launcher_missing")}var I=/(<key>ProgramArguments<\/key>\s*<array>\n)((?:\s*<string>[^<]*<\/string>\n)*)(\s*<\/array>)/,X=new RegExp(`(\\n\\s*<key>${w}</key>\\s*<string>)[^<]*(</string>)`),Gz=/(<key>EnvironmentVariables<\/key>\s*<dict>[\s\S]*?)(\n\s*<\/dict>)/;function Yz(H){return H.replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&amp;","&")}function b(H){let z=[...(I.exec(H)?.[2]??"").matchAll(/<string>([^<]*)<\/string>/g)].map((J)=>Yz(J[1])),M=z[1]==="--run-worker"?z.slice(2):z;return M[0]?{launcher:M[0],args:M.slice(1)}:null}function Sz(H,z){if(!Az(z))return null;try{return b(L(A(H,"Library","LaunchAgents",`${z}.plist`),"utf8"))?.launcher??null}catch{return null}}function d(H,z,M){let J=M.workerIdentity?.(H)??null;return{program:J?[J.executable,"--run-worker",H,...z]:[H,...z],identity:J}}function S(H){return H.map((z)=>` <string>${G(z)}</string>`).join(`
2
+ import{ee as p,ge as V,je as f}from"./vm-hands-entry-lite-7jhh57qs.js";import{$h as E}from"./vm-hands-entry-lite-jd49j573.js";import{pi as y}from"./vm-hands-entry-lite-1mrkcz0p.js";import{Ci as m,Qi as w,Si as u}from"./vm-hands-entry-lite-gs8cpdfw.js";import{spawnSync as F}from"child_process";import{createHash as e,randomUUID as zz}from"crypto";import{chmodSync as Hz,existsSync as P,mkdirSync as Jz,readdirSync as Mz,readFileSync as L,renameSync as Qz,rmSync as T,statSync as Zz,writeFileSync as $z}from"fs";import{dirname as Bz,isAbsolute as v,join as A}from"path";var W="REASON_WORKER_SERVICE",jz="worker_identity_unavailable";function Iz(H){return{platform:process.platform,home:H,uid:process.getuid?.(),command:(z,M)=>F(z,[...M],{stdio:"ignore"}).status??1,read:(z,M)=>{let J=F(z,[...M],{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4});return J.status===0?J.stdout:null},sleep:(z)=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,z),workerIdentity:(z)=>u(H,z),insideService:(z)=>qz(z,process.platform,process.getuid?.())}}function qz(H,z,M){if(process.env[W]===H||process.env.XPC_SERVICE_NAME===H)return!0;if(z==="linux")try{return L("/proc/self/cgroup","utf8").includes(`/${H}.service`)}catch{return!0}if(z!=="darwin")return!1;if(typeof M!=="number")return!0;let J=F("/bin/launchctl",["print",`gui/${M}/${H}`],{encoding:"utf8",timeout:5000});if(J.status===Tz)return!1;if(J.error||J.status!==0)return!0;let Q=Number(/^\s*pid = (\d+)$/m.exec(J.stdout??"")?.[1]??0);if(!Q)return!1;let Z=process.pid;for(let B=0;B<64&&Z>1;B+=1){if(Z===Q)return!0;let $=F("/bin/ps",["-o","ppid=","-p",String(Z)],{encoding:"utf8",timeout:5000}),j=Number($.stdout?.trim());if($.error||$.status!==0||!Number.isSafeInteger(j)||j<=0)return!0;if(j===Z)return!1;Z=j}return Z>1}var Tz=113;class q extends Error{code;constructor(H,z){super(H);this.code=z}}function bz(H,z){if(H.platform!=="darwin"&&H.platform!=="linux")throw new q("A background service needs macOS (launchd) or Linux (systemd --user).");if(H.platform==="darwin")U(H);let J=[f(p(z,H.home))?.owned_paths.find((Q)=>Q.role==="launcher")?.path,y(z,"REASON_CLI_LAUNCHER_PATH")?.trim(),A(H.home,".local","bin",E({env:z})==="staging"?"ara-staging":"ara")];for(let Q of J)try{if(Q&&v(Q)&&Zz(Q).isFile())return V(Q)}catch{}throw new q("A background service runs the installed Reason launcher, which was not found. Install Reason with: curl -fsSL https://reasonmachines.com/install | sh","worker_launcher_missing")}var I=/(<key>ProgramArguments<\/key>\s*<array>\n)((?:\s*<string>[^<]*<\/string>\n)*)(\s*<\/array>)/,X=new RegExp(`(\\n\\s*<key>${w}</key>\\s*<string>)[^<]*(</string>)`),Gz=/(<key>EnvironmentVariables<\/key>\s*<dict>[\s\S]*?)(\n\s*<\/dict>)/;function Yz(H){return H.replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&amp;","&")}function b(H){let z=[...(I.exec(H)?.[2]??"").matchAll(/<string>([^<]*)<\/string>/g)].map((J)=>Yz(J[1])),M=z[1]==="--run-worker"?z.slice(2):z;return M[0]?{launcher:M[0],args:M.slice(1)}:null}function Sz(H,z){if(!Az(z))return null;try{return b(L(A(H,"Library","LaunchAgents",`${z}.plist`),"utf8"))?.launcher??null}catch{return null}}function d(H,z,M){let J=M.workerIdentity?.(H)??null;return{program:J?[J.executable,"--run-worker",H,...z]:[H,...z],identity:J}}function S(H){return H.map((z)=>` <string>${G(z)}</string>`).join(`
3
3
  `)}function g(H,z){let M;try{M=L(H,"utf8")}catch{return null}let J=b(M);if(!J)return null;let Q=v(J.launcher)?V(J.launcher):J.launcher,{program:Z,identity:B}=d(Q,J.args,z),$=M.replace(I,(j,Y,N,R)=>`${Y}${S(Z)}
4
4
  ${R}`);if(!B)$=$.replace(X,"");else if(X.test($))$=$.replace(X,(j,Y,N)=>`${Y}${G(B.app)}${N}`);else $=$.replace(Gz,(j,Y,N)=>`${Y}
5
5
  <key>${w}</key>
@@ -59,4 +59,4 @@ UMask=0077
59
59
  [Install]
60
60
  WantedBy=default.target
61
61
  `}function C(H,z){Jz(Bz(H),{recursive:!0,mode:448});let M=`${H}.${zz()}.tmp`;try{$z(M,z,{mode:384,flag:"wx"}),Hz(M,384),Qz(M,H)}finally{T(M,{force:!0})}}function U(H){if(typeof H.uid!=="number"||!Number.isSafeInteger(H.uid)||H.uid<=0)throw new q("Set up a background service as your own user, not with sudo.","worker_service_root_user");return`gui/${H.uid}`}function Ez(H){let{config:z,launcher:M,host:J}=H,Q=H.kind??"serve",Z=c(z,J,Q),B=Z!==null&&J.insideService?.(Z.label)===!0,$=D(z,J,Q,B?_:K);if(!$)throw new q("A background service needs macOS (launchd) or Linux (systemd --user).");if(J.platform==="darwin")U(J);if(J.platform==="linux"&&J.command("systemctl",["--user","show-environment"])!==0)throw new q("No background service here: this computer has no systemd user session.","worker_service_manager_missing");let j=J.platform==="darwin"?r(z,Q,$,M,J,H.path):null;if(C($.definition,j?j.plist:s(z,Q,$,M,J.home,H.path)),i(z,J,$,B?null:Z),j)return j.identity?$:{...$,identityProblem:jz};return{...$,lingering:J.command("loginctl",["enable-linger"])===0}}function i(H,z,M,J){if(z.platform==="darwin"){let B=U(z);if(J)z.command("/bin/launchctl",["bootout",`${B}/${J.label}`]);if(t(H,M,z)){if(J)T(J.definition,{force:!0});return}if(T(M.definition,{force:!0}),J)z.command("/bin/launchctl",["bootstrap",B,J.definition]);throw new q("Could not start the background service (launchctl bootstrap failed).","worker_service_start_failed")}let Q=`${M.label}.service`,Z=J?`${J.label}.service`:null;if(z.command("systemctl",["--user","daemon-reload"])!==0||Z!==null&&z.command("systemctl",["--user","disable","--now",Z])!==0||z.command("systemctl",["--user","enable",Q])!==0||z.command("systemctl",["--user","restart",Q])!==0){if(z.command("systemctl",["--user","disable",Q]),T(M.definition,{force:!0}),z.command("systemctl",["--user","daemon-reload"]),Z)z.command("systemctl",["--user","enable","--now",Z]);throw new q("Could not start the background service (systemctl --user failed).","worker_service_start_failed")}if(J)T(J.definition,{force:!0}),z.command("systemctl",["--user","daemon-reload"])}function t(H,z,M){let J=U(M);M.command("/bin/launchctl",["bootout",`${J}/${z.label}`]);let Q=(Math.ceil(H.shutdownGraceMs/1000)+10)*1000;for(let Z=0,B=100;;B=Math.min(B*2,2000)){if(M.command("/bin/launchctl",["bootstrap",J,z.definition])===0)return!0;if(Z>=Q)return!1;M.sleep(B),Z+=B}}function mz(H,z,M){let J=x(H,z,M);if(!J)return null;let Q=z.insideService?.(J.label)===!0;if(z.platform==="darwin"&&!Q)Nz(J.definition,z);let Z=D(H,z,M);if(Z&&J.label!==Z.label&&!Q)return C(Z.definition,L(J.definition,"utf8").replaceAll(J.label,Z.label)),i(H,z,Z,J),Z;let B=z.platform==="darwin"&&Q,$;if(B)$=z.command("/bin/launchctl",["kickstart","-k",`${U(z)}/${J.label}`])===0;else if(z.platform==="darwin")$=t(H,J,z);else z.command("systemctl",["--user","enable",`${J.label}.service`]),$=z.command("systemctl",["--user","restart",`${J.label}.service`])===0;if(!$)throw new q(`Could not restart the background service ${J.label}.`,"worker_service_restart_failed");if(Z&&J.label===Z.label)Lz(H,z,M);return J}function uz(H,z,M,J){let Q=x(H,M,J),Z=D(z,M,J);if(M.platform!=="darwin"||!Q||!Z)return;let B=`<string>${G(Q.logs)}</string>`,$=L(Q.definition,"utf8");if($.includes(B))C(Q.definition,$.replaceAll(B,`<string>${G(Z.logs)}</string>`))}function pz(H,z,M="serve"){let J=h(H,z,M);for(let Q of J){if(z.platform==="darwin"){if(typeof z.uid==="number"&&z.uid>0)z.command("/bin/launchctl",["bootout",`gui/${z.uid}/${Q.label}`]);T(Q.definition,{force:!0});continue}z.command("systemctl",["--user","disable","--now",`${Q.label}.service`]),T(Q.definition,{force:!0}),z.command("systemctl",["--user","daemon-reload"])}return J[0]??null}
62
- export{W as Gd,jz as Hd,Iz as Id,q as Jd,bz as Kd,Sz as Ld,_z as Md,l as Nd,xz as Od,Rz as Pd,x as Qd,Lz as Rd,kz as Sd,yz as Td,Ez as Ud,mz as Vd,uz as Wd,pz as Xd};
62
+ export{W as Hd,jz as Id,Iz as Jd,q as Kd,bz as Ld,Sz as Md,_z as Nd,l as Od,xz as Pd,Rz as Qd,x as Rd,Lz as Sd,kz as Td,yz as Ud,Ez as Vd,mz as Wd,uz as Xd,pz as Yd};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Id as ie,Kd as oe}from"./vm-hands-entry-lite-tf1tkqkw.js";import{jf as he}from"./vm-hands-entry-lite-fr2k6eah.js";import{Hf as q,If as ee,Kf as D,Lf as ye,Of as W,Pf as z,Qf as v,Zf as T,_f as Fe}from"./vm-hands-entry-lite-t5kt2wff.js";import{Eg as ge}from"./vm-hands-entry-lite-5y2kfnv2.js";import{qi as re}from"./vm-hands-entry-lite-62x9nv6n.js";import{Mi as J}from"./vm-hands-entry-lite-0p3438xe.js";import{Si as y}from"./vm-hands-entry-lite-tbps80f1.js";import{Jj as xe,Kj as te}from"./vm-hands-entry-lite-avstvbbc.js";import{Qj as be,Wj as we}from"./vm-hands-entry-lite-jjkkee8q.js";import{Xj as f}from"./vm-hands-entry-lite-kxtjkzzh.js";import{spawn as O}from"child_process";import{randomUUID as Se}from"crypto";import{closeSync as ct,copyFileSync as ce,existsSync as G,fstatSync as lt,mkdirSync as le,openSync as ut,readdirSync as F,readFileSync as Ae,readlinkSync as dt,renameSync as ft,rmSync as mt,statSync as pt}from"fs";import{connect as _t}from"net";import{userInfo as Oe}from"os";import{basename as ue,dirname as U,join as _}from"path";var V=`import { spawn, execFileSync } from "node:child_process";
2
+ import{Jd as ie,Ld as oe}from"./vm-hands-entry-lite-d0f4kbc8.js";import{kf as he}from"./vm-hands-entry-lite-cvft83sx.js";import{$f as Fe,If as q,Jf as ee,Lf as D,Mf as ye,Pf as W,Qf as z,Rf as v,_f as T}from"./vm-hands-entry-lite-wdsk86sk.js";import{Fg as ge}from"./vm-hands-entry-lite-pk2xd13q.js";import{ri as re}from"./vm-hands-entry-lite-1k23f7ja.js";import{Ni as J}from"./vm-hands-entry-lite-gs8cpdfw.js";import{Ti as y}from"./vm-hands-entry-lite-m57kpdgb.js";import{Kj as xe,Lj as te}from"./vm-hands-entry-lite-g63y988w.js";import{Rj as be,Xj as we}from"./vm-hands-entry-lite-630eqwb4.js";import{Yj as f}from"./vm-hands-entry-lite-p24kmysw.js";import{spawn as O}from"child_process";import{randomUUID as Se}from"crypto";import{closeSync as ct,copyFileSync as ce,existsSync as G,fstatSync as lt,mkdirSync as le,openSync as ut,readdirSync as F,readFileSync as Ae,readlinkSync as dt,renameSync as ft,rmSync as mt,statSync as pt}from"fs";import{connect as _t}from"net";import{userInfo as Oe}from"os";import{basename as ue,dirname as U,join as _}from"path";var V=`import { spawn, execFileSync } from "node:child_process";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { readFileSync, readlinkSync, lstatSync, realpathSync, statSync, mkdtempSync, mkdirSync, chmodSync, writeFileSync, readdirSync, rmSync, openSync, readSync, closeSync, renameSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
@@ -698,4 +698,4 @@ if(process.env.REASON_CLOUD_GATEWAY_EXEC === "1") {
698
698
  `),1;if(e.length===1&&e[0]==="doctor"){let s=await(r.grants??xe)(i);if(!s)return t.write(`Reason computer use: Reason's permissions could not be read (computer_use_permission_status_unavailable)
699
699
  `),1;return(r.stdout??process.stdout).write(Nt(s)),0}if(e.length!==1||e[0]!=="mcp")return t.write(`Usage: reason __computer-use mcp|doctor
700
700
  `),2;let[a,...c]=i;return(r.run??Rt)(a,[...c,o.ocu,"mcp"],{...process.env,OPEN_COMPUTER_USE_DISABLE_APP_AGENT_PROXY:"1"})}function Nr(e=v){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function Ne(e,r,t,i){return new Promise((o)=>{let a=O(e,r,{env:t,stdio:"ignore"}),c=setTimeout(()=>{a.kill("SIGKILL"),o(-1)},i);a.once("error",()=>{clearTimeout(c),o(-1)}),a.once("exit",(s)=>{clearTimeout(c),o(s??-1)})})}function Tt(e,r,t,i){return new Promise((o)=>{let a=O(e,r,{env:t,stdio:["ignore","pipe","ignore"]}),c="";a.stdout.setEncoding("utf8").on("data",(l)=>{c+=l});let s=setTimeout(()=>{a.kill("SIGKILL"),o(null)},i);a.once("error",()=>{clearTimeout(s),o(null)}),a.once("close",(l)=>{clearTimeout(s),o(l===0?c:null)})})}var Ct="/tmp/open-browser-use",It=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,kt=33554432;function qt(e,r){let t;try{t=e===null?null:JSON.parse(e)}catch{return null}let i=E(t)&&E(t.result)?t.result.metadata:null;if(!E(i)||i.extensionId!==r)return null;return typeof i.extensionInstanceId==="string"&&It.test(i.extensionInstanceId)?i.extensionInstanceId:null}async function Re(e,r,t){let i=t.storages.map((s)=>{try{return F(s).filter((l)=>l.endsWith(".log")||l.endsWith(".ldb")).map((l)=>_(s,l))}catch{return[]}}),o;try{o=i.some((s)=>s.length>0)?F(t.socketDir).filter((s)=>s.endsWith(".sock")):[]}catch{return[]}let a=[];for(let s of o){let l=_(t.socketDir,s),u=qt(await Tt(e,["info","--socket",l,"--timeout","2s"],r,5000),t.extensionId);if(u)a.push({instance:u,socket:l})}let c=[];for(let[s,l]of(a.length>0?i:[]).entries())for(let u of l)try{if(pt(u).size>kt)continue;let n=Ae(u),d=a.find((m)=>n.includes(m.instance));if(d){c.push({storage:t.storages[s],...d});break}}catch{}return c}async function Et(e,r,t){return(await Re(e,r,t))[0]?.instance??null}function Te(e,r,t){return Et(e,r,{socketDir:Ct,extensionId:D,storages:[_(t,"browser-profile","Default","Local Extension Settings",D)]})}var fe=/^(Default|Profile ([0-9]+))$/;async function Bt(e,r,t=y(),i=W){let o=_(t,"Library","Application Support","Google","Chrome"),a=[];try{a=F(o)}catch(n){if(n.code==="EPERM")throw new f("browser_use_chrome_access_denied","macOS blocked Reason from reading Chrome's profiles. Allow Full Disk Access for Reason on this Mac and try again.")}let c=(n)=>Number(fe.exec(n)?.[2]??-1),s=a.filter((n)=>fe.test(n)&&G(_(o,n,"Extensions",q))).sort((n,d)=>c(n)-c(d)),l=(n)=>_(o,n,"Local Extension Settings",q);return(await Re(e,r,{socketDir:i,extensionId:q,storages:s.map(l)})).map(({storage:n,instance:d,socket:m})=>({profile:s.find((p)=>l(p)===n),instance:d,socket:m}))}async function Ft(e,r,t=y(),i=W){let o=(await Bt(e,r,t,i))[0]?.instance;if(!o)throw new f("automation_user_chrome_not_connected","No Chrome profile on this Mac is connected to Reason. Open Chrome with the Reason extension, then try again.");return o}function me(e){return new Promise((r)=>{let t=_t({path:e}),i=(o)=>{t.destroy(),r(o)};t.setTimeout(1000,()=>i(!1)),t.once("error",()=>i(!1)),t.once("connect",()=>i(!0))})}async function Ce(e,r){let t=Date.now()+r;while(Date.now()<t){if(await e())return!0;await new Promise((i)=>setTimeout(i,200))}return!1}var $=new Map;function L(e,r){let t=$.get(e);if(!t)t=r().finally(()=>$.delete(e)),$.set(e,t);return t}async function Pt(e,r){if(await me(e))return;if(mt(e,{force:!0}),await Ne("dbus-daemon",["--session",`--address=unix:path=${e}`,"--fork"],r,1e4)!==0||!await Ce(()=>me(e),5000))throw new f("automation_unavailable","Reason could not start the desktop session bus.")}async function pe(e,r,t){let i=e.platform==="darwin-arm64"?async()=>await Te(e.nativeHost,r,t)!==null:async()=>await Ne(e.nativeHost,["info"],r,5000)===0;if(await i())return;let o=["--profile-directory=Default",`--load-extension=${e.extensionDir}`,"--no-first-run","--no-default-browser-check","--window-size=1280,800","about:blank"],a,c=null,s=0;if(e.platform==="darwin-arm64"){let n=_(t,"browser-profile");T(n);let d=_(n,"NativeMessagingHosts");le(d,{recursive:!0,mode:448});let m=z(e.platform).nativeHostManifests[0];ce(m,_(d,ue(m)));let p=e.browser.slice(0,e.browser.indexOf(".app/")+4),b=o.filter((A)=>A!=="about:blank").concat("--no-startup-window","--use-mock-keychain");a=O("/usr/bin/open",["-g","-n","-a",p,"--args",`--user-data-dir=${n}`,...b],{env:r,stdio:"ignore"})}else{let n=_(r.HOME,".config","google-chrome"),d=_(n,"NativeMessagingHosts");le(d,{recursive:!0,mode:448});let m=z(e.platform).nativeHostManifests[0];ce(m,_(d,ue(m)));let p=process.geteuid?.()===0?["--no-sandbox"]:[];c=_(t,"browser.log");let b=ut(c,"a",384);s=lt(b).size,a=O(e.browser,[`--user-data-dir=${n}`,...o,...p,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",b,b],env:{...r,ACCESSIBILITY_ENABLED:"1"}}),ct(b)}let l=!1;a.once("error",()=>{l=!0}),a.once("exit",(n)=>{l||=n!==0}),a.unref();let u=!1;if(await Ce(async()=>l||(u=await i()),St),!u){if(c&&Ae(c).subarray(s).toString("utf8").includes("No usable sandbox"))throw new f("automation_browser_sandbox_unavailable","Chromium found no usable sandbox on this machine. Run the worker as a non-root user with unprivileged user namespaces enabled, or in a container with seccomp unconfined.");throw new f("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function Rr(e){await qe(e,!0)}function Tr(e){return Ie(e,ke(e))}function Ie(e,r){return e.platform==="darwin-arm64"?_(r,"browser-profile"):_(r,"home",".config","google-chrome")}function ke(e){let r=_(e.root,"automation");if(!G(r)||!$t(e.automation))return e.automation;if(!Lt(Ie(e,r)))try{ft(r,e.automation)}catch{}return G(r)?r:e.automation}function $t(e){try{return F(e).length===0}catch(r){return r.code==="ENOENT"}}function Lt(e){let r;try{r=dt(_(e,"SingletonLock"))}catch{return!1}let t=Number(r.slice(r.lastIndexOf("-")+1));if(!Number.isSafeInteger(t)||t<=0)return!0;try{return process.kill(t,0),!0}catch(i){return i.code==="EPERM"}}async function qe(e,r){be({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=ke(e);T(t);let i=Oe().username,o={USER:i,LOGNAME:i,REASON_AUTOMATION_OCU:e.ocu,REASON_AUTOMATION_OBU:e.nativeHost};if(e.platform==="darwin-arm64"){let n={...o,HOME:y(),PATH:`${U(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:vt};if(!r)return n;await L("browser",()=>pe(e,n,t));let d=await Te(e.nativeHost,n,t);if(!d)throw new f("automation_browser_unavailable","Reason could not connect the desktop browser.");return{...n,REASON_AUTOMATION_OBU_INSTANCE:d,REASON_AUTOMATION_BACKGROUND_TABS:"1"}}let a=await Fe(),c=_(t,"home"),s=_(t,"runtime");T(c),T(s);let l=_(t,"bus"),u={...o,HOME:c,PATH:`${U(e.node)}:/usr/bin:/bin`,DISPLAY:a.display,XAUTHORITY:a.xauthority,XDG_RUNTIME_DIR:s,DBUS_SESSION_BUS_ADDRESS:`unix:path=${l}`,...a.sound?{PULSE_SERVER:ye(a.sound)}:{}};if(await L("bus",()=>Pt(l,u)),r)await L("browser",()=>pe(e,u,t));return u}async function Dt(e,r,t){let i=Oe().username,o={USER:i,LOGNAME:i,HOME:y(),PATH:`${U(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OBU:r,REASON_AUTOMATION_BACKGROUND_TABS:"1"},a=await Ft(r,o);return t.throwIfAborted(),{...o,REASON_AUTOMATION_OBU_INSTANCE:a}}function Ee(e,r,t,i){if(typeof de!=="string")return Promise.reject(new f("automation_unavailable","This Reason build has no automation runtime."));let o=de;return new Promise((a,c)=>{let s=O(e,["--input-type=module","--eval",o],{env:{...r,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:!0}),l=[],u=0,n="",d=null,m=!1,p=(h)=>{d??=h;try{process.kill(-s.pid,"SIGKILL")}catch{s.kill("SIGKILL")}},b=(h)=>{if(m)return;m=!0,clearTimeout(A),i.removeEventListener("abort",x),h()},A=setTimeout(()=>p(new f("automation_timed_out","Reason automation did not finish in time.")),wt),x=()=>p(new f("cancelled","Reason cancelled the automation call."));if(i.addEventListener("abort",x,{once:!0}),s.stdout.on("data",(h)=>{if(u+=h.byteLength,u>ht)p(new f("automation_output_too_large","Reason automation output is too large."));else l.push(h)}),s.stderr.setEncoding("utf8").on("data",(h)=>{n=(n+h).slice(-gt)}),s.stdin.on("error",()=>{}),s.once("error",()=>b(()=>c(d??new f("automation_unavailable","Reason could not start the automation runtime.")))),s.once("close",(h)=>b(()=>{if(d)c(d);else a({code:h??1,stdout:Buffer.concat(l),stderr:n})})),i.aborted)x();s.stdin.end(t)})}var S=new Map;function Gt(e,r,t){for(let[o,a]of S)if(a.expiresAt<=t)S.delete(o);while(S.size>=yt)S.delete(S.keys().next().value);let i=Se();return S.set(i,{runId:e,bytes:r,expiresAt:t+xt}),i}async function Be(e,r,t,i={}){let o=await(i.environment??qe)(e,r.kind==="browser");return t.throwIfAborted(),await(i.runtime??Ee)(e.node,o,JSON.stringify(r),t)}async function Cr(e,r){let t=ve({call:e});if(!("call"in t))B();let i=v();if(!i?.features.computer||t.call.kind==="browser"&&!i.features.browser)throw new f("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");return await Be(i,t.call,r)}function _e(e,r,t){let i=e.stdout.byteLength>M?Gt(r,e.stdout,t):void 0;return{code:e.code,stderr:e.stderr,instance_id:Ot,output_bytes:e.stdout.byteLength,chunk:e.stdout.subarray(0,M).toString("base64"),...i?{output_id:i}:{}}}async function Ir(e,r={}){let t=ve(e.payload),i=(r.now??Date.now)();if("output_id"in t){let p=S.get(t.output_id);if(!p||p.runId!==e.runId||p.expiresAt<=i||t.offset>p.bytes.byteLength)throw new f("automation_output_unavailable","Reason automation output expired.");return{chunk:p.bytes.subarray(t.offset,t.offset+M).toString("base64")}}let o=(r.components??v)(),a=(r.platform??process.platform)==="darwin",c=a?(r.macIdentity??J)():[],s=r.macSetup??k,l=!o?.features.computer||t.call.kind==="browser"&&!t.userChrome&&!o.features.browser;if(a&&(l||c.length===0||t.call.kind==="browser"&&t.userChrome&&!e.userChrome))return _e(await se({runId:e.runId,call:t.call,identity:c,desktopMissing:l,signal:e.signal},s),e.runId,i);if(!o?.features.computer)throw new f("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let u=t.userChrome?e.userChrome:void 0;if(t.userChrome&&!u)throw new f("automation_user_chrome_unavailable","Your own Chrome is not enabled on this computer: run `reason desktop install` on this Mac (and `reason connect --user-chrome on` if you turned it off).");if(t.call.kind==="browser"&&!u&&!o.features.browser)throw new f("automation_browser_not_installed",o.platform==="darwin-arm64"?"Browser use is unavailable on this machine: re-run `reason desktop install`.":"Browser use is unavailable on this machine: install a non-snap Chromium at /usr/bin/chromium, then re-run `reason desktop install`.");e.signal.throwIfAborted();let n=await we(e.runId,e.signal,r.now),d="account"in r?r.account??null:ge(),m;try{if(u){let p=await(r.userChromeEnvironment??Dt)(o,u,e.signal);e.signal.throwIfAborted(),m=await(r.runtime??Ee)(o.node,p,JSON.stringify(t.call),e.signal)}else if(d)m=await(r.delegate??X)(d,t.call,e.signal);else m=await Be(o,t.call,e.signal,r)}finally{n()}if(a)m=await ne({runId:e.runId,call:t.call,identity:c,output:m,signal:e.signal},s);return _e(m,e.runId,i)}
701
- export{Ke as td,M as ud,ve as vd,Or as wd,Rt as xd,vr as yd,Nr as zd,Bt as Ad,Ft as Bd,Rr as Cd,Tr as Dd,Cr as Ed,Ir as Fd};
701
+ export{Ke as ud,M as vd,ve as wd,Or as xd,Rt as yd,vr as zd,Nr as Ad,Bt as Bd,Ft as Cd,Rr as Dd,Tr as Ed,Cr as Fd,Ir as Gd};