@reason-machines/cli-linux-arm64-musl 0.2.380 → 0.2.382

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 (111) hide show
  1. package/README.md +3 -1
  2. package/bin/ara +2 -2
  3. package/bin/vm-hands/api-credentials-xppmbg0m.js +2 -0
  4. package/bin/vm-hands/api-xmpbsm6b.js +2 -0
  5. package/bin/vm-hands/{ask-relay-9pm7kj1s.js → ask-relay-zjqyxvxe.js} +3 -3
  6. package/bin/vm-hands/connect-cli-ehxeg8m5.js +2 -0
  7. package/bin/vm-hands/{custom-endpoint-device-zhpake9f.js → custom-endpoint-device-bm94e9r0.js} +1 -1
  8. package/bin/vm-hands/desktop-account-3tnm4z5w.js +2 -0
  9. package/bin/vm-hands/{device-workspace-vbcry9d6.js → device-workspace-0xsj5ykf.js} +1 -1
  10. package/bin/vm-hands/hands-worker-source-azdrrhsz.js +2 -0
  11. package/bin/vm-hands/{index-bbk6a9sk.js → index-7f2kwwen.js} +1 -1
  12. package/bin/vm-hands/{install-receipt-7x81ek76.js → install-receipt-3xyx3rdd.js} +1 -1
  13. package/bin/vm-hands/local-automation-ynx1qr9v.js +2 -0
  14. package/bin/vm-hands/local-capabilities-855ch0dq.js +2 -0
  15. package/bin/vm-hands/local-desktop-users-ajb81vjm.js +2 -0
  16. package/bin/vm-hands/local-display-mac-9h6btvvq.js +2 -0
  17. package/bin/vm-hands/local-display-session-f9ywkbba.js +2 -0
  18. package/bin/vm-hands/local-pty-session-cjas515w.js +2 -0
  19. package/bin/vm-hands/managed-runtime-dars4628.js +2 -0
  20. package/bin/vm-hands/{network-contract-zqvt1v0t.js → network-contract-dsw79qkc.js} +1 -1
  21. package/bin/vm-hands/package-smk3nqjs.js +2 -0
  22. package/bin/vm-hands/permissions-pdmhp2s3.js +2 -0
  23. package/bin/vm-hands/{reason-hands-protocol-8fxjynte.js → reason-hands-protocol-7d7xj1h3.js} +1 -1
  24. package/bin/vm-hands/serve-service-n6xd6323.js +2 -0
  25. package/bin/vm-hands/status-2m75kz1h.js +96 -0
  26. package/bin/vm-hands/version-74zqccyz.js +2 -0
  27. package/bin/vm-hands/vm-hands-entry-lite-06qnb2w1.js +458 -0
  28. package/bin/vm-hands/{vm-hands-entry-lite-7shpbsw8.js → vm-hands-entry-lite-1gxktkpe.js} +2 -2
  29. package/bin/vm-hands/{vm-hands-entry-lite-wf1ek4f0.js → vm-hands-entry-lite-23bb8ce4.js} +2 -2
  30. package/bin/vm-hands/vm-hands-entry-lite-245929bs.js +346 -0
  31. package/bin/vm-hands/vm-hands-entry-lite-2e18tm6w.js +245 -0
  32. package/bin/vm-hands/{vm-hands-entry-lite-g036gtem.js → vm-hands-entry-lite-2t0vcvd8.js} +1 -1
  33. package/bin/vm-hands/{vm-hands-entry-lite-8yy5ttfw.js → vm-hands-entry-lite-2tcjqgfp.js} +3 -3
  34. package/bin/vm-hands/vm-hands-entry-lite-3n3xh0xv.js +540 -0
  35. package/bin/vm-hands/vm-hands-entry-lite-50n6vbfx.js +251 -0
  36. package/bin/vm-hands/{vm-hands-entry-lite-j2q1k9vb.js → vm-hands-entry-lite-51hmj6am.js} +1 -1
  37. package/bin/vm-hands/{vm-hands-entry-lite-zfwg7ehq.js → vm-hands-entry-lite-5n4vsm6b.js} +2 -2
  38. package/bin/vm-hands/vm-hands-entry-lite-8fj07njx.js +3 -0
  39. package/bin/vm-hands/{vm-hands-entry-lite-r8twmzjc.js → vm-hands-entry-lite-8zawqa9q.js} +2 -2
  40. package/bin/vm-hands/{vm-hands-entry-lite-3hbe4em3.js → vm-hands-entry-lite-9cmfthkq.js} +1 -1
  41. package/bin/vm-hands/{vm-hands-entry-lite-45j8qwsf.js → vm-hands-entry-lite-9w5vs9zv.js} +1 -1
  42. package/bin/vm-hands/{vm-hands-entry-lite-qyzgxd9g.js → vm-hands-entry-lite-aj1ccphg.js} +2 -2
  43. package/bin/vm-hands/{vm-hands-entry-lite-za55dtte.js → vm-hands-entry-lite-ammr3xbc.js} +2 -2
  44. package/bin/vm-hands/{vm-hands-entry-lite-de2rkr5h.js → vm-hands-entry-lite-ch7y4b1b.js} +1 -1
  45. package/bin/vm-hands/{vm-hands-entry-lite-439yqbn5.js → vm-hands-entry-lite-cwe16c51.js} +174 -16
  46. package/bin/vm-hands/vm-hands-entry-lite-dh5gwmyf.js +3 -0
  47. package/bin/vm-hands/vm-hands-entry-lite-dsdwzasy.js +105 -0
  48. package/bin/vm-hands/{vm-hands-entry-lite-5pm6bhb8.js → vm-hands-entry-lite-e0gdt6r5.js} +1 -1
  49. package/bin/vm-hands/{vm-hands-entry-lite-5kgvss4p.js → vm-hands-entry-lite-e2mjbqmr.js} +2 -2
  50. package/bin/vm-hands/vm-hands-entry-lite-ejm5er3h.js +7 -0
  51. package/bin/vm-hands/{vm-hands-entry-lite-mh0xecf3.js → vm-hands-entry-lite-f02906k8.js} +4 -4
  52. package/bin/vm-hands/vm-hands-entry-lite-f5230h6t.js +67 -0
  53. package/bin/vm-hands/{vm-hands-entry-lite-zh8p7ndn.js → vm-hands-entry-lite-fb5dzy9x.js} +2 -2
  54. package/bin/vm-hands/vm-hands-entry-lite-fyvgav60.js +3 -0
  55. package/bin/vm-hands/vm-hands-entry-lite-g7h6wjqy.js +3 -0
  56. package/bin/vm-hands/vm-hands-entry-lite-h8dbw0c7.js +4 -0
  57. package/bin/vm-hands/{vm-hands-entry-lite-nhtb458c.js → vm-hands-entry-lite-hnsm5t36.js} +1 -1
  58. package/bin/vm-hands/{vm-hands-entry-lite-r6pap1kh.js → vm-hands-entry-lite-ma001vzh.js} +1 -1
  59. package/bin/vm-hands/{vm-hands-entry-lite-anmv8hp7.js → vm-hands-entry-lite-mn64e4pt.js} +286 -104
  60. package/bin/vm-hands/{vm-hands-entry-lite-9cgm6g8t.js → vm-hands-entry-lite-pk3q774c.js} +1 -1
  61. package/bin/vm-hands/vm-hands-entry-lite-qef2ndkd.js +6 -0
  62. package/bin/vm-hands/vm-hands-entry-lite-qnnfvm5r.js +5 -0
  63. package/bin/vm-hands/vm-hands-entry-lite-qwf78yqr.js +11 -0
  64. package/bin/vm-hands/vm-hands-entry-lite-r8qg3wp1.js +3 -0
  65. package/bin/vm-hands/vm-hands-entry-lite-rd0ak4ye.js +4 -0
  66. package/bin/vm-hands/{vm-hands-entry-lite-00qsbphw.js → vm-hands-entry-lite-rpn0frzb.js} +2 -2
  67. package/bin/vm-hands/{vm-hands-entry-lite-g9rvf5qk.js → vm-hands-entry-lite-rtt2w6c6.js} +1 -1
  68. package/bin/vm-hands/vm-hands-entry-lite-sex82vb1.js +3 -0
  69. package/bin/vm-hands/{vm-hands-entry-lite-dgxxsdwb.js → vm-hands-entry-lite-xrthfx3q.js} +2 -2
  70. package/bin/vm-hands/{vm-hands-entry-lite-kxdw4myj.js → vm-hands-entry-lite-y2s2w174.js} +1 -1
  71. package/bin/vm-hands/{vm-hands-entry-lite-hc3p6r9p.js → vm-hands-entry-lite-zjfr0zh8.js} +2 -2
  72. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  73. package/bin/vm-hands/{vm-hands-executor-a05whg1y.js → vm-hands-executor-yx6mxa2p.js} +1 -1
  74. package/bin/vm-hands/vm-hands-op-runner-yt3v3v6w.js +2 -0
  75. package/bin/vm-hands/{vm-hands-runtime-ky9jhq5h.js → vm-hands-runtime-ygddqgbs.js} +3 -3
  76. package/bin/vm-hands/worker-sandbox-tgqbmy6b.js +2 -0
  77. package/package.json +1 -1
  78. package/bin/vm-hands/api-af9g18n7.js +0 -2
  79. package/bin/vm-hands/api-credentials-65mrr3tn.js +0 -2
  80. package/bin/vm-hands/connect-cli-w0z9jzv5.js +0 -2
  81. package/bin/vm-hands/desktop-account-5zvgspyw.js +0 -2
  82. package/bin/vm-hands/hands-worker-source-h0b1j53p.js +0 -2
  83. package/bin/vm-hands/local-automation-nm3xtj0a.js +0 -2
  84. package/bin/vm-hands/local-capabilities-bbrr6j7v.js +0 -2
  85. package/bin/vm-hands/local-desktop-users-0hadyvx1.js +0 -2
  86. package/bin/vm-hands/local-display-mac-v1pc7177.js +0 -2
  87. package/bin/vm-hands/local-display-session-n0kagkex.js +0 -2
  88. package/bin/vm-hands/local-pty-session-hs7rq03x.js +0 -2
  89. package/bin/vm-hands/managed-runtime-n7ftmmx7.js +0 -2
  90. package/bin/vm-hands/package-3cd7cfyv.js +0 -2
  91. package/bin/vm-hands/permissions-bfwdxyr5.js +0 -2
  92. package/bin/vm-hands/serve-service-g12x52xn.js +0 -2
  93. package/bin/vm-hands/status-t3jrf9fn.js +0 -96
  94. package/bin/vm-hands/version-m89hab1m.js +0 -2
  95. package/bin/vm-hands/vm-hands-entry-lite-1085xsma.js +0 -5
  96. package/bin/vm-hands/vm-hands-entry-lite-4m40gwkf.js +0 -3
  97. package/bin/vm-hands/vm-hands-entry-lite-5q1q991e.js +0 -181
  98. package/bin/vm-hands/vm-hands-entry-lite-bdp2578c.js +0 -540
  99. package/bin/vm-hands/vm-hands-entry-lite-bvbfcp1k.js +0 -4
  100. package/bin/vm-hands/vm-hands-entry-lite-c01eyep6.js +0 -3
  101. package/bin/vm-hands/vm-hands-entry-lite-dcynw6t2.js +0 -3
  102. package/bin/vm-hands/vm-hands-entry-lite-g6912hkd.js +0 -62
  103. package/bin/vm-hands/vm-hands-entry-lite-hh24bq0d.js +0 -3
  104. package/bin/vm-hands/vm-hands-entry-lite-jb2sr2r7.js +0 -3
  105. package/bin/vm-hands/vm-hands-entry-lite-sb9a1jcn.js +0 -4
  106. package/bin/vm-hands/vm-hands-entry-lite-sky5eg5d.js +0 -11
  107. package/bin/vm-hands/vm-hands-entry-lite-ynzy9k5z.js +0 -340
  108. package/bin/vm-hands/vm-hands-entry-lite-ze9msfq1.js +0 -3
  109. package/bin/vm-hands/vm-hands-entry-lite-zq42mcjc.js +0 -459
  110. package/bin/vm-hands/vm-hands-op-runner-69sca90a.js +0 -2
  111. package/bin/vm-hands/worker-sandbox-wpzkvwer.js +0 -2
@@ -0,0 +1,105 @@
1
+ // @bun
2
+ import{ne as Qz,pe as R,se as Zz}from"./vm-hands-entry-lite-qnnfvm5r.js";import{mi as zz}from"./vm-hands-entry-lite-e2mjbqmr.js";import{Ci as e}from"./vm-hands-entry-lite-ma001vzh.js";import{Wi as Hz,ij as V,kj as Jz}from"./vm-hands-entry-lite-8zawqa9q.js";import{wk as X}from"./vm-hands-entry-lite-r8qg3wp1.js";import{spawnSync as C}from"child_process";import{createHash as Pz,randomUUID as Iz}from"crypto";import{chmodSync as Wz,existsSync as y,mkdirSync as bz,readdirSync as Sz,readFileSync as L,renameSync as wz,rmSync as Y,statSync as _z,writeFileSync as xz}from"fs";import{dirname as Rz,isAbsolute as $z,join as N}from"path";import{spawnSync as Az}from"child_process";import{readFileSync as Oz}from"fs";import{userInfo as v}from"os";import{join as Cz}from"path";var Kz="REASON_SCHEDULED_TASK";function l(H){return Cz(H,"AppData","Local","Reason","Tasks")}function A(H){if(/[\0-\x1f\x7f"%]/.test(H))throw Error(`A background task cannot use a value with a double quote, percent sign or control character: ${H}`);return`'${H.replace(/['\u2018\u2019\u201a\u201b]/g,"$&$&")}'`}function a(H){if(!/^[A-Za-z0-9._-]+$/.test(H))throw Error(`Invalid Windows Scheduled Task name: ${H}`);return`$env:${Kz}=${A(H)};`}function c(H){let z=Object.entries(H.environment).map(([Q,Z])=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`Invalid Windows Scheduled Task environment name: ${Q}`);return`$env:${Q}=${A(Z)};`}),J=`$global:LASTEXITCODE=1; & ${[H.program,...H.args].map(A).join(" ")} 2>&1 | ForEach-Object { Add-Content -LiteralPath ${A(H.log)} -Value $_.ToString() -Encoding UTF8 }; $c=$LASTEXITCODE;`;return[a(H.name),...z,"$ErrorActionPreference='Continue';",H.keepAlive?`do { ${J} if ($c) { Start-Sleep -Seconds 10 } } while ($c)`:`${J} exit $c`].join(" ")}function S(H){return H.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function Vz(){let H=process.env.USERDOMAIN?.trim();return H?`${H}\\${v().username}`:v().username}function h(H){let z=S(H.user??Vz()),J=H.schedule==="logon",Q=H.schedule==="logon"?`<LogonTrigger><Enabled>true</Enabled><UserId>${z}</UserId></LogonTrigger>`:`<TimeTrigger><Repetition><Interval>PT${H.schedule.everyMinutes}M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition><StartBoundary>2026-01-01T00:00:00</StartBoundary><Enabled>true</Enabled></TimeTrigger>`,Z=`-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -Command "${H.script}"`;return`<?xml version="1.0" encoding="UTF-16"?>
3
+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
4
+ <RegistrationInfo>
5
+ <Description>${S(H.description)}</Description>
6
+ </RegistrationInfo>
7
+ <Triggers>
8
+ ${Q}
9
+ </Triggers>
10
+ <Principals>
11
+ <Principal id="Author">
12
+ <UserId>${z}</UserId>
13
+ <LogonType>InteractiveToken</LogonType>
14
+ <RunLevel>LeastPrivilege</RunLevel>
15
+ </Principal>
16
+ </Principals>
17
+ <Settings>
18
+ <MultipleInstancesPolicy>${J?"StopExisting":"IgnoreNew"}</MultipleInstancesPolicy>
19
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
20
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
21
+ <StartWhenAvailable>true</StartWhenAvailable>
22
+ <IdleSettings>
23
+ <StopOnIdleEnd>false</StopOnIdleEnd>
24
+ <RestartOnIdle>false</RestartOnIdle>
25
+ </IdleSettings>
26
+ <ExecutionTimeLimit>${J?"PT0S":"PT1H"}</ExecutionTimeLimit>
27
+ <Priority>${J?5:7}</Priority>
28
+ </Settings>
29
+ <Actions Context="Author">
30
+ <Exec>
31
+ <Command>%SystemRoot%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe</Command>
32
+ <Arguments>${S(Z)}</Arguments>
33
+ </Exec>
34
+ </Actions>
35
+ </Task>
36
+ `}function n(H){return Buffer.concat([Buffer.from([255,254]),Buffer.from(H.replaceAll(`\r
37
+ `,`
38
+ `).replaceAll(`
39
+ `,`\r
40
+ `),"utf16le")])}function r(H){let z=Oz(H);return(z[0]===255&&z[1]===254?z.subarray(2).toString("utf16le"):z.toString("utf8")).replaceAll(`\r
41
+ `,`
42
+ `)}function i(H,z){return["/Create","/TN",H,"/XML",z,"/F"]}function w(H){return["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(H,"utf16le").toString("base64")]}function _(H){return`'*${a(H).replaceAll("'","''")}*'`}function x(H,z){return w(["$all = @(Get-CimInstance Win32_Process)",`$wrappers = @($all | ? { $_.ProcessId -ne $PID -and $_.CommandLine -like ${_(H)} })`,...z.keepWrapper?[]:["foreach ($w in $wrappers) { Stop-Process -Id $w.ProcessId -Force -ErrorAction SilentlyContinue }"],`foreach ($w in $wrappers) { $all | ? { $_.ParentProcessId -eq $w.ProcessId } | % { taskkill.exe /F ${z.tree?"/T ":""}/PID $_.ProcessId | Out-Null } }`].join(`
43
+ `))}function s(H){return w(["$all = @(Get-CimInstance Win32_Process)",`$wrappers = @($all | ? { $_.ProcessId -ne $PID -and $_.CommandLine -like ${_(H)} })`,"foreach ($w in $wrappers) { if ($all | ? { $_.ParentProcessId -eq $w.ProcessId -and $_.Name -ne 'conhost.exe' }) { 'running'; exit 0 } }","exit 1"].join(`
44
+ `))}function t(H,z=process.pid){let J=Az(X("powershell.exe"),w(["$all = @{}; Get-CimInstance Win32_Process | % { $all[[int]$_.ProcessId] = $_ }",`$p = $all[${Math.trunc(z)}]`,"for ($i = 0; $p -and $i -lt 64; $i++) {",` if ($p.CommandLine -like ${_(H)}) { exit 10 }`," $n = $all[[int]$p.ParentProcessId]"," if (-not $n -or $n.ProcessId -eq $p.ProcessId -or $n.CreationDate -gt $p.CreationDate) { exit 11 }"," $p = $n","}","exit 11"].join(`
45
+ `)),{stdio:"ignore",timeout:15000,windowsHide:!0});return J.status===10?!0:J.status===11?!1:null}var P="REASON_WORKER_SERVICE",yz="worker_identity_unavailable";function BH(H){return{platform:process.platform,home:H,uid:process.getuid?.(),command:(z,J)=>C(X(z),[...J],{stdio:"ignore"}).status??1,read:(z,J)=>{let Q=C(X(z),[...J],{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4});return Q.status===0?Q.stdout:null},sleep:(z)=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,z),workerIdentity:(z)=>Jz(H,z),insideService:(z,J)=>kz(z,process.platform,process.getuid?.(),J)}}function kz(H,z,J,Q=!0){if(process.env[P]===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==="win32")return t(H)??Q;if(z!=="darwin")return!1;if(typeof J!=="number")return!0;let Z=C("/bin/launchctl",["print",`gui/${J}/${H}`],{encoding:"utf8",timeout:5000});if(Z.status===Ez)return!1;if(Z.error||Z.status!==0)return!0;let q=Number(/^\s*pid = (\d+)$/m.exec(Z.stdout??"")?.[1]??0);if(!q)return!1;let B=process.pid;for(let $=0;$<64&&B>1;$+=1){if(B===q)return!0;let j=C("/bin/ps",["-o","ppid=","-p",String(B)],{encoding:"utf8",timeout:5000}),G=Number(j.stdout?.trim());if(j.error||j.status!==0||!Number.isSafeInteger(G)||G<=0)return!0;if(G===B)return!1;B=G}return B>1}var Ez=113;class M extends Error{code;constructor(H,z){super(H);this.code=z}}function qH(H,z){if(!u(H.home,H.platform))throw new M(Gz);if(H.platform==="darwin")F(H);let J=Zz(Qz(z,H.home)),Q=zz({env:z})==="staging",Z=Q?"ara-staging":"ara",q=[J?.owned_paths.find((B)=>B.role==="launcher")?.path,e(z,"REASON_CLI_LAUNCHER_PATH")?.trim(),H.platform==="win32"?N(H.home,"AppData","Local","Reason",...Q?["staging"]:[],"bin",Q?"reason-staging.exe":"reason.exe"):N(H.home,".local","bin",Z)];for(let B of q)try{if(B&&$z(B)&&_z(B).isFile())return R(B)}catch{}throw new M(`A background service runs the installed Reason launcher, which was not found. Install Reason with: ${H.platform==="win32"?"irm https://reasonmachines.com/install.ps1 | iex":"curl -fsSL https://reasonmachines.com/install | sh"}`,"worker_launcher_missing")}var k=/(<key>ProgramArguments<\/key>\s*<array>\n)((?:\s*<string>[^<]*<\/string>\n)*)(\s*<\/array>)/,O=new RegExp(`(\\n\\s*<key>${V}</key>\\s*<string>)[^<]*(</string>)`),fz=/(<key>EnvironmentVariables<\/key>\s*<dict>[\s\S]*?)(\n\s*<\/dict>)/;function mz(H){return H.replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("&quot;",'"').replaceAll("&apos;","'").replaceAll("&amp;","&")}function E(H){let z=[...(k.exec(H)?.[2]??"").matchAll(/<string>([^<]*)<\/string>/g)].map((Q)=>mz(Q[1])),J=z[1]==="--run-worker"?z.slice(2):z;return J[0]?{launcher:J[0],args:J.slice(1)}:null}function jH(H,z){if(!dz(z))return null;try{return E(L(N(H,"Library","LaunchAgents",`${z}.plist`),"utf8"))?.launcher??null}catch{return null}}function Bz(H,z,J){let Q=J.workerIdentity?.(H)??null;return{program:Q?[Q.executable,"--run-worker",H,...z]:[H,...z],identity:Q}}function f(H){return H.map((z)=>` <string>${D(z)}</string>`).join(`
46
+ `)}function qz(H,z){let J;try{J=L(H,"utf8")}catch{return null}let Q=E(J);if(!Q)return null;let Z=$z(Q.launcher)?R(Q.launcher):Q.launcher,{program:q,identity:B}=Bz(Z,Q.args,z),$=J.replace(k,(j,G,U,g)=>`${G}${f(q)}
47
+ ${g}`);if(!B)$=$.replace(O,"");else if(O.test($))$=$.replace(O,(j,G,U)=>`${G}${D(B.app)}${U}`);else $=$.replace(fz,(j,G,U)=>`${G}
48
+ <key>${V}</key>
49
+ <string>${D(B.app)}</string>${U}`);return $===J?null:$}function uz(H,z){let J=qz(H,z);if(J!==null)b(H,J)}function GH(H,z,J){if(z.platform!=="darwin")return!1;let Q=d(H,z,J);return Q!==null&&qz(Q.definition,z)!==null}var I="com.reasonmachines.worker.",m="so.reason.worker.",W=[I,m];function dz(H){return W.some((z)=>H.startsWith(z)&&/^[A-Za-z0-9._-]+$/.test(H.slice(z.length)))}function jz(H,z=I){return`${z}connect${H==="production"?"":`.${H}`}`}function MH(H,z){return W.some((J)=>H===jz(z,J))}function pz(H,z,J){if(z==="connect")return jz(H.channel,J);let Q=Pz("sha256").update(H.workspaceRoot).digest("hex").slice(0,8);return`${J}${H.name.toLowerCase()}.${Q}`}var Gz="A background service needs macOS (launchd), Linux (systemd --user) or Windows (Task Scheduler).";function u(H,z){if(z==="darwin")return{directory:N(H,"Library","LaunchAgents"),suffix:".plist"};if(z==="linux")return{directory:N(H,".config","systemd","user"),suffix:".service"};if(z==="win32")return{directory:l(H),suffix:".xml"};return null}function T(H,z,J,Q=I){let Z=pz(H,J,Q),q=u(z.home,z.platform);if(!q)return null;return{label:Z,definition:N(q.directory,`${Z}${q.suffix}`),logs:z.platform==="linux"?`journalctl --user -u ${Z}.service`:N(H.stateDirectory,"service.log")}}function YH(H,z){let J=u(H,z);if(!J)return[];try{return Sz(J.directory).filter((Q)=>W.some((Z)=>Q.startsWith(Z))&&Q.endsWith(J.suffix)).sort().map((Q)=>N(J.directory,Q))}catch{return[]}}function d(H,z,J="serve"){return Mz(H,z,J)[0]??null}function Mz(H,z,J){return W.map((Q)=>T(H,z,J,Q)).filter((Q)=>Q!==null&&y(Q.definition))}function Yz(H,z,J){let Q=T(H,z,J,m);return Q&&y(Q.definition)?Q:null}function gz(H,z,J){let Q=T(H,z,J),Z=Yz(H,z,J);if(!Q||!Z||!y(Q.definition)||z.insideService?.(Z.label))return null;if(!vz(Q,z))return"current_not_running";if(z.platform==="darwin"){if(typeof z.uid==="number"&&z.uid>0)z.command("/bin/launchctl",["bootout",`gui/${z.uid}/${Z.label}`]);return Y(Z.definition,{force:!0}),"retired"}if(z.platform==="win32")return K(Z,z,!0),"retired";return z.command("systemctl",["--user","disable","--now",`${Z.label}.service`]),Y(Z.definition,{force:!0}),z.command("systemctl",["--user","daemon-reload"]),"retired"}function vz(H,z){if(z.platform==="darwin")return typeof z.uid==="number"&&z.uid>0&&z.command("/bin/launchctl",["print",`gui/${z.uid}/${H.label}`])===0;if(z.platform==="win32")return z.command("schtasks",["/Query","/TN",H.label])===0;let J=`${H.label}.service`;return z.command("systemctl",["--user","is-enabled","--quiet",J])===0&&lz.has(z.read("systemctl",["--user","show","--property=ActiveState","--value",J])?.trim()??"")}var lz=new Set(["active","activating","reloading"]);function DH(H,z){if(z.platform==="darwin"){if(typeof z.uid!=="number"||z.uid<=0)return!1;let J=z.read("/bin/launchctl",["print",`gui/${z.uid}/${H.label}`]);return Number(/^\s*pid = (\d+)$/m.exec(J??"")?.[1]??0)>0}if(z.platform==="win32")return z.read("powershell.exe",s(H.label))?.trim()==="running";return Number(z.read("systemctl",["--user","show","--property=MainPID","--value",`${H.label}.service`])?.trim()??0)>0}function UH(H){let{config:z,launcher:J,host:Q,kind:Z}=H,q=T(z,Q,Z);if(!q)return!1;let B;try{B=Q.platform==="win32"?r(q.definition):L(q.definition,"utf8")}catch{return!1}if(Q.platform==="win32")return B===Nz(z,Z,q,J);if(Q.platform!=="darwin")return B===Uz(z,Z,q,J,Q.home,H.path);let $=E(B);return B.replace(O,"").replace(k,(G,U,g,Fz)=>`${U}${$?`${f([$.launcher,...$.args])}
50
+ `:""}${Fz}`)===Dz(z,Z,q,J,{...Q,workerIdentity:()=>null},H.path).plist}function p(H,z){if(z==="connect")return{args:["connect"],environment:{REASON_CLI_CHANNEL:H.channel},description:"Reason connection of this computer"};return{args:["serve",H.name,"--dir",H.workspaceRoot,...H.executionMode==="confined"?["--sandbox"]:[]],environment:{},description:`Reason machine ${H.name} worker`}}function D(H){return H.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function o(H,z=!1){if(/[\0-\x1f\x7f]/.test(H))throw new M("A background service cannot use a path with control characters.");let J=H.replaceAll("\\","\\\\").replaceAll('"',"\\\"").replaceAll("%","%%");return`"${z?J.replaceAll("$","$$$$"):J}"`}function Dz(H,z,J,Q,Z,q){let B=p(H,z),$=Bz(Q,B.args,Z),j={HOME:Z.home,PATH:q,[P]:J.label,...B.environment,...$.identity?{[V]:$.identity.app}:{}};return{identity:$.identity,plist:`<?xml version="1.0" encoding="UTF-8"?>
51
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
52
+ <plist version="1.0">
53
+ <dict>
54
+ <key>Label</key>
55
+ <string>${D(J.label)}</string>
56
+ <key>AssociatedBundleIdentifiers</key>
57
+ <array>
58
+ <string>${Hz}</string>
59
+ </array>
60
+ <key>ProgramArguments</key>
61
+ <array>
62
+ ${f($.program)}
63
+ </array>
64
+ <key>EnvironmentVariables</key>
65
+ <dict>
66
+ ${Object.entries(j).map(([G,U])=>` <key>${G}</key>
67
+ <string>${D(U)}</string>`).join(`
68
+ `)}
69
+ </dict>
70
+ <key>RunAtLoad</key>
71
+ <true/>
72
+ <key>KeepAlive</key>
73
+ <dict>
74
+ <key>SuccessfulExit</key>
75
+ <false/>
76
+ </dict>
77
+ <key>ThrottleInterval</key>
78
+ <integer>10</integer>
79
+ <key>ExitTimeOut</key>
80
+ <integer>${Math.ceil(H.shutdownGraceMs/1000)+10}</integer>
81
+ <key>ProcessType</key>
82
+ <string>Standard</string>
83
+ <key>Umask</key>
84
+ <integer>63</integer>
85
+ <key>StandardOutPath</key>
86
+ <string>${D(J.logs)}</string>
87
+ <key>StandardErrorPath</key>
88
+ <string>${D(J.logs)}</string>
89
+ </dict>
90
+ </plist>
91
+ `}}function Uz(H,z,J,Q,Z,q){let B=p(H,z);return`[Unit]
92
+ Description=${B.description}
93
+
94
+ [Service]
95
+ ExecStart=${[Q,...B.args].map(($)=>o($,!0)).join(" ")}
96
+ Environment=${[`HOME=${Z}`,`PATH=${q}`,`${P}=${J.label}`,...Object.entries(B.environment).map(([$,j])=>`${$}=${j}`)].map(($)=>o($)).join(" ")}
97
+ Restart=on-failure
98
+ RestartSec=10
99
+ TimeoutStopSec=${Math.ceil(H.shutdownGraceMs/1000)+10}
100
+ UMask=0077
101
+
102
+ [Install]
103
+ WantedBy=default.target
104
+ `}function Nz(H,z,J,Q){let Z=p(H,z);return h({description:Z.description,schedule:"logon",script:c({name:J.label,program:Q,args:Z.args,environment:{[P]:J.label,...Z.environment},log:J.logs,keepAlive:!0})})}function Tz(H,z,J){z.command("powershell.exe",x(H.label,{tree:J,keepWrapper:!J}))}function K(H,z,J){z.command("schtasks",["/Delete","/F","/TN",H.label]),z.command("powershell.exe",x(H.label,{tree:J,keepWrapper:!1})),Y(H.definition,{force:!0})}function b(H,z){bz(Rz(H),{recursive:!0,mode:448});let J=`${H}.${Iz()}.tmp`;try{xz(J,z,{mode:384,flag:"wx"}),Wz(J,384),wz(J,H)}finally{Y(J,{force:!0})}}function F(H){if(typeof H.uid!=="number"||!Number.isSafeInteger(H.uid)||H.uid<=0)throw new M("Set up a background service as your own user, not with sudo.","worker_service_root_user");return`gui/${H.uid}`}function NH(H){let{config:z,launcher:J,host:Q}=H,Z=H.kind??"serve",q=Yz(z,Q,Z),B=q!==null&&Q.insideService?.(q.label)===!0,$=T(z,Q,Z,B?m:I);if(!$)throw new M(Gz);if(Q.platform==="darwin")F(Q);if(Q.platform==="linux"&&Q.command("systemctl",["--user","show-environment"])!==0)throw new M("No background service here: this computer has no systemd user session.","worker_service_manager_missing");let j=Q.platform==="darwin"?Dz(z,Z,$,J,Q,H.path):null;if(b($.definition,j?j.plist:Q.platform==="win32"?n(Nz(z,Z,$,J)):Uz(z,Z,$,J,Q.home,H.path)),Lz(z,Q,$,B?null:q),j)return j.identity?$:{...$,identityProblem:yz};if(Q.platform==="win32")return $;return{...$,lingering:Q.command("loginctl",["enable-linger"])===0}}function Lz(H,z,J,Q){if(z.platform==="darwin"){let B=F(z);if(Q)z.command("/bin/launchctl",["bootout",`${B}/${Q.label}`]);if(Xz(H,J,z)){if(Q)Y(Q.definition,{force:!0});return}if(Y(J.definition,{force:!0}),Q)z.command("/bin/launchctl",["bootstrap",B,Q.definition]);throw new M("Could not start the background service (launchctl bootstrap failed).","worker_service_start_failed")}if(z.platform==="win32"){if(Q)K(Q,z,!0);if(z.command("schtasks",i(J.label,J.definition))===0){if(Tz(J,z,z.insideService?.(J.label)!==!0),z.command("schtasks",["/Run","/TN",J.label])===0)return}throw K(J,z,!0),new M("Could not start the background service (schtasks failed).")}let Z=`${J.label}.service`,q=Q?`${Q.label}.service`:null;if(z.command("systemctl",["--user","daemon-reload"])!==0||q!==null&&z.command("systemctl",["--user","disable","--now",q])!==0||z.command("systemctl",["--user","enable",Z])!==0||z.command("systemctl",["--user","restart",Z])!==0){if(z.command("systemctl",["--user","disable",Z]),Y(J.definition,{force:!0}),z.command("systemctl",["--user","daemon-reload"]),q)z.command("systemctl",["--user","enable","--now",q]);throw new M("Could not start the background service (systemctl --user failed).","worker_service_start_failed")}if(Q)Y(Q.definition,{force:!0}),z.command("systemctl",["--user","daemon-reload"])}function Xz(H,z,J){let Q=F(J);J.command("/bin/launchctl",["bootout",`${Q}/${z.label}`]);let Z=(Math.ceil(H.shutdownGraceMs/1000)+10)*1000;for(let q=0,B=100;;B=Math.min(B*2,2000)){if(J.command("/bin/launchctl",["bootstrap",Q,z.definition])===0)return!0;if(q>=Z)return!1;J.sleep(B),q+=B}}function TH(H,z,J){let Q=d(H,z,J);if(!Q)return null;let Z=z.insideService?.(Q.label)===!0;if(z.platform==="darwin"&&!Z)uz(Q.definition,z);let q=T(H,z,J);if(q&&Q.label!==q.label&&!Z)return b(q.definition,L(Q.definition,"utf8").replaceAll(Q.label,q.label)),Lz(H,z,q,Q),q;let B=z.platform==="darwin"&&Z,$;if(z.platform==="win32")Tz(Q,z,!Z),$=z.command("schtasks",["/Run","/TN",Q.label])===0;else if(B)$=z.command("/bin/launchctl",["kickstart","-k",`${F(z)}/${Q.label}`])===0;else if(z.platform==="darwin")$=Xz(H,Q,z);else z.command("systemctl",["--user","enable",`${Q.label}.service`]),$=z.command("systemctl",["--user","restart",`${Q.label}.service`])===0;if(!$)throw new M(`Could not restart the background service ${Q.label}.`,"worker_service_restart_failed");if(q&&Q.label===q.label)gz(H,z,J);return Q}function LH(H,z,J,Q){let Z=d(H,J,Q),q=T(z,J,Q);if(J.platform!=="darwin"||!Z||!q)return;let B=`<string>${D(Z.logs)}</string>`,$=L(Z.definition,"utf8");if($.includes(B))b(Z.definition,$.replaceAll(B,`<string>${D(q.logs)}</string>`))}function XH(H,z,J="serve"){let Q=Mz(H,z,J);for(let Z of Q){if(z.platform==="win32"){K(Z,z,z.insideService?.(Z.label,!1)!==!0);continue}if(z.platform==="darwin"){if(typeof z.uid==="number"&&z.uid>0)z.command("/bin/launchctl",["bootout",`gui/${z.uid}/${Z.label}`]);Y(Z.definition,{force:!0});continue}z.command("systemctl",["--user","disable","--now",`${Z.label}.service`]),Y(Z.definition,{force:!0}),z.command("systemctl",["--user","daemon-reload"])}return Q[0]??null}
105
+ export{l as Pd,P as Qd,yz as Rd,BH as Sd,M as Td,qH as Ud,jH as Vd,GH as Wd,jz as Xd,MH as Yd,YH as Zd,d as _d,gz as $d,DH as ae,UH as be,NH as ce,TH as de,LH as ee,XH as fe};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Be as LJ,Je as gJ,Ke as EJ,Le as VJ,pf as OJ}from"./vm-hands-entry-lite-zfwg7ehq.js";import{createHash as m,randomBytes as KJ}from"crypto";import{closeSync as MJ,fsyncSync as DJ,mkdirSync as oJ,openSync as qJ,renameSync as dJ,rmSync as iJ,statSync as _J,writeSync as xJ,constants as R}from"fs";import{join as a}from"path";var rJ=1;var n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function FJ(J){if(J.environment!==void 0||J.payload.environment!==void 0)throw new W("vm_hands_bind_invalid","bind carries a plaintext environment");if(J.payload.vm_hands_env_deferred===!0&&J.environment_sealed!==void 0)throw new W("vm_hands_bind_invalid","split bind carries an environment");return J.environment_sealed!==void 0}function jJ(J,Z){let{payload:z,authority: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 AJ(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"&&n.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:FJ(J)?J.environment_sealed:null,workspace_deferred:sJ(J)}}function sJ(J){let Z=J.payload[EJ];if(Z===void 0)return!1;if(Z!==!0||J.payload.vm_hands_env_deferred!==!0||J.environment_sealed!==void 0)throw new W("vm_hands_bind_invalid","a pre-bind must be environment-less");return!0}class W extends Error{code;constructor(J,Z){super(Z);this.code=J}}var y=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),b=(J)=>new Uint8Array(Buffer.from(J,"base64url"));function c(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return`[${J.map(c).join(",")}]`;return`{${Object.keys(J).sort().map((Z)=>`${JSON.stringify(Z)}:${c(J[Z])}`).join(",")}}`}async function DZ(J){let Z=await crypto.subtle.importKey("pkcs8",b(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),z=b(J.device_key.spki),Q=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),L=new Uint8Array(await crypto.subtle.exportKey("spki",Q.publicKey)),j=m("sha256").update(z).digest("base64url");return{signing:{privateKey:Z},agreement:Q,signingSpki:z,agreementSpki:L,fingerprint:j}}var aJ=4;class nJ{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;grants=new Map;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(!n.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 L=this.bound.get(J);if(!L)return!1;if(L.envInstalled)return!0;if(Date.now()>=Q||z?.aborted)return!1;await new Promise((j)=>setTimeout(j,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:rJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:y(this.keys.signingSpki),env_public_key:y(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:y(KJ(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(c(Z)));return{...Z,device_signature:y(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=y(KJ(32)),L=OJ({method:"GET",pathAndQuery:LJ,timestamp:z,nonce:Q,challenge:J,bodySha256:m("sha256").update("").digest("hex")}),j=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(L)));return{t:"hello",timestamp:z,nonce:Q,signature:y(tJ(j)),...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(!n.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(m("sha256").update(c({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>=aJ)throw new W("vm_hands_busy","every bind slot is held");if(this.grants.size)throw new W("vm_hands_busy","a bind waits for its workspace beside the setup");if(J.workspace_deferred&&(this.liveBindIds.length||this.commandsSinceVerified))throw new W("vm_hands_prebind_unsafe","a pre-bind needs a VM that served nothing since its last full kill");if(this.lastBrainGeneration.set(J.run_id,J.brain_generation),this.binding.set(J.bind_id,J.run_id),J.workspace_deferred){let z,Q,L=new Promise((j,U)=>{z=j,Q=U});L.catch(()=>{return}),this.grants.set(J.bind_id,{promise:L,resolve:z,reject:Q})}return this.exclusive(()=>this.setUp(J))}async setUp(J){let Z=[...this.bound.keys()],z=null,Q=!1,L=this.grants.get(J.bind_id);try{if(L&&(Z.length||this.commandsSinceVerified))throw new W("vm_hands_prebind_unsafe","a pre-bind needs a VM that served nothing since its last full kill");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:U,readyData:D}=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,...L?{workspaceGrant:L.promise}:{}}),_=this.hooks.restatLayout();this.hooks.verifyMounts?.();let A=null,q=null;if(J.env){let v=J.claim?.owner??{},V=jJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof v.device_id==="string"?v.device_id:"",rootId:J.claim?.root_id??""});this.commandsSinceVerified=!0,A=this.hooks.installEnvironment(J.bind_id,V),q=typeof V.snapshot_id==="string"&&V.snapshot_id?V.snapshot_id:null,z=this.writeJobEnvRootOnly(J.bind_id,V)}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:A!==null,rootId:J.claim?.root_id??"",envDirectory:z}),this.binding.delete(J.bind_id),this.grants.delete(J.bind_id),{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:j,snapshot_revision:A,snapshot_id:q,layout:_,...D?{ready_data:D}:{},policy_digest:m("sha256").update(c({hands_confinement:U.hands_confinement??null,browser_egress:U.browser_egress??null})).digest("hex")}}catch(j){if(z)GJ(z);if(Q){let D=[...this.bound.keys()];await this.hooks.killAndVerifyPayload({bindId:J.bind_id,keep:D,own:!0}).catch(()=>{this.unverified.add(J.bind_id)})}this.binding.delete(J.bind_id),this.grants.delete(J.bind_id);let U=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(U,"executor refused the bind")}}grantWorkspace(J){let Z=this.grants.get(J);if(!Z)throw new W("vm_hands_not_binding","no pre-bind waits for a workspace grant");Z.resolve()}abandonWorkspaceGrant(J){this.grants.get(J)?.reject(new W("vm_hands_bind_lost","the pre-bind ended before its workspace grant"))}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(!n.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=jJ(await this.openSealed(J.sealed,z),{runId:Z.runId,deviceId:J.deviceId,rootId:Z.rootId,snapshotId:J.snapshotId});this.commandsSinceVerified=!0;let L=this.hooks.installEnvironment(Z.bindId,Q);if(Z.envInstalled=!0,Z.envDirectory)GJ(Z.envDirectory);return Z.envDirectory=null,Z.envDirectory=this.writeJobEnvRootOnly(`${Z.bindId}-r${L}`,Q),{snapshot_id:J.snapshotId,installed_revision:L,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:m("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),this.abandonWorkspaceGrant(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((L)=>L!==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(L){throw this.unverified.add(J),L}if(!z.length)this.unverified.clear(),this.commandsSinceVerified=!1;if(Z?.envDirectory)GJ(Z.envDirectory);return{bind_id:Z?J:null,killed_verified:!0,shredded:!0,srt_fallbacks:z.length?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(J)}}async openSealed(J,Z){let z=()=>{throw new W("vm_hands_env_invalid","env did not decrypt")},Q=await crypto.subtle.importKey("spki",b(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(z),L=await crypto.subtle.deriveKey({name:"ECDH",public:Q},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),j=await crypto.subtle.decrypt({name:"AES-GCM",iv:b(J.iv),additionalData:new TextEncoder().encode(Z)},L,b(J.ct)).catch(z),U=JSON.parse(new TextDecoder().decode(j));if(!U||typeof U!=="object"||Array.isArray(U))throw new W("vm_hands_env_invalid","env not an object");return U}writeJobEnvRootOnly(J,Z){let z=a(this.options.envRoot,`bind-${J}`);oJ(z,{mode:448});let Q=_J(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 L=Z.variables&&typeof Z.variables==="object"?Z.variables:{},j=Object.entries(L).filter(([_,A])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(_)&&typeof A==="string").map(([_,A])=>`export ${_}='${String(A).replaceAll("'","'\\''")}'`).join(`
2
+ import{Cf as OJ,Oe as LJ,We as gJ,Xe as EJ,Ye as VJ}from"./vm-hands-entry-lite-5n4vsm6b.js";import{createHash as m,randomBytes as KJ}from"crypto";import{closeSync as MJ,fsyncSync as DJ,mkdirSync as oJ,openSync as qJ,renameSync as dJ,rmSync as iJ,statSync as _J,writeSync as xJ,constants as R}from"fs";import{join as a}from"path";var rJ=1;var n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function FJ(J){if(J.environment!==void 0||J.payload.environment!==void 0)throw new W("vm_hands_bind_invalid","bind carries a plaintext environment");if(J.payload.vm_hands_env_deferred===!0&&J.environment_sealed!==void 0)throw new W("vm_hands_bind_invalid","split bind carries an environment");return J.environment_sealed!==void 0}function jJ(J,Z){let{payload:z,authority: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 AJ(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"&&n.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:FJ(J)?J.environment_sealed:null,workspace_deferred:sJ(J)}}function sJ(J){let Z=J.payload[EJ];if(Z===void 0)return!1;if(Z!==!0||J.payload.vm_hands_env_deferred!==!0||J.environment_sealed!==void 0)throw new W("vm_hands_bind_invalid","a pre-bind must be environment-less");return!0}class W extends Error{code;constructor(J,Z){super(Z);this.code=J}}var y=(J)=>Buffer.from(J instanceof Uint8Array?J:new Uint8Array(J)).toString("base64url"),b=(J)=>new Uint8Array(Buffer.from(J,"base64url"));function c(J){if(J===null||typeof J!=="object")return JSON.stringify(J);if(Array.isArray(J))return`[${J.map(c).join(",")}]`;return`{${Object.keys(J).sort().map((Z)=>`${JSON.stringify(Z)}:${c(J[Z])}`).join(",")}}`}async function DZ(J){let Z=await crypto.subtle.importKey("pkcs8",b(J.device_key.pkcs8),{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),z=b(J.device_key.spki),Q=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!1,["deriveKey"]),L=new Uint8Array(await crypto.subtle.exportKey("spki",Q.publicKey)),j=m("sha256").update(z).digest("base64url");return{signing:{privateKey:Z},agreement:Q,signingSpki:z,agreementSpki:L,fingerprint:j}}var aJ=4;class nJ{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;grants=new Map;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(!n.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 L=this.bound.get(J);if(!L)return!1;if(L.envInstalled)return!0;if(Date.now()>=Q||z?.aborted)return!1;await new Promise((j)=>setTimeout(j,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:rJ,workspace_id:this.init.workspace_id,instance_generation:this.init.instance_generation,credential:this.init.credential,device_public_key:y(this.keys.signingSpki),env_public_key:y(this.keys.agreementSpki),key_fingerprint:this.keys.fingerprint,manifest_digest:this.init.manifest_digest,nonce:y(KJ(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(c(Z)));return{...Z,device_signature:y(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=y(KJ(32)),L=OJ({method:"GET",pathAndQuery:LJ,timestamp:z,nonce:Q,challenge:J,bodySha256:m("sha256").update("").digest("hex")}),j=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},this.keys.signing.privateKey,new Uint8Array(L)));return{t:"hello",timestamp:z,nonce:Q,signature:y(tJ(j)),...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(!n.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(m("sha256").update(c({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>=aJ)throw new W("vm_hands_busy","every bind slot is held");if(this.grants.size)throw new W("vm_hands_busy","a bind waits for its workspace beside the setup");if(J.workspace_deferred&&(this.liveBindIds.length||this.commandsSinceVerified))throw new W("vm_hands_prebind_unsafe","a pre-bind needs a VM that served nothing since its last full kill");if(this.lastBrainGeneration.set(J.run_id,J.brain_generation),this.binding.set(J.bind_id,J.run_id),J.workspace_deferred){let z,Q,L=new Promise((j,U)=>{z=j,Q=U});L.catch(()=>{return}),this.grants.set(J.bind_id,{promise:L,resolve:z,reject:Q})}return this.exclusive(()=>this.setUp(J))}async setUp(J){let Z=[...this.bound.keys()],z=null,Q=!1,L=this.grants.get(J.bind_id);try{if(L&&(Z.length||this.commandsSinceVerified))throw new W("vm_hands_prebind_unsafe","a pre-bind needs a VM that served nothing since its last full kill");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:U,readyData:D}=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,...L?{workspaceGrant:L.promise}:{}}),_=this.hooks.restatLayout();this.hooks.verifyMounts?.();let A=null,q=null;if(J.env){let v=J.claim?.owner??{},V=jJ(await this.openSealed(J.env,J.bind_id),{runId:J.run_id,deviceId:typeof v.device_id==="string"?v.device_id:"",rootId:J.claim?.root_id??""});this.commandsSinceVerified=!0,A=this.hooks.installEnvironment(J.bind_id,V),q=typeof V.snapshot_id==="string"&&V.snapshot_id?V.snapshot_id:null,z=this.writeJobEnvRootOnly(J.bind_id,V)}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:A!==null,rootId:J.claim?.root_id??"",envDirectory:z}),this.binding.delete(J.bind_id),this.grants.delete(J.bind_id),{bind_id:J.bind_id,attempt_id:J.attempt_id,attempt_token:J.attempt_token,launch_id:j,snapshot_revision:A,snapshot_id:q,layout:_,...D?{ready_data:D}:{},policy_digest:m("sha256").update(c({hands_confinement:U.hands_confinement??null,browser_egress:U.browser_egress??null})).digest("hex")}}catch(j){if(z)GJ(z);if(Q){let D=[...this.bound.keys()];await this.hooks.killAndVerifyPayload({bindId:J.bind_id,keep:D,own:!0}).catch(()=>{this.unverified.add(J.bind_id)})}this.binding.delete(J.bind_id),this.grants.delete(J.bind_id);let U=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(U,"executor refused the bind")}}grantWorkspace(J){let Z=this.grants.get(J);if(!Z)throw new W("vm_hands_not_binding","no pre-bind waits for a workspace grant");Z.resolve()}abandonWorkspaceGrant(J){this.grants.get(J)?.reject(new W("vm_hands_bind_lost","the pre-bind ended before its workspace grant"))}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(!n.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=jJ(await this.openSealed(J.sealed,z),{runId:Z.runId,deviceId:J.deviceId,rootId:Z.rootId,snapshotId:J.snapshotId});this.commandsSinceVerified=!0;let L=this.hooks.installEnvironment(Z.bindId,Q);if(Z.envInstalled=!0,Z.envDirectory)GJ(Z.envDirectory);return Z.envDirectory=null,Z.envDirectory=this.writeJobEnvRootOnly(`${Z.bindId}-r${L}`,Q),{snapshot_id:J.snapshotId,installed_revision:L,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:m("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),this.abandonWorkspaceGrant(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((L)=>L!==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(L){throw this.unverified.add(J),L}if(!z.length)this.unverified.clear(),this.commandsSinceVerified=!1;if(Z?.envDirectory)GJ(Z.envDirectory);return{bind_id:Z?J:null,killed_verified:!0,shredded:!0,srt_fallbacks:z.length?null:this.hooks.takeSrtFallbacks?.()??null}}finally{this.unbinding.delete(J)}}async openSealed(J,Z){let z=()=>{throw new W("vm_hands_env_invalid","env did not decrypt")},Q=await crypto.subtle.importKey("spki",b(J.epk),{name:"ECDH",namedCurve:"P-256"},!1,[]).catch(z),L=await crypto.subtle.deriveKey({name:"ECDH",public:Q},this.keys.agreement.privateKey,{name:"AES-GCM",length:256},!1,["decrypt"]),j=await crypto.subtle.decrypt({name:"AES-GCM",iv:b(J.iv),additionalData:new TextEncoder().encode(Z)},L,b(J.ct)).catch(z),U=JSON.parse(new TextDecoder().decode(j));if(!U||typeof U!=="object"||Array.isArray(U))throw new W("vm_hands_env_invalid","env not an object");return U}writeJobEnvRootOnly(J,Z){let z=a(this.options.envRoot,`bind-${J}`);oJ(z,{mode:448});let Q=_J(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 L=Z.variables&&typeof Z.variables==="object"?Z.variables:{},j=Object.entries(L).filter(([_,A])=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(_)&&typeof A==="string").map(([_,A])=>`export ${_}='${String(A).replaceAll("'","'\\''")}'`).join(`
3
3
  `)+`
4
4
  `,U=a(z,`.job.env.${KJ(8).toString("hex")}`),D=qJ(U,R.O_WRONLY|R.O_CREAT|R.O_EXCL|R.O_NOFOLLOW,384);try{xJ(D,j),DJ(D)}finally{MJ(D)}return dJ(U,a(z,"job.env")),z}}function GJ(J){try{let Z=a(J,"job.env"),z=_J(Z).size,Q=qJ(Z,R.O_WRONLY|R.O_NOFOLLOW);try{xJ(Q,Buffer.alloc(z)),DJ(Q)}finally{MJ(Q)}}catch{}iJ(J,{recursive:!0,force:!0})}function tJ(J){if(J.length!==64)throw new W("vm_hands_signature_invalid","unexpected ECDSA signature length");let Z=(L)=>{let j=0;while(j<L.length-1&&L[j]===0)j++;let U=L.subarray(j),D=U[0]&128?Uint8Array.of(0,...U):U;return Uint8Array.of(2,D.length,...D)},z=Z(J.subarray(0,32)),Q=Z(J.subarray(32));return Uint8Array.of(48,z.length+Q.length,...z,...Q)}import{randomUUID as eJ}from"crypto";var JZ="/app/local-runtime/session?register=vm_hands_v1",ZZ="/app/local-runtime",TJ=25000,wJ=20000,$Z=1e4,vJ=5000,hJ=new Set(["pty.start","jobs.control","preview.serve.v1","display.stream.v1"]),WJ=75000,zZ=2000,QZ=1e4,XZ=new Set(["vm_hands_no_register","vm_hands_register_failed"]),YZ=3,KZ=20000,GZ=250,FZ=2000;function HJ(J){let Z=Math.min(GZ*2**(J-1),FZ);return Math.round(Z/2+Math.random()*Z/2)}var WZ=5000;function NZ(J){return J>=500||J===408||J===429}var t=20000;function SJ(J,Z){return typeof J==="string"&&/^[A-Za-z0-9._:-]{1,160}$/.test(J)?J:Z}class g extends Error{}var PZ=64;async function IJ(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,vJ))])}async function UZ(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,vJ))]);return Z.length}async function p(J,Z,z){return await IJ(J,z),Z.unbind(z)}function e(J){for(let Z of J.outbox?.splice(0)??[])Z.reject(Error("vm_hands_attempt_ended"))}var kJ=15000,CZ=1e4,BZ=1000;async function wZ(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??(()=>{}),L=async(D)=>{for(let[_,A]of[...z.turns]){z.turns.delete(_),J.onTurn?.(_,null),e(A);let q=await p(z,J.agent,_).catch(()=>null);if(q)z.receipts.push({turn:A,failure:"vm_hands_bind_lost",unbound:q});Q("vm_hands.bound_dropped",{reason:D})}},j=0,U=0;try{for(let D=0;!J.signal.aborted;D++){let _=await jZ(J,z).catch((q)=>{if(q instanceof W&&z.deviceId===null&&q.code==="vm_hands_no_session"&&Date.now()-Z<QZ)return{closeCode:0,closeReason:"vm_hands_no_session"};if(q instanceof W&&z.deviceId===null&&XZ.has(q.code)&&j<YZ&&Date.now()-Z<KZ)return j++,U=HJ(j),Q("vm_hands.register_retry",{attempt:j,code:q.code,delay_ms:U}),{closeCode:0,closeReason:"vm_hands_register_retry"};if(q instanceof W&&z.deviceId===null)throw q;return{closeCode:0,closeReason:q instanceof Error?q.message:String(q)}});if(Q("vm_hands.session_closed",{close_code:_.closeCode,reason:_.closeReason.slice(0,120),registered:z.deviceId!==null}),_.closeCode===4401||z.attest==="refused")return;if(J.signal.aborted)return;if(z.turns.size&&Date.now()-z.lostAt>=WJ)await L("reconnect_deadline");if(z.served)z.served=!1,D=0;let A=_.closeReason==="drain_reconnect"?0:_.closeReason==="vm_hands_register_retry"?U:_.closeReason==="vm_hands_no_session"?Math.min(250*2**Math.min(D,5),2000):z.turns.size?Math.min(250*2**Math.min(D,5),5000,Math.max(0,z.lostAt+WJ-Date.now())):Math.min(500*2**D,30000);if(await new Promise((q)=>setTimeout(q,A)),z.turns.size&&Date.now()-z.lostAt>=WJ)await L("reconnect_deadline")}}finally{await L("session_ended")}}async function jZ(J,Z){let z=Z.deviceId,Q=J.log??(()=>{}),L=z?`/app/local-runtime/session?device_id=${encodeURIComponent(z)}`:JZ,j=`${J.apiOrigin.replace(/^http/,"ws")}${L}`,U=new WebSocket(j),D=0,_="",A=new Map,q=[],v=null,V=new Promise(($)=>{U.onclose=(K)=>{D=K.code,_=K.reason;for(let X of A.values())X.reject(new g(`session closed ${K.code}`));for(let X of Z.attestWaiters.splice(0))X(!1);A.clear(),$()}});U.onmessage=($)=>{let K;try{K=JSON.parse(String($.data))}catch{U.close(4400);return}if(K.t==="res"){let X=K;A.get(X.id)?.resolve({status:X.status,body:X.body}),A.delete(X.id);return}if(K.t==="reconnect"){let X=Math.max(0,Math.min(Number(K.after_ms)||0,BZ));Q("vm_hands.drain_reconnect",{after_ms:X}),setTimeout(()=>{try{U.close(4001,"drain_reconnect")}catch{}},X).unref?.();return}if(!v?.(K))q.push(K)};let l=($,K)=>new Promise((X,F)=>{let P=q.findIndex((B)=>$.includes(B.t));if(P>=0){X(q.splice(P,1)[0]);return}let C=setTimeout(()=>{v=null,F(new W("vm_hands_no_register",`no ${$.join("/")} in ${K} ms`))},K);v=(B)=>{if(!$.includes(B.t))return!1;return clearTimeout(C),v=null,X(B),!0}}),u=($)=>U.send(JSON.stringify($)),S=($,K)=>new Promise((X,F)=>{if(U.readyState!==WebSocket.OPEN){F(new g("session closed"));return}let P=eJ(),C=typeof K.wait_ms==="number"?K.wait_ms:0,B=setTimeout(()=>{if(!A.delete(P))return;F(new g(`no answer to ${$.split("/").pop()} in ${C+kJ} ms`)),U.close(4000,"request_timeout")},C+kJ);A.set(P,{reject:(Y)=>{clearTimeout(B),F(Y)},resolve:({status:Y,body:G})=>{clearTimeout(B);let N=null;try{N=G?JSON.parse(G):null}catch{}X({status:Y,json:N})}}),u({t:"req",id:P,path:`${ZZ}${$}`,body:JSON.stringify(K)})}),NJ=()=>U.close(1001,"stopping");J.signal.addEventListener("abort",NJ,{once:!0});let JJ,o=new Map,d=new Map,ZJ=!1,$J=new Set,zJ=new Set,QJ=Promise.resolve(),i=!1;try{await new Promise((Y,G)=>{let N=setTimeout(()=>G(Error("session open timeout")),CZ);U.onopen=()=>{clearTimeout(N),Q("vm_hands.ws_open",{}),Y()},U.onerror=()=>{clearTimeout(N),G(Error("session socket error"))}});let $=await l(["challenge"],5000);Q("vm_hands.challenge",{});let K=[],X=null,F;if(z){u(await J.agent.helloFrame($.challenge,Z.connection));let Y=await l(["ready"],1e4);if(typeof Y.vm_hands_connection==="string")Z.connection=Y.vm_hands_connection;if(F={device_id:z,...Y.cadence?{cadence:Y.cadence}:{}},typeof Y.vm_hands_probe_script==="string"){if(X=Y.vm_hands_probe_script,i=!0,J.agent.phase==="registered"&&!Z.turns.size)Z.attest="pending"}Z.served=!0,Q("vm_hands.reconnected",{device_id:z});let G=Array.isArray(Y.vm_hands_binds)?Y.vm_hands_binds:Y.vm_hands_bind?[Y.vm_hands_bind]:[];for(let[N,M]of[...Z.turns]){if(G.some((T)=>T&&T.operation_id===M.claim.operation_id&&T.attempt_id===M.claim.attempt_id)){K.push(M),Q("vm_hands.bound_resumed",{operation_id:M.claim.operation_id});continue}Z.turns.delete(N),J.onTurn?.(N,null),e(M);let x=await p(Z,J.agent,N).catch(()=>null);if(x)Z.receipts.push({turn:M,failure:"vm_hands_bind_lost",unbound:x});Q("vm_hands.bound_dropped",{reason:"not_named_on_reconnect"})}}else{u(await J.agent.registerFrame($.challenge)),Q("vm_hands.register_sent",{});let Y=await Promise.race([l(["registered","register_refused"],1e4),V.then(()=>{throw new W(_==="register_failed"?"vm_hands_register_failed":"vm_hands_register_closed","session closed before the register was answered")})]);if(Y.t==="register_refused")throw new W(Y.code,"register refused");J.agent.registered();let G=Y;if(F=G,Z.deviceId=G.device_id,typeof G.vm_hands_connection==="string")Z.connection=G.vm_hands_connection;if(typeof G.vm_hands_probe_script==="string"){if(X=G.vm_hands_probe_script,i=!0,J.agent.phase==="registered"&&!Z.turns.size)Z.attest="pending"}Z.served=!0,Q("vm_hands.registered",{device_id:F.device_id})}let P=async()=>{let Y=await S("/heartbeat",await J.heartbeat());if(Y.status>=300)throw Error(`heartbeat ${Y.status}`)};await P();let C=F.cadence?.presence_interval_ms??30000;if(JJ=setInterval(()=>{P().catch(()=>U.close())},C),X&&Z.attest!=="accepted"&&J.agent.phase==="registered"&&!Z.turns.size)RJ(X,$.challenge);let B=(Y,G)=>{d.set(Y,G().catch(async(N)=>{if(await PJ(N,Y),N instanceof g)U.close();else await XJ().catch(()=>{return})}).finally(()=>{d.delete(Y)}))};try{await XJ();for(let Y of K)Y.flush=()=>UJ(Y),Y.flush(),B(Y.claim.attempt_id,()=>CJ(Y));while(!J.signal.aborted&&U.readyState===WebSocket.OPEN){let Y=await S("/operations/claim",{wait_ms:Math.min(F.cadence?.claim_wait_ms??TJ,TJ)});if(Y.status===204||!Y.json)continue;if(Y.status>=300)throw Error(`claim ${Y.status}`);let G=Y.json;if(G.capability==="hands.connect"){if(d.has(G.attempt_id)){h({claim:G,eventSeq:0}).complete("failed",{error_code:"vm_hands_busy"}).catch(()=>{return});continue}B(G.attempt_id,()=>fJ(G))}else bJ(G).catch(()=>{return})}}catch(Y){await PJ(Y,null)}}finally{if(JJ)clearInterval(JJ);J.signal.removeEventListener("abort",NJ);for(let $ of Z.turns.values())$.flush=null;U.close(),await V,await Promise.all([...d.values()]);for(let $ of J.agent.liveBindIds){if(Z.turns.has($))continue;let K=await p(Z,J.agent,$).catch(()=>null),X=o.get($);if(K&&X)Z.receipts.push({turn:{...X,eventSeq:X.eventSeq+1},failure:"vm_hands_bind_lost",unbound:K});Q("vm_hands.bound_dropped",{reason:"bound_after_loss"})}for(let $ of $J)$.abort()}return{closeCode:D,closeReason:_};async function PJ($,K){if($ instanceof g){if(!ZJ&&Z.turns.size)Z.lostAt=Date.now();ZJ=!0}else{let X=K!==null?[K]:[...new Set([...Z.turns.keys(),...J.agent.liveBindIds])];if(K===null)ZJ=!0;for(let F of X){let P=Z.turns.get(F);if(Z.turns.delete(F),P)e(P),J.onTurn?.(F,null);if(J.agent.liveBindIds.includes(F)){let C=await p(Z,J.agent,F).catch(()=>null),B=o.get(F)??P;if(C&&B)Z.receipts.push({turn:{...B,eventSeq:B.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 h($){let K=$.claim,X={attempt_id:K.attempt_id,attempt_token:K.attempt_token},F=encodeURIComponent(K.operation_id);return{fence:X,op:F,complete:(C,B={})=>S(`/operations/${F}/complete`,{...X,status:C,...B}),emit:(C,B)=>{let Y=($.chain??Promise.resolve()).catch(()=>{return}).then(()=>P(C,B));return $.chain=Y,Y}};async function P(C,B){let Y=$.eventSeq,G=(T)=>S(`/operations/${F}/events`,{...X,event_seq_start:T,events:[{kind:C,payload:{sequence:T,capability:String(K.capability??"hands.connect"),data:B}}]}),N=Y,M=await G(N),x=M.status===409?M.json?.expected_event_seq:void 0;if(typeof x==="number"&&x===Y+1)M={status:200,json:{duplicate:!0}};else if(typeof x==="number"&&x>=0&&x!==Y)N=x,M=await G(N);if(M.status<300)$.eventSeq=N+1;return M}}function yJ($){return(K,X)=>new Promise((F,P)=>{if(Z.turns.get($.claim.attempt_id)!==$){P(Error("vm_hands_attempt_ended"));return}if($.outbox??=[],$.outbox.length>=PZ){P(Error("vm_hands_outbox_full"));return}$.outbox.push({kind:K,data:X,resolve:F,reject:P}),$.flush?.()})}function UJ($){if(zJ.has($))return;zJ.add($),(async()=>{try{while($.outbox?.length&&Z.turns.get($.claim.attempt_id)===$&&U.readyState===WebSocket.OPEN){let K=$.outbox[0],X;try{X=await h($).emit(K.kind,K.data)}catch(F){if(F instanceof g)return;X={status:500}}if($.outbox.shift(),X.status<300)K.resolve();else K.reject(Error(`${K.kind} refused ${X.status}`))}}finally{zJ.delete($)}})()}async function RJ($,K){try{let X=await J.agent.attestFrame($,K);if(U.readyState!==WebSocket.OPEN)return;u(X);let F=await l(["attested","attest_refused"],15000);Z.attest=F.t==="attested"?"accepted":"refused";for(let P of Z.attestWaiters.splice(0))P(Z.attest==="accepted");if(Q("vm_hands.attest",{result:Z.attest,exit_code:X.exit_code,...F.t==="attest_refused"?{code:String(F.code??"")}:{}}),Z.attest==="refused")U.close(4401,"attest_refused")}catch(X){Q("vm_hands.attest_failed",{code:X instanceof W?X.code:"probe_error"});for(let F of Z.attestWaiters.splice(0))F(!1);if(Z.attest!=="accepted")U.close(4000,"attest_unanswered")}}async function fJ($){let K=i&&Z.attest==="pending",X=$.vm_hands_attest,F=X;if(Z.attest==="refused"){Q("vm_hands.claim_attest_refused",{said:typeof X==="string"?X.slice(0,16):typeof X,local:Z.attest}),await h({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(F==="accepted"){if(!K&&Z.attest!=="accepted"){Z.attest="accepted";for(let E of Z.attestWaiters.splice(0))E(!0)}}else if(F!=="pending"||!K&&Z.attest!=="accepted"){Q("vm_hands.claim_attest_refused",{said:typeof X==="string"?X.slice(0,16):typeof X,local:Z.attest}),await h({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}if(Z.attest!=="accepted"){let E=Date.parse($.lease_until)-Date.now()-5000,k=Math.max(0,Math.min(t,Number.isFinite(E)?E:t));if(!await new Promise((s)=>{let lJ=setTimeout(()=>s(!1),k);Z.attestWaiters.push((uJ)=>{clearTimeout(lJ),s(uJ)})})){await h({claim:$,eventSeq:0}).complete("failed",{error_code:"vm_hands_unattested"}).catch(()=>{return});return}}let P={claim:$,eventSeq:0},{complete:C,emit:B}=h(P),Y;try{if($.capability!=="hands.connect")throw new W("vm_hands_bind_invalid","not hands.connect");Y=!FJ($)}catch(E){Q("vm_hands.bind_refused",{code:E instanceof W?E.code:"unexpected"}),await C("failed",{error_code:E instanceof W?E.code:"vm_hands_bind_invalid"});return}let G,N=null,M=!1;Z.bindsStarting++;try{let E=await UZ(Z);if(E)Q("vm_hands.person_terminals_closed",{count:E});let k=AJ($),r=J.agent.bind(k);if(k.workspace_deferred)M=!0,N=mJ(P,()=>M);G=await r}catch(E){Q("vm_hands.bind_refused",{code:E instanceof W?E.code:"unexpected"}),await C("failed",{error_code:E instanceof W?E.code:"vm_hands_bind_failed"});return}finally{M=!1,Z.bindsStarting--}let x=N?await N:-1,T={...G.ready_data??J.readyData({launchId:G.launch_id,claim:$})};if(Y)delete T.environment_installed;let YJ=!Y&&G.snapshot_revision!==null&&G.snapshot_id!==null?{environment_installed:{snapshot_id:G.snapshot_id,installed_revision:G.snapshot_revision}}:{};o.set($.attempt_id,{claim:$,launchId:G.launch_id,readyData:T,eventSeq:P.eventSeq,ackSeq:-1});let H={...T,...YJ,vm_hands:{layout:G.layout,policy_digest:G.policy_digest,launch_id:G.launch_id}},f=Date.now()+WZ,I=1,O=await B("hands.ready",H);while(NZ(O.status)&&!J.signal.aborted){let E=HJ(I);if(Date.now()+E>=f)break;await new Promise((k)=>setTimeout(k,E)),I++,O=await B("hands.ready",H)}if(I>1)Q("vm_hands.ready_retried",{attempts:I,status_class:`${Math.floor(O.status/100)}xx`});if(o.delete($.attempt_id),O.status>=300){await IJ(Z,$.attempt_id),await J.agent.boundRefused($.attempt_id),await C("failed",{error_code:SJ(O.json?.error,"vm_hands_probe_failed")});return}let w={claim:$,launchId:G.launch_id,readyData:T,eventSeq:P.eventSeq,ackSeq:x};Z.turns.set($.attempt_id,w),w.flush=()=>UJ(w),J.onTurn?.($.attempt_id,yJ(w)),await CJ(w)}async function mJ($,K){let{fence:X,op:F}=h($),P=$.claim.attempt_id,C=-1;try{for(;;){let B=await S(`/operations/${F}/heartbeat`,{...X,control_ack_seq:C,wait_ms:wJ});if(!K())return C;if(B.status>=300)return J.agent.abandonWorkspaceGrant(P),C;let Y=(B.json?.controls??[]).slice().sort((G,N)=>G.seq-N.seq);for(let G of Y){if(G.seq<=C)continue;if(C=G.seq,G.kind===VJ)return Q("vm_hands.workspace_granted",{}),J.agent.grantWorkspace(P),C;return Q("vm_hands.workspace_grant_abandoned",{control:/^[a-z][a-z0-9._-]{0,63}$/.test(G.kind)?G.kind:"other"}),J.agent.abandonWorkspaceGrant(P),C}}}catch{return J.agent.abandonWorkspaceGrant(P),C}}async function CJ($){let{fence:K,op:X}=h($),F=null,P=null,C=J.agent.executorExited($.claim.attempt_id).then((B)=>{return P=B,null});J:for(;;){let B=await Promise.race([C,S(`/operations/${X}/heartbeat`,{...K,control_ack_seq:$.ackSeq,wait_ms:wJ})]);if(!B){F="vm_hands_executor_exited",Q("vm_hands.executor_exited",{reason:P});break}if(B.status>=300)break;let Y=(B.json?.controls??[]).slice().sort((G,N)=>G.seq-N.seq);for(let G of Y){if(G.seq<=$.ackSeq)continue;if(G.kind==="operation.cancel"||G.kind==="cancel"){$.ackSeq=G.seq;break J}if(G.kind===gJ)try{await pJ($,G.payload??{})}catch(N){if(N instanceof g)throw N;F=N instanceof W?N.code:"environment_unavailable";let M=N&&typeof N==="object"&&"code"in N&&typeof N.code==="string"&&/^[a-z][a-z0-9_]{2,63}$/.test(N.code)?N.code:null;Q("vm_hands.environment_refused",{code:F,cause:M});break J}$.ackSeq=G.seq}}await cJ($,F)}async function bJ($){let K=$,X={claim:K,eventSeq:0},{complete:F,emit:P,fence:C,op:B}={...h(X)},Y=$.vm_hands_origin==="person"?"person":"model",G=String($.capability??"");if(!J.executeOp){await F("failed",{error_code:"vm_hands_op_unsupported"});return}if($.vm_hands_attest==="accepted"&&Z.attest==="pending"&&!(i&&Z.attest==="pending")){Z.attest="accepted";for(let O of Z.attestWaiters.splice(0))O(!0)}if(Z.attest!=="accepted"){let O=Date.parse(String($.lease_until??""))-Date.now()-5000,w=Z.attest==="refused"?0:Math.max(0,Math.min(t,Number.isFinite(O)?O:t));if(!(w>0&&await new Promise((k)=>{let r=setTimeout(()=>k(!1),w);Z.attestWaiters.push((s)=>{clearTimeout(r),k(s)})}))){await F("failed",{error_code:"vm_hands_unattested"});return}}let N=J.agent.bindIdForRun(K.run_id);if(Y==="model"&&N===null){await F("failed",{error_code:"vm_hands_not_bound"});return}let M=G==="pty.start"&&Y==="person"&&!$.authority;if(M&&(J.agent.liveBindIds.length>0||Z.bindsStarting>0)){await F("failed",{error_code:"vm_hands_bound"});return}if(hJ.has(G)&&!M&&J.agent.liveBindIds.length===0){await F("failed",{error_code:"vm_hands_not_bound"});return}if(Y==="model"&&N||hJ.has(G)&&!M)J.agent.opServed();let x=new AbortController;$J.add(x);let T,YJ=new Promise((O)=>{T=O}),H={abort:x,settled:YJ};if(M)Z.personTerminals.add(H);if(Y==="model"&&N){let O=Z.modelOps.get(N)??new Set;O.add(H),Z.modelOps.set(N,O),await J.agent.environmentInstalled(N,zZ,x.signal)}let f=-1,I=setInterval(()=>{S(`/operations/${B}/heartbeat`,{...C,control_ack_seq:f,wait_ms:0}).then((O)=>{if(O.status>=300){x.abort();return}let w=O.json?.controls??[];for(let E of w)if(f=Math.max(f,E.seq),E.kind==="operation.cancel"||E.kind==="cancel")x.abort()},()=>x.abort())},$Z);try{let O=await J.executeOp({kind:Y,claim:$,...Y==="model"&&N?{bindId:N}:{},signal:x.signal,emit:async(E)=>{await P(E.kind,E.data??{})}}),w=await F(O.status,{...O.result?{result:O.result}:{},...O.error_code?{error_code:SJ(O.error_code,"vm_hands_op_failed")}:{}});Q("vm_hands.op",{capability:G,kind:Y,status:O.status,code:O.error_code??null,...w.status>=300?{complete_status:w.status,complete_error:String(w.json?.error??"").slice(0,64)}:{}})}finally{if(clearInterval(I),$J.delete(x),N)Z.modelOps.get(N)?.delete(H);Z.personTerminals.delete(H),T()}}async function cJ($,K){let X=$.claim.attempt_id;if(Z.turns.get(X)===$)Z.turns.delete(X);J.onTurn?.(X,null),e($);let F=await p(Z,J.agent,X);Z.receipts.push({turn:$,failure:K,unbound:F}),await XJ()}function XJ(){return QJ=QJ.then(BJ,BJ),QJ}async function BJ(){while(Z.receipts.length){let{turn:$,failure:K,unbound:X}=Z.receipts[0],{complete:F,emit:P}=h($);try{if(await P("hands.stopped",{...$.readyData,reason_code:K?"failed":"cancelled",killed_verified:X.killed_verified,shredded:X.shredded,...X.srt_fallbacks?{vm_hands_srt_fallbacks:X.srt_fallbacks}:{}}),K)await F("failed",{error_code:K});else await F("cancelled",{error_code:"driver_stopped"})}catch(C){if(C instanceof g)return}Z.receipts.shift()}}async function pJ($,K){let{fence:X,op:F}=h($),P=K.snapshot_id;if(K.version!==1||typeof P!=="string"||Object.keys(K).length!==2)throw new W("vm_hands_env_invalid","invalid environment delivery");let C=await S(`/operations/${F}/environment`,{...X,snapshot_id:P}),B=C.json?.environment_sealed;if(C.status!==200||!B||C.json?.payload!==void 0)throw new W("vm_hands_env_invalid","environment not delivered sealed");let Y=await J.agent.deliverEnvironment({attemptId:$.claim.attempt_id,snapshotId:P,deviceId:Z.deviceId??"",sealed:B});if((await S(`/operations/${F}/environment-ack`,{...X,...Y})).status>=300)throw new W("vm_hands_env_ack_refused","environment ack refused")}}
5
5
  export{DZ as xa,nJ as ya,wZ as za};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{ni as m,oi as y}from"./vm-hands-entry-lite-r6pap1kh.js";import{basename as UJ}from"path";var f=["production","staging"],DJ="https://api.reasonmachines.com",EJ="https://staging-api.reasonmachines.com";var u={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},GJ=new Set(["ara-staging","reason-staging"]);function mJ(J={}){let Q=m(J.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(Q){if(f.includes(Q))return Q;throw Error(`Unknown Reason CLI channel: ${Q}`)}let V=UJ(J.executablePath??process.execPath).toLowerCase();return GJ.has(V)?"staging":"production"}function yJ(J,Q){return{...J,...y("REASON_CLI_CHANNEL",Q)}}function j(J){return J==="staging"?EJ:DJ}function sJ(J){return`${j(J)}/mcp/ara`}var s={production:["https://api.ara.so",u.production.api],staging:["https://api-staging.ara.so",u.staging.api]};function p(J){let Q;try{Q=new URL(J).origin}catch{return J}let V=f.find((Z)=>s[Z].includes(Q));return V?j(V):Q}function cJ(J,Q){return J===Q||p(J)===p(Q)}function lJ(J,Q){return f.some((V)=>s[V].includes(J)&&Q===j(V))}function iJ(J,Q){try{let V=new URL(Q);return!V.username&&!V.password&&(V.origin===j(J)||V.origin===u[J].api)}catch{return!1}}function rJ(J){try{let Q=new URL(J).hostname.replace(/^\[|\]$/g,"").toLowerCase();return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}import{randomBytes as VJ}from"crypto";import{chmodSync as ZJ,closeSync as a,constants as _J,linkSync as $J,lstatSync as k,mkdirSync as XJ,openSync as kJ,readdirSync as P,readFileSync as t,readlinkSync as R,renameSync as _,rmdirSync as KJ,symlinkSync as A,unlinkSync as U}from"fs";import{createRequire as CJ}from"module";import{constants as FJ}from"os";import{basename as O,join as K,sep as OJ}from"path";import{existsSync as I,lstatSync as l,readdirSync as PJ,readFileSync as HJ,readlinkSync as RJ,realpathSync as TJ}from"fs";import{join as L,sep as AJ}from"path";function i(J,...Q){let V=L(J,"ara"),Z=L(J,"reason");if(!r(V))return L(Z,...Q);if(!I(Z))return L(V,...Q);return I(L(V,...Q))&&!I(L(Z,...Q))?L(V,...Q):L(Z,...Q)}function r(J){try{let Q=l(J);if(!Q.isSymbolicLink())return Q.isDirectory();return RJ(J)!=="reason"&&I(J)}catch{return!1}}function o(J,Q=[]){if(!r(J))return!1;let V;try{V=[J,...PJ(J,{withFileTypes:!0}).filter((Z)=>Z.isDirectory()).map((Z)=>L(J,Z.name))]}catch{return!1}return V.some((Z)=>["connect","connect-once"].filter(($)=>!Q.includes(L(Z,$))).some(($)=>{let M=L(Z,$,"worker.json");try{l(M)}catch{return!1}try{let z=JSON.parse(HJ(M,"utf8"))?.stateDirectory;if(typeof z!=="string")return!0;let q=(X,B)=>X===B||X.startsWith(B+AJ);return q(z,J)||q(c(z),c(J))}catch{return!0}}))}function c(J){try{return TJ(J)}catch{return J}}var S=new Set(["credentials.json","local-device.json","local-device.revoked.json","local-device.auth-migration.json","local-device.json.registration-pending.json","local-daemon.json","local-daemon.json.workspaces.json","local-root-fingerprint-key.json","instances","workspaces"]),x=new Set(["local-device.proxy.json"]),bJ=new Set(["local-device.key","local-device.binding"]),n=new Map;function jJ(J,Q,V){let Z=K(J,"ara");if(/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(J))return{state:Y(Z)?.isDirectory()?"kept":"absent"};return zJ(Z,K(J,"reason"),{linkAlways:!0,kept:($)=>o($,V??[]),native:Q===void 0?LJ:()=>Q},V!==void 0)}function qQ(J,...Q){return jJ(J),i(J,...Q)}function BQ(J,Q=process.platform){let V=K(J,"Library","Logs");if(Q==="darwin")for(let Z of[""," Staging"," Development"])zJ(K(V,`Ara${Z}`),K(V,`Reason${Z}`),{linkAlways:!1,kept:()=>!1,native:LJ});return K(V,"Reason")}var MJ="config_rename_unavailable:busy";function zJ(J,Q,V,Z=!1){let $=Z?void 0:n.get(J);if($)return $;let M;try{M=IJ(J,Q,V)}catch(z){let q=`config_rename_unavailable:${G(z)??"failed"}`;try{return{state:Y(J)?.isDirectory()?"kept":"absent",problem:q}}catch{return{state:"kept",problem:q}}}if(!(M.state==="absent"&&V.linkAlways)&&M.problem!==MJ&&!(M.state==="kept"&&!M.problem))n.set(J,M);return M}function IJ(J,Q,V){vJ(Q,V.native);let Z=!1;for(let $=0;$<8;$+=1){let M=Y(J);if(M?.isSymbolicLink())return R(J)===O(Q)?{state:Z?"renamed":"linked"}:{state:"kept"};if(!M){if(v(Q))W(()=>U(Q),"ENOENT");if(!(Z||V.linkAlways)||!T(Q))return{state:"absent"};let X=F(Q,"link");A(O(Q),X);try{W(()=>_(X,J),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{W(()=>U(X),"ENOENT")}continue}if(!M.isDirectory())return{state:"absent"};if(V.kept(J))return e(Q),{state:"kept"};let z=V.native();if(!z)return e(Q),{state:"kept",problem:"config_rename_unavailable:no_native"};let q=SJ(z,J);if(!q)return{state:"kept",problem:MJ};try{if(k(J).isSymbolicLink())continue;let X=NJ(z,J,Q);if(X)return{state:"kept",problem:X};Z=!0}finally{q()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function NJ(J,Q,V){let Z=Y(V);if(!Z||v(V)){if(!Z)A(O(V),V);try{J.exchange(Q,V)}catch(X){if(v(V))W(()=>U(V),"ENOENT");return`config_rename_unavailable:${G(X)??"exchange_failed"}`}return null}if(!Z.isDirectory())return"config_rename_unavailable:ENOTDIR";if(Z.dev!==k(Q).dev)return"config_rename_unavailable:EXDEV";let $=[F(V,"probe"),F(V,"probe")];try{A("a",$[0]),A("b",$[1]),J.exchange($[0],$[1])}catch(X){return`config_rename_unavailable:${G(X)??"exchange_failed"}`}finally{for(let X of $)W(()=>U(X),"ENOENT")}let M=wJ(V);for(let X of bJ){let B=Y(K(V,X)),w=Y(K(Q,X));if(B&&w&&B.ino!==w.ino)XJ(`${M}-replaced`,{mode:448,recursive:!0}),_(K(V,X),K(`${M}-replaced`,X))}let z={linked:new Map,unitsKept:new Set};qJ(Q,V,"",z);let q=F(V,"rename");A(O(V),q);try{J.exchange(Q,q)}catch(X){return W(()=>U(q),"ENOENT"),`config_rename_unavailable:${G(X)??"exchange_failed"}`}return BJ(q,V,z,M),null}function g(J){return J===""||!J.includes(OJ)}function qJ(J,Q,V,Z){let $=g(V)&&N(K(Q,V),K(J,V));if($)Z.unitsKept.add(V);for(let M of P(K(J,V))){if($&&(S.has(M)||x.has(M)))continue;let z=K(V,M),q=K(J,z),X=K(Q,z),B=Y(q);if(!B)continue;let w=Y(X);if(B.isDirectory()){if(!w)W(()=>XJ(X,{mode:B.mode&4095}),"EEXIST"),ZJ(X,B.mode&4095);if(T(X))qJ(J,Q,z,Z)}else if(!w){if(B.isSymbolicLink())W(()=>A(R(q),X),"EEXIST");else if(W(()=>$J(q,X),"EEXIST","ENOENT"))Z.linked.set(z,B.ino)}}}function vJ(J,Q){let V;try{if(!T(J))return;V=P(J)}catch{return}for(let Z of V){let $=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(Z);if(!$)continue;let M=K(J,Z),z=Y(M);if(!z)continue;if(!z.isDirectory()){if(!JJ(Number($[2])))W(()=>U(M),"ENOENT");continue}let q=Q(),X=null;if(q){try{X=q.lock(M)}catch{continue}if(!X)continue}else if(JJ(Number($[2])))continue;try{let B=F(J,"claim");if(W(()=>_(M,B),"ENOENT"))BJ(B,J,null,wJ(J))}finally{X?.()}}}function BJ(J,Q,V,Z){for(let[$,M]of V?.linked??[])if(!Y(K(J,$))&&Y(K(Q,$))?.ino===M)W(()=>U(K(Q,$)),"ENOENT");if(YJ(J,Q,"",V),W(()=>KJ(J),"ENOTEMPTY","EEXIST"))return;_(J,Z),ZJ(Z,448)}function YJ(J,Q,V,Z){let $=g(V)&&(Z?Z.unitsKept.has(V):N(K(Q,V),K(J,V)));for(let M of P(K(J,V))){let z=K(V,M),q=K(J,z),X=K(Q,z),B=k(q),w=Y(X);if(w&&B.ino===w.ino&&B.dev===w.dev){U(q);continue}if(B.isFile()&&w?.isFile()&&Z?.linked.get(z)===w.ino){_(q,X);continue}if($&&(S.has(M)||x.has(M)))continue;if(!w){if(B.isFile()){if(W(()=>$J(q,X),"EEXIST"))U(q)}else W(()=>_(q,X),"EEXIST","ENOTEMPTY");continue}if(B.isDirectory()&&w.isDirectory())YJ(J,Q,z,Z),W(()=>KJ(q),"ENOTEMPTY","EEXIST")}}function YQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=["",...P(Q,{withFileTypes:!0}).filter(($)=>$.isDirectory()&&!$.name.startsWith(".")).map(($)=>$.name)];for(let $ of Z){let M=K(Q,$),z=K(V,$);if(!N(M,z)||!N(z,M))continue;if([...S,...x].some((X)=>h(K(M,X),K(z,X))===!1))return $}return null}function WQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=($)=>{for(let M of P(K(Q,$))){let z=K($,M);if(g($)&&(M==="connect"||M==="connect-once"))continue;let q=k(K(Q,z)),X=Y(K(V,z));if(!X||q.ino===X.ino&&q.dev===X.dev)continue;if(q.isDirectory()&&X.isDirectory()&&!X.isSymbolicLink()){let B=Z(z);if(B!==null)return B}else if(q.isSymbolicLink()||X.isSymbolicLink()){if(!(q.isSymbolicLink()&&X.isSymbolicLink()&&R(K(Q,z))===R(K(V,z))))return z}else if(h(K(Q,z),K(V,z))!==!0)return z}return null};return Z("")}function h(J,Q){let V=Y(J),Z=Y(Q);if(!V&&!Z)return null;if(!V||!Z||V.isDirectory()!==Z.isDirectory())return!1;if(V.ino===Z.ino&&V.dev===Z.dev)return!0;if(V.isDirectory())return[...new Set([...P(J),...P(Q)])].every((M)=>h(K(J,M),K(Q,M))===!0);try{return t(J).equals(t(Q))}catch{return!1}}function N(J,Q){for(let V of S)if(WJ(K(J,V),K(Q,V)))return!0;return!1}function WJ(J,Q){let V=Y(J);if(!V)return!1;let Z=Y(Q);if(!Z)return!0;if(V.isDirectory()){if(!Z.isDirectory())return!0;return P(J).some(($)=>WJ(K(J,$),K(Q,$)))}if(V.isSymbolicLink())return!Z.isSymbolicLink()||R(J)!==R(Q);return V.ino!==Z.ino||V.dev!==Z.dev}function e(J){if(v(J))W(()=>U(J),"ENOENT")}function wJ(J){return K(J,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${VJ(3).toString("hex")}`)}function v(J){try{return k(J).isSymbolicLink()&&R(J)===O(J)}catch{return!1}}function T(J){let Q=Y(J);return Q!==null&&Q.isDirectory()}function SJ(J,Q){for(let V=0;V<40;V+=1){let Z=J.lock(Q);if(Z)return Z;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function F(J,Q){return K(J,`.${Q}-${process.pid}-${VJ(6).toString("hex")}`)}function JJ(J){if(J===process.pid)return!1;try{return process.kill(J,0),!0}catch(Q){return G(Q)==="EPERM"}}function Y(J){try{return k(J)}catch(Q){if(G(Q)==="ENOENT"||G(Q)==="ENOTDIR")return null;throw Q}}function W(J,...Q){try{return J(),!0}catch(V){if(Q.includes(G(V)??""))return!1;throw V}}function G(J){return J instanceof Error&&"code"in J&&typeof J.code==="string"?J.code:void 0}var C,uJ=2,fJ=4,xJ=2,gJ=2,QJ=-100;function LJ(){if(C!==void 0)return C;if(C=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let J;try{J=CJ(import.meta.url)("bun:ffi")}catch{return null}let Q=process.platform==="darwin",V=Q?"__error":"__errno_location",Z=Q?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:$}=J;for(let M of Z)try{let z=Q?"renamex_np":"renameat2",X=J.dlopen(M,{flock:{args:[$.i32,$.i32],returns:$.i32},[V]:{args:[],returns:$.ptr},[z]:Q?{args:[$.ptr,$.ptr,$.u32],returns:$.i32}:{args:[$.i32,$.ptr,$.i32,$.ptr,$.u32],returns:$.i32}}).symbols,B=X[V]();if(B===null)continue;let w=(H)=>{let E=J.read.i32(B),D=Object.entries(FJ.errno).find(([,b])=>b===E)?.[0]??`errno_${E}`;return Object.assign(Error(`${H} failed: ${D}`),{code:D})},d=(H)=>Buffer.from(`${H}\x00`,"utf8");return C={exchange(H,E){let D=d(H),b=d(E);if((Q?X[z](J.ptr(D),J.ptr(b),xJ):X[z](QJ,J.ptr(D),QJ,J.ptr(b),gJ))!==0)throw w("exchange")},lock(H){let E=kJ(H,_J.O_RDONLY);if(X.flock(E,uJ|fJ)===0)return()=>a(E);let D=w("lock");if(a(E),D.code==="EWOULDBLOCK"||D.code==="EAGAIN")return null;throw D}},C}catch{}return null}
3
- export{f as Yh,mJ as Zh,yJ as _h,j as $h,sJ as ai,p as bi,cJ as ci,lJ as di,iJ as ei,rJ as fi,r as gi,jJ as hi,qQ as ii,BQ as ji,YQ as ki,WQ as li,LJ as mi};
2
+ import{Ci as m,Di as y}from"./vm-hands-entry-lite-ma001vzh.js";import{basename as UJ}from"path";var f=["production","staging"],DJ="https://api.reasonmachines.com",EJ="https://staging-api.reasonmachines.com";var u={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},GJ=new Set(["ara-staging","ara-staging.exe","reason-staging","reason-staging.exe"]);function mJ(J={}){let Q=m(J.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(Q){if(f.includes(Q))return Q;throw Error(`Unknown Reason CLI channel: ${Q}`)}let V=UJ(J.executablePath??process.execPath).toLowerCase();return GJ.has(V)?"staging":"production"}function yJ(J,Q){return{...J,...y("REASON_CLI_CHANNEL",Q)}}function j(J){return J==="staging"?EJ:DJ}function sJ(J){return`${j(J)}/mcp/ara`}var s={production:["https://api.ara.so",u.production.api],staging:["https://api-staging.ara.so",u.staging.api]};function p(J){let Q;try{Q=new URL(J).origin}catch{return J}let V=f.find((Z)=>s[Z].includes(Q));return V?j(V):Q}function cJ(J,Q){return J===Q||p(J)===p(Q)}function lJ(J,Q){return f.some((V)=>s[V].includes(J)&&Q===j(V))}function iJ(J,Q){try{let V=new URL(Q);return!V.username&&!V.password&&(V.origin===j(J)||V.origin===u[J].api)}catch{return!1}}function rJ(J){try{let Q=new URL(J).hostname.replace(/^\[|\]$/g,"").toLowerCase();return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}import{randomBytes as VJ}from"crypto";import{chmodSync as ZJ,closeSync as a,constants as _J,linkSync as $J,lstatSync as k,mkdirSync as XJ,openSync as kJ,readdirSync as P,readFileSync as t,readlinkSync as R,renameSync as _,rmdirSync as KJ,symlinkSync as A,unlinkSync as U}from"fs";import{createRequire as CJ}from"module";import{constants as FJ}from"os";import{basename as O,join as K,sep as OJ}from"path";import{existsSync as I,lstatSync as l,readdirSync as PJ,readFileSync as HJ,readlinkSync as RJ,realpathSync as TJ}from"fs";import{join as L,sep as AJ}from"path";function i(J,...Q){let V=L(J,"ara"),Z=L(J,"reason");if(!r(V))return L(Z,...Q);if(!I(Z))return L(V,...Q);return I(L(V,...Q))&&!I(L(Z,...Q))?L(V,...Q):L(Z,...Q)}function r(J){try{let Q=l(J);if(!Q.isSymbolicLink())return Q.isDirectory();return RJ(J)!=="reason"&&I(J)}catch{return!1}}function o(J,Q=[]){if(!r(J))return!1;let V;try{V=[J,...PJ(J,{withFileTypes:!0}).filter((Z)=>Z.isDirectory()).map((Z)=>L(J,Z.name))]}catch{return!1}return V.some((Z)=>["connect","connect-once"].filter(($)=>!Q.includes(L(Z,$))).some(($)=>{let M=L(Z,$,"worker.json");try{l(M)}catch{return!1}try{let z=JSON.parse(HJ(M,"utf8"))?.stateDirectory;if(typeof z!=="string")return!0;let q=(X,B)=>X===B||X.startsWith(B+AJ);return q(z,J)||q(c(z),c(J))}catch{return!0}}))}function c(J){try{return TJ(J)}catch{return J}}var S=new Set(["credentials.json","local-device.json","local-device.revoked.json","local-device.auth-migration.json","local-device.json.registration-pending.json","local-daemon.json","local-daemon.json.workspaces.json","local-root-fingerprint-key.json","instances","workspaces"]),x=new Set(["local-device.proxy.json"]),bJ=new Set(["local-device.key","local-device.binding"]),n=new Map;function jJ(J,Q,V){let Z=K(J,"ara");if(process.platform==="win32"||/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(J))return{state:Y(Z)?.isDirectory()?"kept":"absent"};return zJ(Z,K(J,"reason"),{linkAlways:!0,kept:($)=>o($,V??[]),native:Q===void 0?LJ:()=>Q},V!==void 0)}function qQ(J,...Q){return jJ(J),i(J,...Q)}function BQ(J,Q=process.platform){if(Q==="win32")return K(J,"AppData","Local","Reason","Logs");let V=K(J,"Library","Logs");if(Q==="darwin")for(let Z of[""," Staging"," Development"])zJ(K(V,`Ara${Z}`),K(V,`Reason${Z}`),{linkAlways:!1,kept:()=>!1,native:LJ});return K(V,"Reason")}var MJ="config_rename_unavailable:busy";function zJ(J,Q,V,Z=!1){let $=Z?void 0:n.get(J);if($)return $;let M;try{M=IJ(J,Q,V)}catch(z){let q=`config_rename_unavailable:${G(z)??"failed"}`;try{return{state:Y(J)?.isDirectory()?"kept":"absent",problem:q}}catch{return{state:"kept",problem:q}}}if(!(M.state==="absent"&&V.linkAlways)&&M.problem!==MJ&&!(M.state==="kept"&&!M.problem))n.set(J,M);return M}function IJ(J,Q,V){vJ(Q,V.native);let Z=!1;for(let $=0;$<8;$+=1){let M=Y(J);if(M?.isSymbolicLink())return R(J)===O(Q)?{state:Z?"renamed":"linked"}:{state:"kept"};if(!M){if(v(Q))W(()=>U(Q),"ENOENT");if(!(Z||V.linkAlways)||!T(Q))return{state:"absent"};let X=F(Q,"link");A(O(Q),X);try{W(()=>_(X,J),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{W(()=>U(X),"ENOENT")}continue}if(!M.isDirectory())return{state:"absent"};if(V.kept(J))return e(Q),{state:"kept"};let z=V.native();if(!z)return e(Q),{state:"kept",problem:"config_rename_unavailable:no_native"};let q=SJ(z,J);if(!q)return{state:"kept",problem:MJ};try{if(k(J).isSymbolicLink())continue;let X=NJ(z,J,Q);if(X)return{state:"kept",problem:X};Z=!0}finally{q()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function NJ(J,Q,V){let Z=Y(V);if(!Z||v(V)){if(!Z)A(O(V),V);try{J.exchange(Q,V)}catch(X){if(v(V))W(()=>U(V),"ENOENT");return`config_rename_unavailable:${G(X)??"exchange_failed"}`}return null}if(!Z.isDirectory())return"config_rename_unavailable:ENOTDIR";if(Z.dev!==k(Q).dev)return"config_rename_unavailable:EXDEV";let $=[F(V,"probe"),F(V,"probe")];try{A("a",$[0]),A("b",$[1]),J.exchange($[0],$[1])}catch(X){return`config_rename_unavailable:${G(X)??"exchange_failed"}`}finally{for(let X of $)W(()=>U(X),"ENOENT")}let M=wJ(V);for(let X of bJ){let B=Y(K(V,X)),w=Y(K(Q,X));if(B&&w&&B.ino!==w.ino)XJ(`${M}-replaced`,{mode:448,recursive:!0}),_(K(V,X),K(`${M}-replaced`,X))}let z={linked:new Map,unitsKept:new Set};qJ(Q,V,"",z);let q=F(V,"rename");A(O(V),q);try{J.exchange(Q,q)}catch(X){return W(()=>U(q),"ENOENT"),`config_rename_unavailable:${G(X)??"exchange_failed"}`}return BJ(q,V,z,M),null}function g(J){return J===""||!J.includes(OJ)}function qJ(J,Q,V,Z){let $=g(V)&&N(K(Q,V),K(J,V));if($)Z.unitsKept.add(V);for(let M of P(K(J,V))){if($&&(S.has(M)||x.has(M)))continue;let z=K(V,M),q=K(J,z),X=K(Q,z),B=Y(q);if(!B)continue;let w=Y(X);if(B.isDirectory()){if(!w)W(()=>XJ(X,{mode:B.mode&4095}),"EEXIST"),ZJ(X,B.mode&4095);if(T(X))qJ(J,Q,z,Z)}else if(!w){if(B.isSymbolicLink())W(()=>A(R(q),X),"EEXIST");else if(W(()=>$J(q,X),"EEXIST","ENOENT"))Z.linked.set(z,B.ino)}}}function vJ(J,Q){let V;try{if(!T(J))return;V=P(J)}catch{return}for(let Z of V){let $=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(Z);if(!$)continue;let M=K(J,Z),z=Y(M);if(!z)continue;if(!z.isDirectory()){if(!JJ(Number($[2])))W(()=>U(M),"ENOENT");continue}let q=Q(),X=null;if(q){try{X=q.lock(M)}catch{continue}if(!X)continue}else if(JJ(Number($[2])))continue;try{let B=F(J,"claim");if(W(()=>_(M,B),"ENOENT"))BJ(B,J,null,wJ(J))}finally{X?.()}}}function BJ(J,Q,V,Z){for(let[$,M]of V?.linked??[])if(!Y(K(J,$))&&Y(K(Q,$))?.ino===M)W(()=>U(K(Q,$)),"ENOENT");if(YJ(J,Q,"",V),W(()=>KJ(J),"ENOTEMPTY","EEXIST"))return;_(J,Z),ZJ(Z,448)}function YJ(J,Q,V,Z){let $=g(V)&&(Z?Z.unitsKept.has(V):N(K(Q,V),K(J,V)));for(let M of P(K(J,V))){let z=K(V,M),q=K(J,z),X=K(Q,z),B=k(q),w=Y(X);if(w&&B.ino===w.ino&&B.dev===w.dev){U(q);continue}if(B.isFile()&&w?.isFile()&&Z?.linked.get(z)===w.ino){_(q,X);continue}if($&&(S.has(M)||x.has(M)))continue;if(!w){if(B.isFile()){if(W(()=>$J(q,X),"EEXIST"))U(q)}else W(()=>_(q,X),"EEXIST","ENOTEMPTY");continue}if(B.isDirectory()&&w.isDirectory())YJ(J,Q,z,Z),W(()=>KJ(q),"ENOTEMPTY","EEXIST")}}function YQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=["",...P(Q,{withFileTypes:!0}).filter(($)=>$.isDirectory()&&!$.name.startsWith(".")).map(($)=>$.name)];for(let $ of Z){let M=K(Q,$),z=K(V,$);if(!N(M,z)||!N(z,M))continue;if([...S,...x].some((X)=>h(K(M,X),K(z,X))===!1))return $}return null}function WQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=($)=>{for(let M of P(K(Q,$))){let z=K($,M);if(g($)&&(M==="connect"||M==="connect-once"))continue;let q=k(K(Q,z)),X=Y(K(V,z));if(!X||q.ino===X.ino&&q.dev===X.dev)continue;if(q.isDirectory()&&X.isDirectory()&&!X.isSymbolicLink()){let B=Z(z);if(B!==null)return B}else if(q.isSymbolicLink()||X.isSymbolicLink()){if(!(q.isSymbolicLink()&&X.isSymbolicLink()&&R(K(Q,z))===R(K(V,z))))return z}else if(h(K(Q,z),K(V,z))!==!0)return z}return null};return Z("")}function h(J,Q){let V=Y(J),Z=Y(Q);if(!V&&!Z)return null;if(!V||!Z||V.isDirectory()!==Z.isDirectory())return!1;if(V.ino===Z.ino&&V.dev===Z.dev)return!0;if(V.isDirectory())return[...new Set([...P(J),...P(Q)])].every((M)=>h(K(J,M),K(Q,M))===!0);try{return t(J).equals(t(Q))}catch{return!1}}function N(J,Q){for(let V of S)if(WJ(K(J,V),K(Q,V)))return!0;return!1}function WJ(J,Q){let V=Y(J);if(!V)return!1;let Z=Y(Q);if(!Z)return!0;if(V.isDirectory()){if(!Z.isDirectory())return!0;return P(J).some(($)=>WJ(K(J,$),K(Q,$)))}if(V.isSymbolicLink())return!Z.isSymbolicLink()||R(J)!==R(Q);return V.ino!==Z.ino||V.dev!==Z.dev}function e(J){if(v(J))W(()=>U(J),"ENOENT")}function wJ(J){return K(J,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${VJ(3).toString("hex")}`)}function v(J){try{return k(J).isSymbolicLink()&&R(J)===O(J)}catch{return!1}}function T(J){let Q=Y(J);return Q!==null&&Q.isDirectory()}function SJ(J,Q){for(let V=0;V<40;V+=1){let Z=J.lock(Q);if(Z)return Z;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function F(J,Q){return K(J,`.${Q}-${process.pid}-${VJ(6).toString("hex")}`)}function JJ(J){if(J===process.pid)return!1;try{return process.kill(J,0),!0}catch(Q){return G(Q)==="EPERM"}}function Y(J){try{return k(J)}catch(Q){if(G(Q)==="ENOENT"||G(Q)==="ENOTDIR")return null;throw Q}}function W(J,...Q){try{return J(),!0}catch(V){if(Q.includes(G(V)??""))return!1;throw V}}function G(J){return J instanceof Error&&"code"in J&&typeof J.code==="string"?J.code:void 0}var C,uJ=2,fJ=4,xJ=2,gJ=2,QJ=-100;function LJ(){if(C!==void 0)return C;if(C=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let J;try{J=CJ(import.meta.url)("bun:ffi")}catch{return null}let Q=process.platform==="darwin",V=Q?"__error":"__errno_location",Z=Q?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:$}=J;for(let M of Z)try{let z=Q?"renamex_np":"renameat2",X=J.dlopen(M,{flock:{args:[$.i32,$.i32],returns:$.i32},[V]:{args:[],returns:$.ptr},[z]:Q?{args:[$.ptr,$.ptr,$.u32],returns:$.i32}:{args:[$.i32,$.ptr,$.i32,$.ptr,$.u32],returns:$.i32}}).symbols,B=X[V]();if(B===null)continue;let w=(H)=>{let E=J.read.i32(B),D=Object.entries(FJ.errno).find(([,b])=>b===E)?.[0]??`errno_${E}`;return Object.assign(Error(`${H} failed: ${D}`),{code:D})},d=(H)=>Buffer.from(`${H}\x00`,"utf8");return C={exchange(H,E){let D=d(H),b=d(E);if((Q?X[z](J.ptr(D),J.ptr(b),xJ):X[z](QJ,J.ptr(D),QJ,J.ptr(b),gJ))!==0)throw w("exchange")},lock(H){let E=kJ(H,_J.O_RDONLY);if(X.flock(E,uJ|fJ)===0)return()=>a(E);let D=w("lock");if(a(E),D.code==="EWOULDBLOCK"||D.code==="EAGAIN")return null;throw D}},C}catch{}return null}
3
+ export{f as li,mJ as mi,yJ as ni,j as oi,sJ as pi,p as qi,cJ as ri,lJ as si,iJ as ti,rJ as ui,r as vi,jJ as wi,qQ as xi,BQ as yi,YQ as zi,WQ as Ai,LJ as Bi};
@@ -0,0 +1,7 @@
1
+ // @bun
2
+ import{Hc as n}from"./vm-hands-entry-lite-qef2ndkd.js";import{dd as r}from"./vm-hands-entry-lite-g7h6wjqy.js";import{sk as a,tk as s,wk as i}from"./vm-hands-entry-lite-r8qg3wp1.js";import{Ek as B}from"./vm-hands-entry-lite-51hmj6am.js";import{spawn as f,spawnSync as v}from"child_process";import{existsSync as U,mkdtempSync as o,readFileSync as t,readdirSync as _j,realpathSync as Sj,rmSync as e,statSync as jj}from"fs";import{platform as h,tmpdir as qj}from"os";import{dirname as E,join as H,win32 as T}from"path";import{fileURLToPath as Mj,pathToFileURL as y}from"url";var kj=["bwrap","socat","rg"],Fj=2000,g=20000,Pj=3,w=4000,Ej=new Set([".git",".hg",".svn","node_modules"]),Rj=["runAsHostUid","sysrq-trigger"],zj=H(E(E(Mj(import.meta.url))),"packages","sandbox-runtime"),Dj=H(zj,"src","index.ts"),Gj=!1;function oj(){Gj=!0}function Jj(){return Gj?H(E(Sj(process.execPath)),"runtime","srt"):void 0}function C(){let j=H(Jj()??zj,"vendor","srt-win"),q=H(j,process.arch,"srt-win.exe"),G=H(j,"arm64","srt-win.exe");return process.arch==="x64"&&!U(q)&&U(G)?G:q}var tj="confined commands need the Windows sandbox: run `reason connect` and approve the Windows prompt.";function ej(j=C()){let q=v(j,["status"],{encoding:"utf8",timeout:15000,windowsHide:!0});try{let G=JSON.parse(q.stdout??"");return q.status===0&&G.user?.user?.exists===!0&&G.user.cred_present===!0}catch{return!1}}function jq(j=C()){let q=v(j,["install"],{stdio:["ignore","ignore","ignore"],timeout:120000,windowsHide:!0});return q.status===0?"installed":q.status===10?"cancelled":"failed"}async function Kj(){let j=Jj();if(j&&process.platform==="linux"&&!U(H(j,"vendor","seccomp",process.arch,"apply-seccomp")))throw Error("packaged_sandbox_runtime_vendor_missing");if(j&&process.platform==="win32"&&!U(C()))throw Error("packaged_sandbox_runtime_vendor_missing");if(j){let J=t(H(j,"sandbox-runtime.mjs"),"utf8");for(let K of Rj)if(!J.includes(K))throw Error(`packaged_sandbox_runtime_fork_missing:${K}`)}let z=(await import(j?y(H(j,"sandbox-runtime.mjs")).href:y(Dj).href)).SandboxManager;if(!z||typeof z.initialize!=="function"||typeof z.wrapWithSandboxArgv!=="function")throw Error("sandbox-runtime does not expose the expected SandboxManager API.");return{SandboxManager:z}}function Wj(j={}){if((j.platformName??h())!=="linux")return!1;let G=j.fileExists??U,z=j.readFile??((J)=>t(J,"utf8"));for(let J of["/.dockerenv","/run/.containerenv"])try{if(G(J))return!0}catch{}try{return/docker|containerd|kubepods|lxc|libpod/.test(z("/proc/1/cgroup"))}catch{return!1}}function Qj(j){return["/bin/true","/usr/bin/true"].find((q)=>j(q))??null}function xj(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 Oj(j,q){try{let G=v("bwrap",xj(j,q),{stdio:"ignore",timeout:Fj});return!G.error&&G.status===0}catch{return!1}}function fj(j){let q=j.platformName??h(),G=j.fileExists??U;if(q==="win32")return(j.bash??a)()&&G(C())?X??"strict":null;if(q!=="linux")return null;let z=j.hasExecutable??r;if(!kj.every((V)=>z(V)))return null;let J=Qj(G);if(!J)return null;let K=X??(j.containerized??Wj({platformName:q})?"weak":"strict");return(j.probeNamespaces??((V)=>Oj(V,J)))(K)?K:null}var _=null,R=!1,Y=null,c=null,u=null,X=null,S=null,P=null,M=null,D=[],N=new Map;function W(){throw A("sandbox_mode_conflict"),new B("sandbox_unavailable","Sandbox process policy conflicts with an existing probe or session. Restart the worker.")}function qq(j){if(X!==null&&X!==j||R&&_!==null&&_!==j||S!==null&&S!==j)W();X=j}function A(j){if(!Y)process.stderr.write(`Reason worker: confined commands are off (${j})
3
+ `);Y=j}function Vj(j){if(Y)return!1;if(!R){if(_=fj(j??{}),R=!0,_&&!j)Yj()}return _!==null}function vj(){return Vj()?_:null}var k=null,I=0;function x(j,q){if(Y)throw new B("sandbox_unavailable","Confined execution is unavailable in this worker process.");if(X&&j.sandboxMode&&X!==j.sandboxMode)W();let G=X??j.sandboxMode??vj();if(!G)throw new B("sandbox_unavailable","Confined command execution is unavailable on this operating system.");if(S&&S!==G)W();return S=G,k??=(async()=>{let{SandboxManager:z}=await(j.loadSandboxRuntime??Kj)();return await z.initialize(uj(G,q)),z})().catch((z)=>{if(k=null,q)P=null,process.stderr.write(`Reason worker: the Windows sandbox did not start for this folder (${String(z).slice(0,500)})
4
+ `);else A(`initialize_failed: ${String(z)}`);throw z instanceof B?z:new B("sandbox_unavailable","The confined execution sandbox failed to start.")}),k.then((z)=>{if(Y)throw new B("sandbox_unavailable","Confined execution became unavailable during sandbox initialization.");return z})}function O(){if(I-=1,I===0)for(let j of D.splice(0))j()}async function Zj(j,q=!0,G,z){let J=z===void 0?1/0:Date.now()+z;await Bj();let K=bj();if(q)await K;let Q=JSON.stringify(j),V=!1,$=()=>{if(!V)return;V=!1;let Z=(N.get(Q)??1)-1;if(Z>0)N.set(Q,Z);else N.delete(Q)};try{for(;;){if(G?.aborted)throw new B("cancelled","Operation was cancelled.");if(Date.now()>=J)return!1;if(M){await M;continue}let Z=N.keys().next().value;if(P??=Z??Q,P===Q&&(Z===void 0||Z===Q))break;if(!V){V=!0,N.set(Q,(N.get(Q)??0)+1);continue}if(I===0&&Z===Q){$j();continue}await new Promise((L)=>{if(D.push(L),G?.addEventListener("abort",()=>L(),{once:!0}),J!==1/0)setTimeout(L,Math.max(0,J-Date.now())).unref?.()})}return I+=1,!0}finally{if(V&&I===0)for(let Z of D.splice(0))Z();$()}}function $j(){return M??=Xj().finally(()=>{M=null}),M}function Hj(j,q,G=process.env){let z=G.USERPROFILE?T.resolve(G.USERPROFILE).toLowerCase():null,J=T.resolve(j).toLowerCase(),K=z!==null&&J.startsWith(`${z}\\`),Q=q?Lj(G).filter((V)=>V.toLowerCase()===J||V.toLowerCase().startsWith(`${J}\\`)):[];return{denyRead:[],allowRead:[j],allowWrite:q?[j]:[],denyWrite:q?Q:K?[]:[j]}}function Lj(j,q=process.execPath){let G=new Map;for(let z of[...(j.PATH??j.Path??"").split(";"),T.dirname(q)]){if(!z||!T.isAbsolute(z))continue;let J=T.resolve(z);if(!G.has(J.toLowerCase()))G.set(J.toLowerCase(),J)}return[...G.values()]}function hj(j=process.env,q=process.execPath){let G=[j.SystemRoot,j.ProgramFiles,j["ProgramFiles(x86)"],j.ProgramW6432,j.ProgramData,j.USERPROFILE].filter((z)=>!!z).map((z)=>T.resolve(z).toLowerCase());return Lj(j,q).filter((z)=>{let J=z.toLowerCase();return!G.some((K)=>J===K||J.startsWith(`${K}\\`))})}var l=null,m=null;function Bj(j=C()){return m??=(async()=>{let q;try{q=JSON.parse((await Uj(j,["status"])).stdout).user?.user?.sid}catch{return null}if(typeof q!=="string"||!/^S-1-[0-9-]+$/.test(q))return null;if(!await new Promise((z)=>{let J=f(i("icacls"),[j,"/grant",`*${q}:(RX)`],{stdio:"ignore",windowsHide:!0,timeout:30000});J.on("error",()=>z(!1)),J.on("close",(K)=>z(K===0))}))process.stderr.write(`Reason worker: could not let the Windows sandbox user run srt-win.exe
5
+ `);return q})(),m}function Uj(j,q,G){return new Promise((z)=>{let J=f(j,q,{stdio:["pipe","pipe","ignore"],windowsHide:!0,timeout:120000}),K="";J.stdout?.setEncoding("utf8").on("data",(Q)=>{K+=Q}),J.on("error",()=>z({status:null,stdout:K})),J.on("close",(Q)=>z({status:Q,stdout:K})),J.stdin?.end(G??"")})}function bj(j=C()){return l??=(async()=>{let q=hj();if(q.length===0)return;let G=await Bj(j),z=G?await Uj(j,["acl","stamp","--holder-pid",String(process.ppid),"--sandbox-user-sid",G],JSON.stringify({denyRead:[],denyWrite:q})):null;if(!z||z.status!==0&&z.status!==2)A(`program_folder_deny_failed: ${z?`exit ${z.status}`:"no sandbox user"}`),process.stderr.write(`Reason worker: could not deny the Windows sandbox writes to PATH folders (${z?`exit ${z.status}`:"no sandbox user"}); confined commands are off
6
+ `)})(),l}var yj=`h=$(mktemp -d) || exit 125; trap 'rm -rf "$h"' EXIT; mkdir -p "$h/AppData/Roaming" "$h/AppData/Local"; w=$(cygpath -w "$h"); export HOME="$h" USERPROFILE="$w" APPDATA="$w\\AppData\\Roaming" LOCALAPPDATA="$w\\AppData\\Local" TEMP="$w" TMP="$w"; `;async function Xj(){let j=k;if(k=null,P=null,!j)return;try{await(await j).reset()}catch{}}async function Yj(j={}){if(Y)return!1;if(j.loadSandboxRuntime)return d(j.loadSandboxRuntime);if(!Vj())return!1;return c??=d(Kj),c}async function d(j){try{let{SandboxManager:q}=await j();if(process.platform==="win32"){if(!U(C()))A("dependencies_missing: srt-win.exe");return!Y}let G=q.checkDependencies().errors;if(G.length>0)return A(`dependencies_missing: ${G.join(", ")}`),!1;return!Y}catch(q){return A(`load_failed: ${String(q)}`),!1}}async function zq(j={}){if(!j.loadSandboxRuntime&&!j.sandboxMode){if(!await Yj())return!1;return u??=p({}),u}return p(j)}async function p(j){let q=process.platform==="win32",G=o(H(qj(),"reason-device-probe-"));try{let z=q?Hj(G,!1):void 0;if(z)await Zj(z,!1);let J;try{J=await gj(await x(j,z),G)}catch{return!1}finally{if(q)O()}if(!J)A("confined_command_failed");if(I===0)await(q?$j():Xj());return J}finally{e(G,{recursive:!0,force:!0})}}async function gj(j,q){let G=process.platform==="win32",z=G?"true":Qj(U);if(!z)return!1;try{let{argv:J,env:K}=await j.wrapWithSandboxArgv(Aj([z]),Cj(),{filesystem:G?Nj([],q):Ij({root:q,allowWrite:!1,temporaryDirectory:q,protectedPaths:[]})},void 0,q),[Q,...V]=J;if(!Q)return!1;return await wj(Q,V,q,G?{env:K}:{})}catch{return!1}finally{try{j.cleanupAfterCommand()}catch{}}}function wj(j,q,G,z={}){return new Promise((J)=>{let K=!1,Q,V=(L)=>{if(K)return;K=!0,clearTimeout(Q),J(L)},$;try{$=(z.spawnChild??f)(j,q,{cwd:G,env:z.env??{PATH:n,HOME:G,TMPDIR:G},stdio:"ignore",windowsHide:!0})}catch{V(!1);return}$.once("error",()=>V(!1));let Z=(L,F)=>V(L===0&&F===null);if($.once("exit",Z),$.once("close",Z),$.exitCode!==null||$.signalCode!==null)Z($.exitCode,$.signalCode);if(K)return;Q=setTimeout(()=>{V(!1);try{$.kill("SIGKILL")}catch{}},Math.min(z.timeoutMs??g,g))})}function Cj(j=U,q=h()){if(q==="win32")return s("win32");return["/bin/bash","/bin/sh"].find((G)=>j(G))??"/bin/sh"}function Aj(j){return j.map((q)=>`'${q.replaceAll("'","'\\''")}'`).join(" ")}function cj(j,q,G=(z)=>_j(z,{withFileTypes:!0}).filter((J)=>J.isDirectory()||J.isFile()).map((J)=>J.name)){let z=[],J=[{path:j,depth:0}],K=0;while(J.length>0&&K<w){let Q=J.pop(),V;try{V=G(Q.path)}catch{continue}for(let $ of V){if(K+=1,K>w)break;let Z=H(Q.path,$);if(q(Z)){z.push(Z);continue}if(Q.depth+1<Pj&&!Ej.has($))J.push({path:Z,depth:Q.depth+1})}}return z}function Ij(j){let q=H(j.root,".git"),G=[];try{if(jj(q).isDirectory())G=[H(q,"config"),H(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,...G]}}function Nj(j,q){let G=H(q,".git"),z=[];try{if(jj(G).isDirectory())z=[H(G,"config"),H(G,"hooks")]}catch{}return{denyRead:[...j],allowRead:[],allowWrite:[],denyWrite:[...j,...z]}}function uj(j,q){if(q)return{network:{allowedDomains:[],deniedDomains:[]},filesystem:q,windows:{srtWin:{path:C()}}};return{network:{allowedDomains:[],deniedDomains:[]},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},...j==="weak"?{enableWeakerNestedSandbox:!0}:{}}}function Gq(j){let q=j.createTemporaryDirectory??(()=>o(H(qj(),"reason-device-"))),G=j.removeTemporaryDirectory??((z)=>e(z,{recursive:!0,force:!0}));return async(z,J,K)=>{let Q=process.platform==="win32",V;if(Q){let Z=Hj(K.root,K.allowWrite);if(!await Zj(Z,!K.workerProbe,K.signal,K.timeoutMs))return{exitCode:null,signal:null,stdout:"",stderr:"",timedOut:!0,truncated:!1};try{V=await x(j,Z)}catch(L){throw O(),L}}else V=await x(j),I+=1;let $;try{$=q();let Z=cj(K.root,j.isProtectedPath),L;try{L=await V.wrapWithSandboxArgv((Q?yj:"")+Aj([z,...J]),j.shell??Cj(),{filesystem:Q?Nj(Z,K.root):Ij({root:K.root,allowWrite:K.allowWrite,temporaryDirectory:$,protectedPaths:Z})},K.signal,K.cwd)}catch(b){throw b instanceof B?b:new B("sandbox_unavailable","The confined execution sandbox could not wrap the command.")}let[F,...Tj]=L.argv;if(!F)throw new B("sandbox_unavailable","The confined execution sandbox produced no command.");return await j.spawnCaptured(F,Tj,{cwd:K.cwd,timeoutMs:K.timeoutMs,signal:K.signal,env:Q?L.env:j.scrubEnvironment(K.root,$)})}finally{O();try{V.cleanupAfterCommand()}catch{}if($!==void 0)G($)}}}
7
+ export{oj as xc,C as yc,tj as zc,ej as Ac,jq as Bc,qq as Cc,Vj as Dc,zq as Ec,Cj as Fc,Gq as Gc};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{wa as f}from"./vm-hands-entry-lite-3hbe4em3.js";import{Zh as K,bi as U,ci as y,ii as T}from"./vm-hands-entry-lite-5kgvss4p.js";import{ni as v}from"./vm-hands-entry-lite-r6pap1kh.js";import{Vj as $}from"./vm-hands-entry-lite-hc3p6r9p.js";var u=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function _(x){let w=typeof x==="string"?u.exec(x):null;return w?{major:Number(w[1]),minor:Number(w[2])}:null}import{createHash as n,randomBytes as j}from"crypto";import{createInterface as o}from"readline";import{randomBytes as d}from"crypto";import{chmodSync as q,existsSync as C,lstatSync as l,mkdirSync as a,readFileSync as b,renameSync as p,unlinkSync as O,writeFileSync as L}from"fs";import{homedir as t}from"os";import{dirname as i,join as F}from"path";function B(x=process.env,w=t()){let H=x.XDG_CONFIG_HOME?.trim()||F(w,".config"),J=K({env:x})==="staging"?["staging"]:[];return F(T(H,...J),"credentials.json")}function A(x,w=B()){return a(i(w),{recursive:!0,mode:448}),L(w,`${JSON.stringify(x,null,2)}
3
- `,{mode:384}),q(w,384),w}function M(x=B()){if(!C(x))return null;try{let w=b(x,"utf8"),H=JSON.parse(w);if(typeof H.apiOrigin!=="string"||typeof H.clientId!=="string"||typeof H.accessToken!=="string"||typeof H.refreshToken!=="string"||typeof H.expiresAt!=="string"||typeof H.orgId!=="string"||!Array.isArray(H.scopes))return null;let G=new URL(H.apiOrigin).origin,J=U(G);if(J!==G)s(x,w,J);return{apiOrigin:J,clientId:H.clientId,accessToken:H.accessToken,refreshToken:H.refreshToken,expiresAt:H.expiresAt,scopes:H.scopes.filter((Q)=>typeof Q==="string"),orgId:H.orgId}}catch{return null}}function s(x,w,H){let G=`${x}.${process.pid}.${d(6).toString("hex")}.tmp`;try{let J=l(x);if(!J.isFile()||J.uid!==process.geteuid?.())return;let Q=JSON.parse(w);if(L(G,`${JSON.stringify({...Q,apiOrigin:H},null,2)}
4
- `,{mode:384,flag:"wx"}),q(G,384),b(x,"utf8")!==w)throw Error("credentials_changed");p(G,x)}catch{try{O(G)}catch{}}}function R(x=B()){if(!C(x))return!1;return O(x),!0}var S=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var s0=S.filter((x)=>x!=="network:read"&&x!=="network:write");class D extends Error{oauthCode;constructor(x,w=null){super(x);this.oauthCode=w;this.name="LoginError"}}function n0(){let x=j(48).toString("base64url"),w=n("sha256").update(x).digest("base64url");return{verifier:x,challenge:w,state:j(32).toString("base64url")}}function r(x,w){let H=typeof x.error==="string"?x.error:null,G=typeof x.error_description==="string"?x.error_description:H?H:w;return new D(G,H)}async function e(x,w,H,G){let J=await H(`${x}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:w,signal:G}),Q=await J.json().catch(()=>({}));if(!J.ok)throw r(Q,`OAuth token request failed (${J.status})`);return Q}var x0=1e4;async function w0(x,w={}){let H=w.fetchImpl??fetch,G=await e(x.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:x.clientId,refresh_token:x.refreshToken}),H,AbortSignal.timeout(x0)).catch((Q)=>{if(Q instanceof Error&&Q.name==="TimeoutError")throw new D("Reason did not answer the login refresh in time. Check the network and retry.");throw Q});if(typeof G.access_token!=="string"||typeof G.refresh_token!=="string"||typeof G.expires_in!=="number")throw new D("Reason returned an incomplete refreshed login.");let J={...x,accessToken:G.access_token,refreshToken:G.refresh_token,expiresAt:new Date(Date.now()+G.expires_in*1000).toISOString(),scopes:typeof G.scope==="string"?G.scope.split(/\s+/).filter(Boolean):x.scopes};return A(J,w.path??B()),J}var z=new Map;function k(x,w){if(!w)return x;if(w.aborted)return Promise.reject(w.reason);return new Promise((H,G)=>{let J=()=>G(w.reason);w.addEventListener("abort",J,{once:!0}),x.then(H,G).finally(()=>w.removeEventListener("abort",J))})}async function P(x={}){let w=x.path??B(),H=M(w);if(!H)return null;let G=x.apiOrigin??v(process.env,"REASON_API_URL")?.trim();if(G&&!y(H.apiOrigin,new URL(G).origin))return null;let J=Date.parse(H.expiresAt)<=Date.now()+60000;if(!x.forceRefresh&&!J)return H;let Q=[w,H.apiOrigin,H.clientId,H.refreshToken].join("\x00"),V=z.get(Q);if(V)return k(V,x.signal);let Z;return Z=w0(H,{fetchImpl:x.fetchImpl,path:w}).catch(async(Y)=>{if(!(Y instanceof D)||Y.oauthCode!=="invalid_grant"&&Y.oauthCode!=="invalid_client")throw Y;let N=M(w),c=Y.oauthCode==="invalid_client"?N?.clientId!==H.clientId:N?.refreshToken!==H.refreshToken;if(N&&c)return P({fetchImpl:x.fetchImpl,path:w});return R(w),null}).finally(()=>{if(z.get(Q)===Z)z.delete(Q)}),z.set(Q,Z),k(Z,x.signal)}function o0(x,w){return new Promise((H)=>{let G=o({input:x}),J=!1,Q=(Z)=>{if(J)return;J=!0,w.removeEventListener("abort",V),G.close(),x.pause(),H(Z)},V=()=>Q(null);w.addEventListener("abort",V,{once:!0}),G.once("line",(Z)=>Q(Z)),G.once("close",()=>Q(null))})}var $0=$.object({label:$.string(),used_percent:$.number().min(0).max(100).nullable(),resets_at:$.string().nullable(),exhausted:$.boolean().nullable()}),H0=$.object({groups:$.array($.object({selectable:$.boolean().optional(),accounts:$.array($.object({source_id:$.string().min(1),model_ids:$.array($.string().min(1)).optional()}))}))});function G0(x){let w=H0.safeParse(x);if(!w.success)return;return w.data.groups.some((H)=>H.selectable!==!1&&H.accounts.some((G)=>G.model_ids===void 0||G.model_ids.length>0))}class X extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor(x,w,H,G,J,Q){super(H);this.status=x;this.code=w;this.suggestedModel=G;this.retryAfterMs=J;this.resolutionReason=Q;this.name="ApiError"}static rateLimitDelayMs(x,w){if(!(x instanceof X)||x.status!==429)return null;return Math.min(60000,Math.max(w,x.retryAfterMs??0))}}var J0=["minimal","low","medium","high","xhigh","max"],Q0=$.object({id:$.string().min(1),kind:$.string(),name:$.string(),custom_name:$.string().nullish(),status:$.string(),online:$.boolean(),compatible:$.boolean().optional(),compatibility_reason:$.string().nullish(),folder_lane_of:$.string().nullish(),roots:$.array($.object({id:$.string().min(1),label:$.string()}))}),W0=$.object({devices:$.array(Q0),end_cursor:$.string().nullish(),has_next_page:$.boolean().optional()}),Z0=$.object({id:$.string().min(1),name:$.string()}),V0=$.object({items:$.array(Z0)}),X0=$.object({id:$.string().min(1),name:$.string(),main:$.boolean(),mine:$.boolean(),session_id:$.string().nullish(),appearance:$.object({color:$.string().nullish()}).nullish().catch(null)}),Y0=$.object({items:$.array(X0)}),B0=$.object({skill_id:$.string().min(1),name:$.string(),description:$.string().nullish(),activation_keywords:$.array($.string()).default([]),is_enabled:$.boolean().default(!0)}),D0=$.object({items:$.array(B0).default([])}),z0=$.object({id:$.string().min(1),kind:$.string(),enabled:$.boolean(),schedule:$.object({expression:$.string().nullish(),every_seconds:$.number().nullish(),next_run_at:$.string().nullish()}).nullish(),github:$.object({event:$.string().nullish(),action:$.string().nullish(),repo:$.string().nullish()}).nullish(),last_fired_at:$.string().nullish()}),h=$.object({id:$.string().min(1),name:$.string().nullish(),instructions:$.string().nullish(),enabled:$.boolean(),triggers:$.array(z0).default([])}),N0=$.object({items:$.array(h).default([]),end_cursor:$.string().nullish(),has_next_page:$.boolean().optional()}),K0=$.object({id:$.string().min(1),slug:$.string().nullish(),name:$.string(),description:$.string().nullish(),transport:$.string().nullish(),url:$.string().nullish(),enabled:$.boolean()}),M0=$.object({items:$.array(K0).default([])}),P0=$.object({status:$.string(),summary:$.string().nullish(),category:$.string().nullish(),outcome:$.string().nullish(),message_count:$.number().nullish(),pr_url:$.string().nullish(),cost_usd:$.number().nullish(),generated_at:$.string().nullish()}),E=$.object({tags:$.array($.string()).default([])}),_0=$.enum(["linux","macos"]),m=$.object({id:$.string().min(1),name:$.string().min(1),platform:_0.nullable(),workers:$.object({total:$.number().int(),online:$.number().int(),busy:$.number().int(),idle:$.number().int()}),sessions:$.object({queued:$.number().int(),running:$.number().int()})}),F0=$.object({machines:$.array(m)}),U0=$.object({machine:m}),T0=$.object({deleted:$.literal(!0),revoked_workers:$.number().int(),revoked_tokens:$.number().int()}),q0=$.object({token:$.object({id:$.string().min(1),machine_id:$.string().min(1),token_prefix:$.string()}),secret:$.string().startsWith("rmt_")}),I=$.looseObject({machine_id:$.string().min(1),machine_name:$.string().min(1)}),C0=I.extend({organization_id:$.string().min(1)}),b0=$.object({id:$.string().min(1),name:$.string().min(1),state:$.enum(["waiting","placed"]),queue_position:$.number().int().nullable()});function H1(x){let w=b0.safeParse(x.machine);return w.success?w.data:null}var O0=$.union([$.object({kind:$.literal("cloud")}),$.object({kind:$.enum(["mac","headless"]),device_id:$.string().min(1),root_id:$.string().min(1)})]);function G1(x){let w=O0.safeParse(x.runs_on);return w.success?w.data:null}function W(x,w,H){let G=x.safeParse(w);if(!G.success)throw new X(502,H,"Reason returned an unexpected response.");return G.data}var L0=$.object({error:$.object({type:$.string(),message:$.string()})});function g(x,w,H){let G=L0.safeParse(w),J=typeof w.error==="string"?w.error:G.success?G.data.error.type:`http_${x}`,Q=typeof w.detail==="string"?w.detail:typeof w.message==="string"?w.message:G.success?G.data.error.message:`Reason request failed (${x}${typeof w.error==="string"?` ${w.error}`:""})`,V=J==="github_connection_required"&&typeof w.connect_url==="string"&&/^https?:\/\//.test(w.connect_url)?` Connect it at ${w.connect_url}`:"",Z=H===null||H.trim()===""?NaN:Number(H);return new X(x,J,`${Q}${V}`,typeof w.suggested_model==="string"?w.suggested_model:void 0,Number.isFinite(Z)&&Z>=0?Z*1000:void 0,typeof w.resolution_reason==="string"?w.resolution_reason:void 0)}async function J1(x){let w=await(x.fetchImpl??fetch)(`${x.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${x.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(x.body),signal:AbortSignal.timeout(30000),redirect:"error"}),H=await w.json().catch(()=>({}));if(!w.ok)throw g(w.status,H,w.headers.get("retry-after"));return W(C0,H,"invalid_machine_ticket")}class A0{options;credentials;constructor(x,w={}){this.options=w;this.credentials=x}trackEvent(x,w={}){}async request(x,w={},H=!1){let G=this.options.fetchImpl??fetch,J=await G(`${this.credentials.apiOrigin}/v3${x}`,{method:w.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":"reason-cli","x-reason-agent":"Reason CLI",...w.raw?{"content-type":w.raw.contentType}:w.body===void 0?{}:{"content-type":"application/json"},...w.headers},body:w.raw?w.raw.bytes:w.body===void 0?void 0:JSON.stringify(w.body),signal:w.signal,redirect:"error"}),Q=await J.json().catch(()=>({}));if(J.status===401&&!H&&w.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let V=await P({fetchImpl:G,path:this.options.credentialsPath,forceRefresh:!0,signal:w.signal});if(V)return this.credentials=V,this.request(x,w,!0)}if(!J.ok)throw g(J.status,Q,J.headers.get("retry-after"));return Q}createHeadlessDeviceEnrollmentTicket(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:x,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(x){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:x,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(w){if(w instanceof X&&(w.status===404||w.status===405||w.status===403&&w.code==="endpoint_not_available"))return null;throw w}}addDeviceRoot(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(x)}/roots`,{method:"POST",body:w,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(x)}/roots/${encodeURIComponent(w)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(x,w=""){let H=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return x===void 0?H:`${H}/${encodeURIComponent(x)}${w}`}async listMachines(){return W(F0,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(x){let w=await this.request(this.machinePath(),{method:"POST",body:{name:x.name,...x.platform?{platform:x.platform}:{}}});return W(U0,w,"invalid_machine").machine}async deleteMachine(x){let w=await this.request(this.machinePath(x),{method:"DELETE"});return W(T0,w,"invalid_machine_deletion")}async createMachineToken(x){let w=await this.request(this.machinePath(x,"/tokens"),{method:"POST",body:{}});return W(q0,w,"invalid_machine_token")}async createMachineEnrollmentTicket(x,w){let H=await this.request(this.machinePath(x,"/enrollment-tickets"),{method:"POST",body:w,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return W(I,H,"invalid_machine_ticket")}self(x){return this.request("/self",{signal:x})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:x,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:x,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(x,w){let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:x,signal:w});return W(f,H,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(x)}`,{method:"POST",body:w,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(x){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:{messages:x},signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((w)=>typeof w.email==="string"?[{email:w.email,role:typeof w.role==="string"?w.role:"member"}]:[])}claimExistingCliPairing(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:x}})}async claudeCodeSignIn(x){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:x?AbortSignal.any([x,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(x,w,H={}){let G=x.kind==="setup_token"?{setup_token:x.token}:{access_token:x.credential.access,refresh_token:x.credential.refresh,expires_at:new Date(x.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:H.retryUnauthorized,signal:H.signal,body:{...G,...w?{account_key:w}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((w)=>{let H=typeof w.full_name==="string"?w.full_name:typeof w.repo_full_name==="string"?w.repo_full_name:null;if(!H)return[];return[{repo_id:typeof w.repo_id==="string"?w.repo_id:void 0,full_name:H,provider:w.provider==="gitlab"?"gitlab":"github",default_branch:typeof w.default_branch==="string"?w.default_branch:null,private:typeof w.private==="boolean"?w.private:void 0}]})}async listProjects(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),w=V0.safeParse(x);if(!w.success)throw new X(502,"invalid_project_list","Reason returned an unexpected project list.");return w.data.items}async listReasons(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return W(Y0,x,"invalid_reason_list").items}async openReasonConversation(x){let w=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(x)}/conversation`,{method:"POST"});return W($.object({session_id:$.string().min(1)}),w,"invalid_reason_conversation").session_id}async listSkills(){try{let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return W(D0,x,"invalid_skill_list").items}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return[];throw x}}async listDevices(){let x=[],w=null;for(let H=0;H<50;H+=1){let G=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${w?`?after=${encodeURIComponent(w)}`:""}`),J=W0.safeParse(G);if(!J.success)throw new X(502,"invalid_device_list","Reason returned an unexpected machine list.");if(x.push(...J.data.devices),w=J.data.has_next_page?J.data.end_cursor??null:null,!w)break}return x}async listModels(){try{let w=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((J)=>J.hidden!==!0),H=w.filter((J)=>J.available!==!1).map(({reasoning_efforts:J,hidden:Q,available:V,...Z})=>({...Z,...Array.isArray(J)?{reasoning_efforts:J0.filter((Y)=>J.includes(Y))}:{}})),G=new Set(H.map((J)=>J.detail));return{models:H.length>1&&G.size===1?H.map(({detail:J,...Q})=>Q):H,runnable:H.length>0||w.length===0}}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return{models:[],runnable:!0};throw x}}async getAgentVersion(x){try{let w=await this.request("/deployment",{signal:x,retryUnauthorized:!1});return _(w.reason_version)?w.reason_version:null}catch{return null}}async getUsageQuota(){try{let x=$0.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!x.success)return null;let w;try{w=G0(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...x.data,own_inference:w}}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return null;throw x}}async listSessions(x=50,w,H={}){let G=new URLSearchParams({first:String(Math.min(Math.max(x,1),200)),status:H.status??"active"});if(w)G.set("project_id",w);if(H.origin)G.set("origin",H.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${G.toString()}`)).items??[]}getSession(x,w){let H=w?.fields.length?`?fields=${encodeURIComponent(w.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}${H}`)}async prestartSession(x){let w=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:x}});return w?.status==="starting"||w?.status==="ready"}async createSession(x){let w=x.mode==="ephemeral"||x.workspaceOwnership==="externally-managed";if(x.attachments?.length)await this.requireSessionAttachments();if(w||x.runtimeProfile){let J=await this.request("/deployment");if(w&&(!Array.isArray(J.session_modes)||!J.session_modes.includes(x.mode??"standard")||!Array.isArray(J.workspace_ownerships)||!J.workspace_ownerships.includes(x.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(x.runtimeProfile&&(!Array.isArray(J.experimental_runtime_profiles)||!J.experimental_runtime_profiles.includes(x.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:x.prompt,...x.attachments?.length?{attachments:x.attachments}:{},...x.mode?{mode:x.mode}:{},...x.workspaceOwnership?{workspace_ownership:x.workspaceOwnership}:{},...x.target?{target:x.target}:{},...x.repo?{repo:x.repo}:{},...x.provider?{provider:x.provider}:{},...x.model?{model:x.model}:{},...x.reasoningEffort?{reasoning_effort:x.reasoningEffort}:{},...x.runtimeProfile?{experimental_runtime_profile:x.runtimeProfile}:{},...x.ref?{ref:x.ref}:{},...x.branch?{branch:x.branch}:{},...x.completionMode?{completion_mode:x.completionMode}:{},...x.env&&Object.keys(x.env).length>0?{env:x.env}:{},...x.clientSessionId?{client_session_id:x.clientSessionId}:{},...x.longRunning?{long_running:{enabled:!0}}:{},...x.spendLimitRcu?{spend_limit_rcu:x.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),G=await this.getSession(H.session_id);if(w){let J=G.session_policy,Q=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!J||J.version!==1||J.mode!==(x.mode??"standard")||J.workspaceOwnership!==(x.workspaceOwnership??"managed")||!J.components||Q.some((V)=>J.components[V]!==!0))throw await this.cancelSession(H.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(x.runtimeProfile&&G.experimental_runtime_profile!==x.runtimeProfile)throw await this.cancelSession(H.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return G}async getEvents(x,w=-1,H={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/events?after_seq=${w}&limit=500${H.waitMs?`&wait_ms=${H.waitMs}`:""}`,H.signal?{signal:H.signal}:{})}catch(G){if(!(G instanceof X)||G.status!==403&&G.status!==404)throw G;return{session:await this.getSession(x),items:[],next_seq:w}}}async getMessages(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages?first=500${w===void 0?"":`&after_seq=${w}`}`)}async getAttachments(x,w){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/attachments${w?`?view=${w}`:""}`)).items??[]}catch(H){if(H instanceof X&&(H.status===403||H.status===404))return[];throw H}}async requireSessionAttachments(){let x=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(x.session_attachments!==!0){let w=typeof x.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(x.reason_version)?`Agent ${x.reason_version}`:null,H=typeof x.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(x.commit_sha)?`server ${x.commit_sha.slice(0,12)}`:null,G=[w,H].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${G?` (${G})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(x,w,H={}){if(H.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages`,{method:"POST",body:{message:w,...H.attachments?.length?{attachments:H.attachments}:{},...H.model?{model:H.model}:{},...H.reasoningEffort?{reasoning_effort:H.reasoningEffort}:{},...H.target?{target:H.target}:{},...H.delivery?{delivery:H.delivery}:{}}})}async steerQueuedMessage(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages/${encodeURIComponent(w)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages/${encodeURIComponent(w)}/queued`,{method:"DELETE"})}async getConversation(x){let w=[],H=null;for(let G=0;G<50;G+=1){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/conversation${H?`?after=${encodeURIComponent(H)}`:""}`);if(w.push(...J.items??[]),!J.has_next_page||!J.end_cursor)break;H=J.end_cursor}return w}createSharedLink(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/shared-links`,{method:"POST",body:{url:w.url,...w.label?{label:w.label}:{},...w.expiresInSeconds!==void 0?{expires_in_seconds:w.expiresInSeconds}:{}}})}sessionAction(x,w,H={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/${w}`,{method:"POST",body:H})}renameSession(x,w){return this.sessionAction(x,"rename",{title:w||null})}moveSessionToProject(x,w){return this.sessionAction(x,"project",{project_id:w})}compactSession(x){return this.sessionAction(x,"compact")}retrySession(x){return this.sessionAction(x,"retry")}rewindSession(x,w){return this.sessionAction(x,"rewind",{message_id:w.messageId,content:w.content,request_id:w.requestId})}forkSession(x,w){return this.sessionAction(x,"fork",{...w.message?{message:w.message}:{},client_session_id:w.clientSessionId})}cancelSession(x,w={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/cancel`,{method:"POST",body:w.mode==="hard"?{mode:"hard"}:{}})}sessionPath(x,w=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}${w}`}async archiveSession(x){await this.request(this.sessionPath(x,"/archive"),{method:"POST",body:{}})}async unarchiveSession(x){await this.request(this.sessionPath(x,"/unarchive"),{method:"POST",body:{}})}async deleteSession(x){await this.request(this.sessionPath(x),{method:"DELETE"})}async listSessionTags(x){return W(E,await this.request(this.sessionPath(x,"/tags")),"invalid_session_tags").tags}async appendSessionTags(x,w){let H=await this.request(this.sessionPath(x,"/tags"),{method:"POST",body:{tags:w}});return W(E,H,"invalid_session_tags").tags}async sessionInsight(x,w=!1){let H=await this.request(this.sessionPath(x,w?"/insights/generate":"/insights"),w?{method:"POST",body:{}}:{});return W(P0,H,"invalid_session_insight")}async listAutomations(){let x=[],w=null;for(let H=0;H<20;H+=1){let G=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${w?`&after=${encodeURIComponent(w)}`:""}`),J=W(N0,G,"invalid_automation_list");if(x.push(...J.items),w=J.has_next_page?J.end_cursor??null:null,!w)break}return x}async createScheduledAutomation(x,w){let H=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,G=W(h,await this.request(H,{method:"POST",body:{name:x.name,instructions:x.instructions,...x.repo?{repo:x.repo.full_name,provider:x.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${H}/${encodeURIComponent(G.id)}/triggers`,{method:"POST",body:w})}catch(J){throw await this.deleteAutomation(G.id).catch(()=>{return}),J}return G}async setAutomationEnabled(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(x)}`,{method:"PATCH",body:{enabled:w}})}async deleteAutomation(x){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(x)}`,{method:"DELETE"})}async transcribe(x,w){let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:x,contentType:w}});return W($.object({transcript:$.string()}),H,"invalid_transcript").transcript}async listMcpServers(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return W(M0,x,"invalid_mcp_server_list").items}async setSkillEnabled(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(x)}`,{method:"PUT",body:{is_enabled:w}})}}
5
- export{B as A,M as B,n0 as C,P as D,o0 as E,X as F,J0 as G,H1 as H,G1 as I,J1 as J,A0 as K};
2
+ import{wa as f}from"./vm-hands-entry-lite-9cmfthkq.js";import{mi as K,qi as U,ri as y,xi as T}from"./vm-hands-entry-lite-e2mjbqmr.js";import{Ci as v}from"./vm-hands-entry-lite-ma001vzh.js";import{ik as $}from"./vm-hands-entry-lite-zjfr0zh8.js";var u=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function _(x){let w=typeof x==="string"?u.exec(x):null;return w?{major:Number(w[1]),minor:Number(w[2])}:null}import{createHash as s,randomBytes as j}from"crypto";import{createInterface as o}from"readline";import{randomBytes as d}from"crypto";import{chmodSync as q,existsSync as C,lstatSync as l,mkdirSync as a,readFileSync as b,renameSync as p,unlinkSync as O,writeFileSync as L}from"fs";import{homedir as t}from"os";import{dirname as i,join as F}from"path";function B(x=process.env,w=t()){let H=x.XDG_CONFIG_HOME?.trim()||F(w,".config"),J=K({env:x})==="staging"?["staging"]:[];return F(T(H,...J),"credentials.json")}function A(x,w=B()){return a(i(w),{recursive:!0,mode:448}),L(w,`${JSON.stringify(x,null,2)}
3
+ `,{mode:384}),q(w,384),w}function M(x=B()){if(!C(x))return null;try{let w=b(x,"utf8"),H=JSON.parse(w);if(typeof H.apiOrigin!=="string"||typeof H.clientId!=="string"||typeof H.accessToken!=="string"||typeof H.refreshToken!=="string"||typeof H.expiresAt!=="string"||typeof H.orgId!=="string"||!Array.isArray(H.scopes))return null;let G=new URL(H.apiOrigin).origin,J=U(G);if(J!==G)n(x,w,J);return{apiOrigin:J,clientId:H.clientId,accessToken:H.accessToken,refreshToken:H.refreshToken,expiresAt:H.expiresAt,scopes:H.scopes.filter((Q)=>typeof Q==="string"),orgId:H.orgId}}catch{return null}}function n(x,w,H){let G=`${x}.${process.pid}.${d(6).toString("hex")}.tmp`;try{let J=l(x);if(!J.isFile()||process.platform!=="win32"&&J.uid!==process.geteuid?.())return;let Q=JSON.parse(w);if(L(G,`${JSON.stringify({...Q,apiOrigin:H},null,2)}
4
+ `,{mode:384,flag:"wx"}),q(G,384),b(x,"utf8")!==w)throw Error("credentials_changed");p(G,x)}catch{try{O(G)}catch{}}}function R(x=B()){if(!C(x))return!1;return O(x),!0}var S=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var o0=S.filter((x)=>x!=="network:read"&&x!=="network:write");class D extends Error{oauthCode;constructor(x,w=null){super(x);this.oauthCode=w;this.name="LoginError"}}function r0(){let x=j(48).toString("base64url"),w=s("sha256").update(x).digest("base64url");return{verifier:x,challenge:w,state:j(32).toString("base64url")}}function r(x,w){let H=typeof x.error==="string"?x.error:null,G=typeof x.error_description==="string"?x.error_description:H?H:w;return new D(G,H)}async function e(x,w,H,G){let J=await H(`${x}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:w,signal:G}),Q=await J.json().catch(()=>({}));if(!J.ok)throw r(Q,`OAuth token request failed (${J.status})`);return Q}var x0=1e4;async function w0(x,w={}){let H=w.fetchImpl??fetch,G=await e(x.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:x.clientId,refresh_token:x.refreshToken}),H,AbortSignal.timeout(x0)).catch((Q)=>{if(Q instanceof Error&&Q.name==="TimeoutError")throw new D("Reason did not answer the login refresh in time. Check the network and retry.");throw Q});if(typeof G.access_token!=="string"||typeof G.refresh_token!=="string"||typeof G.expires_in!=="number")throw new D("Reason returned an incomplete refreshed login.");let J={...x,accessToken:G.access_token,refreshToken:G.refresh_token,expiresAt:new Date(Date.now()+G.expires_in*1000).toISOString(),scopes:typeof G.scope==="string"?G.scope.split(/\s+/).filter(Boolean):x.scopes};return A(J,w.path??B()),J}var z=new Map;function k(x,w){if(!w)return x;if(w.aborted)return Promise.reject(w.reason);return new Promise((H,G)=>{let J=()=>G(w.reason);w.addEventListener("abort",J,{once:!0}),x.then(H,G).finally(()=>w.removeEventListener("abort",J))})}async function P(x={}){let w=x.path??B(),H=M(w);if(!H)return null;let G=x.apiOrigin??v(process.env,"REASON_API_URL")?.trim();if(G&&!y(H.apiOrigin,new URL(G).origin))return null;let J=Date.parse(H.expiresAt)<=Date.now()+60000;if(!x.forceRefresh&&!J)return H;let Q=[w,H.apiOrigin,H.clientId,H.refreshToken].join("\x00"),V=z.get(Q);if(V)return k(V,x.signal);let Z;return Z=w0(H,{fetchImpl:x.fetchImpl,path:w}).catch(async(Y)=>{if(!(Y instanceof D)||Y.oauthCode!=="invalid_grant"&&Y.oauthCode!=="invalid_client")throw Y;let N=M(w),c=Y.oauthCode==="invalid_client"?N?.clientId!==H.clientId:N?.refreshToken!==H.refreshToken;if(N&&c)return P({fetchImpl:x.fetchImpl,path:w});return R(w),null}).finally(()=>{if(z.get(Q)===Z)z.delete(Q)}),z.set(Q,Z),k(Z,x.signal)}function e0(x,w){return new Promise((H)=>{let G=o({input:x}),J=!1,Q=(Z)=>{if(J)return;J=!0,w.removeEventListener("abort",V),G.close(),x.pause(),H(Z)},V=()=>Q(null);w.addEventListener("abort",V,{once:!0}),G.once("line",(Z)=>Q(Z)),G.once("close",()=>Q(null))})}var $0=$.object({label:$.string(),used_percent:$.number().min(0).max(100).nullable(),resets_at:$.string().nullable(),exhausted:$.boolean().nullable()}),H0=$.object({groups:$.array($.object({selectable:$.boolean().optional(),accounts:$.array($.object({source_id:$.string().min(1),model_ids:$.array($.string().min(1)).optional()}))}))});function G0(x){let w=H0.safeParse(x);if(!w.success)return;return w.data.groups.some((H)=>H.selectable!==!1&&H.accounts.some((G)=>G.model_ids===void 0||G.model_ids.length>0))}class X extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor(x,w,H,G,J,Q){super(H);this.status=x;this.code=w;this.suggestedModel=G;this.retryAfterMs=J;this.resolutionReason=Q;this.name="ApiError"}static rateLimitDelayMs(x,w){if(!(x instanceof X)||x.status!==429)return null;return Math.min(60000,Math.max(w,x.retryAfterMs??0))}}var J0=["minimal","low","medium","high","xhigh","max"],Q0=$.object({id:$.string().min(1),kind:$.string(),name:$.string(),custom_name:$.string().nullish(),status:$.string(),online:$.boolean(),compatible:$.boolean().optional(),compatibility_reason:$.string().nullish(),folder_lane_of:$.string().nullish(),roots:$.array($.object({id:$.string().min(1),label:$.string()}))}),W0=$.object({devices:$.array(Q0),end_cursor:$.string().nullish(),has_next_page:$.boolean().optional()}),Z0=$.object({id:$.string().min(1),name:$.string()}),V0=$.object({items:$.array(Z0)}),X0=$.object({id:$.string().min(1),name:$.string(),main:$.boolean(),mine:$.boolean(),session_id:$.string().nullish(),appearance:$.object({color:$.string().nullish()}).nullish().catch(null)}),Y0=$.object({items:$.array(X0)}),B0=$.object({skill_id:$.string().min(1),name:$.string(),description:$.string().nullish(),activation_keywords:$.array($.string()).default([]),is_enabled:$.boolean().default(!0)}),D0=$.object({items:$.array(B0).default([])}),z0=$.object({id:$.string().min(1),kind:$.string(),enabled:$.boolean(),schedule:$.object({expression:$.string().nullish(),every_seconds:$.number().nullish(),next_run_at:$.string().nullish()}).nullish(),github:$.object({event:$.string().nullish(),action:$.string().nullish(),repo:$.string().nullish()}).nullish(),last_fired_at:$.string().nullish()}),h=$.object({id:$.string().min(1),name:$.string().nullish(),instructions:$.string().nullish(),enabled:$.boolean(),triggers:$.array(z0).default([])}),N0=$.object({items:$.array(h).default([]),end_cursor:$.string().nullish(),has_next_page:$.boolean().optional()}),K0=$.object({id:$.string().min(1),slug:$.string().nullish(),name:$.string(),description:$.string().nullish(),transport:$.string().nullish(),url:$.string().nullish(),enabled:$.boolean()}),M0=$.object({items:$.array(K0).default([])}),P0=$.object({status:$.string(),summary:$.string().nullish(),category:$.string().nullish(),outcome:$.string().nullish(),message_count:$.number().nullish(),pr_url:$.string().nullish(),cost_usd:$.number().nullish(),generated_at:$.string().nullish()}),E=$.object({tags:$.array($.string()).default([])}),_0=$.enum(["linux","macos"]),I=$.object({id:$.string().min(1),name:$.string().min(1),platform:_0.nullable(),workers:$.object({total:$.number().int(),online:$.number().int(),busy:$.number().int(),idle:$.number().int()}),sessions:$.object({queued:$.number().int(),running:$.number().int()})}),F0=$.object({machines:$.array(I)}),U0=$.object({machine:I}),T0=$.object({deleted:$.literal(!0),revoked_workers:$.number().int(),revoked_tokens:$.number().int()}),q0=$.object({token:$.object({id:$.string().min(1),machine_id:$.string().min(1),token_prefix:$.string()}),secret:$.string().startsWith("rmt_")}),m=$.looseObject({machine_id:$.string().min(1),machine_name:$.string().min(1)}),C0=m.extend({organization_id:$.string().min(1)}),b0=$.object({id:$.string().min(1),name:$.string().min(1),state:$.enum(["waiting","placed"]),queue_position:$.number().int().nullable()});function J1(x){let w=b0.safeParse(x.machine);return w.success?w.data:null}var O0=$.union([$.object({kind:$.literal("cloud")}),$.object({kind:$.enum(["mac","headless"]),device_id:$.string().min(1),root_id:$.string().min(1)})]);function Q1(x){let w=O0.safeParse(x.runs_on);return w.success?w.data:null}function W(x,w,H){let G=x.safeParse(w);if(!G.success)throw new X(502,H,"Reason returned an unexpected response.");return G.data}var L0=$.object({error:$.object({type:$.string(),message:$.string()})});function g(x,w,H){let G=L0.safeParse(w),J=typeof w.error==="string"?w.error:G.success?G.data.error.type:`http_${x}`,Q=typeof w.detail==="string"?w.detail:typeof w.message==="string"?w.message:G.success?G.data.error.message:`Reason request failed (${x}${typeof w.error==="string"?` ${w.error}`:""})`,V=J==="github_connection_required"&&typeof w.connect_url==="string"&&/^https?:\/\//.test(w.connect_url)?` Connect it at ${w.connect_url}`:"",Z=H===null||H.trim()===""?NaN:Number(H);return new X(x,J,`${Q}${V}`,typeof w.suggested_model==="string"?w.suggested_model:void 0,Number.isFinite(Z)&&Z>=0?Z*1000:void 0,typeof w.resolution_reason==="string"?w.resolution_reason:void 0)}async function W1(x){let w=await(x.fetchImpl??fetch)(`${x.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${x.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(x.body),signal:AbortSignal.timeout(30000),redirect:"error"}),H=await w.json().catch(()=>({}));if(!w.ok)throw g(w.status,H,w.headers.get("retry-after"));return W(C0,H,"invalid_machine_ticket")}class A0{options;credentials;constructor(x,w={}){this.options=w;this.credentials=x}trackEvent(x,w={}){}async request(x,w={},H=!1){let G=this.options.fetchImpl??fetch,J=await G(`${this.credentials.apiOrigin}/v3${x}`,{method:w.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":"reason-cli","x-reason-agent":"Reason CLI",...w.raw?{"content-type":w.raw.contentType}:w.body===void 0?{}:{"content-type":"application/json"},...w.headers},body:w.raw?w.raw.bytes:w.body===void 0?void 0:JSON.stringify(w.body),signal:w.signal,redirect:"error"}),Q=await J.json().catch(()=>({}));if(J.status===401&&!H&&w.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let V=await P({fetchImpl:G,path:this.options.credentialsPath,forceRefresh:!0,signal:w.signal});if(V)return this.credentials=V,this.request(x,w,!0)}if(!J.ok)throw g(J.status,Q,J.headers.get("retry-after"));return Q}createHeadlessDeviceEnrollmentTicket(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:x,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(x){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:x,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(w){if(w instanceof X&&(w.status===404||w.status===405||w.status===403&&w.code==="endpoint_not_available"))return null;throw w}}addDeviceRoot(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(x)}/roots`,{method:"POST",body:w,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(x)}/roots/${encodeURIComponent(w)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(x,w=""){let H=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return x===void 0?H:`${H}/${encodeURIComponent(x)}${w}`}async listMachines(){return W(F0,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(x){let w=await this.request(this.machinePath(),{method:"POST",body:{name:x.name,...x.platform?{platform:x.platform}:{}}});return W(U0,w,"invalid_machine").machine}async deleteMachine(x){let w=await this.request(this.machinePath(x),{method:"DELETE"});return W(T0,w,"invalid_machine_deletion")}async createMachineToken(x){let w=await this.request(this.machinePath(x,"/tokens"),{method:"POST",body:{}});return W(q0,w,"invalid_machine_token")}async createMachineEnrollmentTicket(x,w){let H=await this.request(this.machinePath(x,"/enrollment-tickets"),{method:"POST",body:w,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return W(m,H,"invalid_machine_ticket")}self(x){return this.request("/self",{signal:x})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:x,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:x,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(x,w){let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:x,signal:w});return W(f,H,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(x)}`,{method:"POST",body:w,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(x){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:{messages:x},signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((w)=>typeof w.email==="string"?[{email:w.email,role:typeof w.role==="string"?w.role:"member"}]:[])}claimExistingCliPairing(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:x}})}async claudeCodeSignIn(x){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:x?AbortSignal.any([x,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(x,w,H={}){let G=x.kind==="setup_token"?{setup_token:x.token}:{access_token:x.credential.access,refresh_token:x.credential.refresh,expires_at:new Date(x.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:H.retryUnauthorized,signal:H.signal,body:{...G,...w?{account_key:w}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((w)=>{let H=typeof w.full_name==="string"?w.full_name:typeof w.repo_full_name==="string"?w.repo_full_name:null;if(!H)return[];return[{repo_id:typeof w.repo_id==="string"?w.repo_id:void 0,full_name:H,provider:w.provider==="gitlab"?"gitlab":"github",default_branch:typeof w.default_branch==="string"?w.default_branch:null,private:typeof w.private==="boolean"?w.private:void 0}]})}async listProjects(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),w=V0.safeParse(x);if(!w.success)throw new X(502,"invalid_project_list","Reason returned an unexpected project list.");return w.data.items}async listReasons(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return W(Y0,x,"invalid_reason_list").items}async openReasonConversation(x){let w=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(x)}/conversation`,{method:"POST"});return W($.object({session_id:$.string().min(1)}),w,"invalid_reason_conversation").session_id}async listSkills(){try{let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return W(D0,x,"invalid_skill_list").items}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return[];throw x}}async listDevices(){let x=[],w=null;for(let H=0;H<50;H+=1){let G=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${w?`?after=${encodeURIComponent(w)}`:""}`),J=W0.safeParse(G);if(!J.success)throw new X(502,"invalid_device_list","Reason returned an unexpected machine list.");if(x.push(...J.data.devices),w=J.data.has_next_page?J.data.end_cursor??null:null,!w)break}return x}async listModels(){try{let w=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((J)=>J.hidden!==!0),H=w.filter((J)=>J.available!==!1).map(({reasoning_efforts:J,hidden:Q,available:V,...Z})=>({...Z,...Array.isArray(J)?{reasoning_efforts:J0.filter((Y)=>J.includes(Y))}:{}})),G=new Set(H.map((J)=>J.detail));return{models:H.length>1&&G.size===1?H.map(({detail:J,...Q})=>Q):H,runnable:H.length>0||w.length===0}}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return{models:[],runnable:!0};throw x}}async getAgentVersion(x){try{let w=await this.request("/deployment",{signal:x,retryUnauthorized:!1});return _(w.reason_version)?w.reason_version:null}catch{return null}}async getUsageQuota(){try{let x=$0.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!x.success)return null;let w;try{w=G0(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...x.data,own_inference:w}}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return null;throw x}}async listSessions(x=50,w,H={}){let G=new URLSearchParams({first:String(Math.min(Math.max(x,1),200)),status:H.status??"active"});if(w)G.set("project_id",w);if(H.origin)G.set("origin",H.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${G.toString()}`)).items??[]}getSession(x,w){let H=w?.fields.length?`?fields=${encodeURIComponent(w.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}${H}`)}async prestartSession(x){let w=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:x}});return w?.status==="starting"||w?.status==="ready"}async createSession(x){let w=x.mode==="ephemeral"||x.workspaceOwnership==="externally-managed";if(x.attachments?.length)await this.requireSessionAttachments();if(w||x.runtimeProfile){let J=await this.request("/deployment");if(w&&(!Array.isArray(J.session_modes)||!J.session_modes.includes(x.mode??"standard")||!Array.isArray(J.workspace_ownerships)||!J.workspace_ownerships.includes(x.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(x.runtimeProfile&&(!Array.isArray(J.experimental_runtime_profiles)||!J.experimental_runtime_profiles.includes(x.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:x.prompt,...x.attachments?.length?{attachments:x.attachments}:{},...x.mode?{mode:x.mode}:{},...x.workspaceOwnership?{workspace_ownership:x.workspaceOwnership}:{},...x.target?{target:x.target}:{},...x.repo?{repo:x.repo}:{},...x.provider?{provider:x.provider}:{},...x.model?{model:x.model}:{},...x.reasoningEffort?{reasoning_effort:x.reasoningEffort}:{},...x.runtimeProfile?{experimental_runtime_profile:x.runtimeProfile}:{},...x.ref?{ref:x.ref}:{},...x.branch?{branch:x.branch}:{},...x.completionMode?{completion_mode:x.completionMode}:{},...x.env&&Object.keys(x.env).length>0?{env:x.env}:{},...x.clientSessionId?{client_session_id:x.clientSessionId}:{},...x.longRunning?{long_running:{enabled:!0}}:{},...x.spendLimitRcu?{spend_limit_rcu:x.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),G=await this.getSession(H.session_id);if(w){let J=G.session_policy,Q=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!J||J.version!==1||J.mode!==(x.mode??"standard")||J.workspaceOwnership!==(x.workspaceOwnership??"managed")||!J.components||Q.some((V)=>J.components[V]!==!0))throw await this.cancelSession(H.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(x.runtimeProfile&&G.experimental_runtime_profile!==x.runtimeProfile)throw await this.cancelSession(H.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return G}async getEvents(x,w=-1,H={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/events?after_seq=${w}&limit=500${H.waitMs?`&wait_ms=${H.waitMs}`:""}`,H.signal?{signal:H.signal}:{})}catch(G){if(!(G instanceof X)||G.status!==403&&G.status!==404)throw G;return{session:await this.getSession(x),items:[],next_seq:w}}}async getMessages(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages?first=500${w===void 0?"":`&after_seq=${w}`}`)}async getAttachments(x,w){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/attachments${w?`?view=${w}`:""}`)).items??[]}catch(H){if(H instanceof X&&(H.status===403||H.status===404))return[];throw H}}async requireSessionAttachments(){let x=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(x.session_attachments!==!0){let w=typeof x.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(x.reason_version)?`Agent ${x.reason_version}`:null,H=typeof x.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(x.commit_sha)?`server ${x.commit_sha.slice(0,12)}`:null,G=[w,H].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${G?` (${G})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(x,w,H={}){if(H.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages`,{method:"POST",body:{message:w,...H.attachments?.length?{attachments:H.attachments}:{},...H.model?{model:H.model}:{},...H.reasoningEffort?{reasoning_effort:H.reasoningEffort}:{},...H.target?{target:H.target}:{},...H.delivery?{delivery:H.delivery}:{}}})}async steerQueuedMessage(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages/${encodeURIComponent(w)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages/${encodeURIComponent(w)}/queued`,{method:"DELETE"})}async getConversation(x){let w=[],H=null;for(let G=0;G<50;G+=1){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/conversation${H?`?after=${encodeURIComponent(H)}`:""}`);if(w.push(...J.items??[]),!J.has_next_page||!J.end_cursor)break;H=J.end_cursor}return w}createSharedLink(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/shared-links`,{method:"POST",body:{url:w.url,...w.label?{label:w.label}:{},...w.expiresInSeconds!==void 0?{expires_in_seconds:w.expiresInSeconds}:{}}})}sessionAction(x,w,H={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/${w}`,{method:"POST",body:H})}renameSession(x,w){return this.sessionAction(x,"rename",{title:w||null})}moveSessionToProject(x,w){return this.sessionAction(x,"project",{project_id:w})}compactSession(x){return this.sessionAction(x,"compact")}retrySession(x){return this.sessionAction(x,"retry")}rewindSession(x,w){return this.sessionAction(x,"rewind",{message_id:w.messageId,content:w.content,request_id:w.requestId})}forkSession(x,w){return this.sessionAction(x,"fork",{...w.message?{message:w.message}:{},client_session_id:w.clientSessionId})}cancelSession(x,w={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/cancel`,{method:"POST",body:w.mode==="hard"?{mode:"hard"}:{}})}sessionPath(x,w=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}${w}`}async archiveSession(x){await this.request(this.sessionPath(x,"/archive"),{method:"POST",body:{}})}async unarchiveSession(x){await this.request(this.sessionPath(x,"/unarchive"),{method:"POST",body:{}})}async deleteSession(x){await this.request(this.sessionPath(x),{method:"DELETE"})}async listSessionTags(x){return W(E,await this.request(this.sessionPath(x,"/tags")),"invalid_session_tags").tags}async appendSessionTags(x,w){let H=await this.request(this.sessionPath(x,"/tags"),{method:"POST",body:{tags:w}});return W(E,H,"invalid_session_tags").tags}async sessionInsight(x,w=!1){let H=await this.request(this.sessionPath(x,w?"/insights/generate":"/insights"),w?{method:"POST",body:{}}:{});return W(P0,H,"invalid_session_insight")}async listAutomations(){let x=[],w=null;for(let H=0;H<20;H+=1){let G=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${w?`&after=${encodeURIComponent(w)}`:""}`),J=W(N0,G,"invalid_automation_list");if(x.push(...J.items),w=J.has_next_page?J.end_cursor??null:null,!w)break}return x}async createScheduledAutomation(x,w){let H=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,G=W(h,await this.request(H,{method:"POST",body:{name:x.name,instructions:x.instructions,...x.repo?{repo:x.repo.full_name,provider:x.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${H}/${encodeURIComponent(G.id)}/triggers`,{method:"POST",body:w})}catch(J){throw await this.deleteAutomation(G.id).catch(()=>{return}),J}return G}async setAutomationEnabled(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(x)}`,{method:"PATCH",body:{enabled:w}})}async deleteAutomation(x){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(x)}`,{method:"DELETE"})}async transcribe(x,w){let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:x,contentType:w}});return W($.object({transcript:$.string()}),H,"invalid_transcript").transcript}async listMcpServers(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return W(M0,x,"invalid_mcp_server_list").items}async setSkillEnabled(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(x)}`,{method:"PUT",body:{is_enabled:w}})}}
5
+ export{B as A,M as B,r0 as C,P as D,e0 as E,X as F,J0 as G,J1 as H,Q1 as I,W1 as J,A0 as K};