omo-ai 5.1.9 → 5.1.10
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.
- package/package.json +1 -1
- package/plugin/CHANGELOG.md +11 -1
- package/plugin/extensions/memory-run-supervisor.mjs +1 -1
- package/plugin/extensions/omo-computer-use.js +1 -1
- package/plugin/extensions/omo-init-deep-advisor.js +1 -1
- package/plugin/extensions/omo-member.js +1 -1
- package/plugin/extensions/omo-task.js +2 -2
- package/plugin/extensions/omo.js +2 -2
- package/plugin/package.json +1 -1
- package/plugin/runtime/agent-toolkit-sdk/sdk.js +2 -2
- package/plugin/runtime/ast-grep-mcp/manifest.json +1 -1
- package/plugin/runtime/rollback-migrate.js +1 -1
- package/plugin/skills/browser/runtime/omowright/manifest.json +1 -1
package/package.json
CHANGED
package/plugin/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [5.1.10] - 2026-10-02
|
|
11
|
+
|
|
12
|
+
**Hotfix: `omo -p` exits again after a delegated task.** Since 5.1.8, a headless or scripted run whose agent handed work to an in-process task printed its answer and then never exited, so CI jobs, cron entries and wrappers that wait on it hung until killed. Interactive sessions leaked a loopback bridge server and its socket for every such task. This release runs on the senpi 2026.10.1-3 engine.
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
|
|
16
|
+
**`omo -p` exits after an in-process task child finishes, and the child's resources are released.** Since 5.1.8 an in-process child loads the engine's builtin extensions, but its teardown disposed the session without running their `session_shutdown` handlers, so codemode's per-session bridge server stayed listening and kept the process alive. Child teardown now runs those handlers first, within the host's shutdown budget, on both the normal path and the path that discards a child whose handle never started. ([#9413](https://github.com/code-yeongyu/oh-my-openagent/issues/9413), [#9418](https://github.com/code-yeongyu/oh-my-openagent/pull/9418))
|
|
17
|
+
|
|
18
|
+
A delegated task that the host recovers after a restart is reported as continued only once its continuation prompt is acknowledged; a refused or timed-out prompt is now reported as lost instead of a successful reattach. Thanks to @Dante-dan. ([#9406](https://github.com/code-yeongyu/oh-my-openagent/pull/9406))
|
|
19
|
+
|
|
10
20
|
## [5.1.9] - 2026-10-02
|
|
11
21
|
|
|
12
22
|
**In the desktop app's restricted modes, the agent's own tools stop asking for approval, and a bash call from an eval cell no longer hangs.** Files that ship with the app no longer count as outside paths, the first Python cell after a cold start works on Windows x64, and delegated tasks keep your timeout settings and run at thinking levels their models accept. This release runs on the senpi 2026.10.1-3 engine.
|
|
@@ -27,7 +37,7 @@ A delegated task that runs in-process now keeps your timeout and retry settings,
|
|
|
27
37
|
|
|
28
38
|
Builtin category chains only name thinking levels their models accept, so child sessions no longer flood `fallback.log` with `validation_warning` lines and each rung runs at its declared level instead of a silent clamp. Thanks to @markshikada for the report and the byte-compare that pinned it down. ([#9378](https://github.com/code-yeongyu/oh-my-openagent/issues/9378))
|
|
29
39
|
|
|
30
|
-
On macOS, a repeated permission denial no longer claims the privacy pane was just opened; it points at the pane opened earlier, or tells you to open it when the first attempt failed.
|
|
40
|
+
On macOS, a repeated permission denial no longer claims the privacy pane was just opened; it points at the pane opened earlier, or tells you to open it when the first attempt failed.
|
|
31
41
|
|
|
32
42
|
## [5.1.8] - 2026-10-01
|
|
33
43
|
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// omo:
|
|
2
|
+
// omo:TjnQCKXEURxbYg7A7o7hIiZArPEgwqm0UuY_B37usgA:xE1V0Tu0M-W7qbPAWE96oZWECfAaCG1VE1qlEbZRthk
|
|
3
3
|
import{spawn as t}from"node:child_process";import*as e from"node:fs";import*as r from"node:fs/promises";function n(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}async function i(t){for(let e=0;;e+=1)try{return await t()}catch(t){if("EINTR"!==n(t)||e>=128)throw t}}function o(t){for(let e=0;;e+=1)try{return t()}catch(t){if("EINTR"!==n(t)||e>=128)throw t}}import{Buffer as a}from"node:buffer";import{constants as s}from"node:fs";function l(t){return"number"==typeof t?0!==(t&s.O_EXCL):"string"==typeof t&&t.toLowerCase().includes("x")}async function c(t,e,r,n){let o="string"==typeof e?a.from(e,r??"utf8"):e,s=0;for(;s<o.length;){n?.throwIfAborted();let{bytesWritten:e}=await i(()=>t.write(o,s));if(e<=0)throw Error(`fs write made no progress at offset ${s}`);s+=e}}function u(t){return"function"==typeof t}function d(t){return(...e)=>i(async()=>t(...e))}function f(t){return(...e)=>o(()=>t(...e))}function p(t,e){let r="async"===e?d:f,n=new Map;return new Proxy(t,{get(t,e){if(n.has(e))return n.get(e);let i=Reflect.get(t,e);if(!u(i))return i;let o=r(i),a=Reflect.get(i,"native");return u(a)&&Object.assign(o,{native:r(a)}),n.set(e,o),o}})}var m=new Set(["stat","sync","datasync","chmod","chown","utimes","truncate"]);var w=p(r,"async"),h=p(e,"sync"),{access:y,chmod:g,copyFile:v,cp:b,link:E,lstat:S,mkdir:x,mkdtemp:_,readFile:I,readdir:N,realpath:O,rename:k,rm:P,rmdir:T,stat:M,unlink:R}=w,{accessSync:A,chmodSync:$,fsyncSync:L,linkSync:C,lstatSync:D,mkdirSync:U,readFileSync:q,readdirSync:j,realpathSync:F,statSync:J,unlinkSync:G,writeFileSync:H,writeSync:B}=h,{constants:V,watch:Y}=e,K=async(...t)=>{let e=()=>r.open(...t);return function(t){return new Proxy(t,{get(t,e){let r=Reflect.get(t,e);if(!u(r))return r;let o=e=>Reflect.apply(r,t,[...e]);return"close"===e||e===Symbol.asyncDispose?(...t)=>{let e=o(t);return e instanceof Promise?e.catch(t=>{if("EINTR"!==n(t))throw t}):e}:"string"==typeof e&&m.has(e)?(...t)=>{let e=o(t);return e instanceof Promise?e.catch(e=>{if("EINTR"!==n(e))throw e;return i(async()=>o(t))}):e}:(...t)=>o(t)}})}(await(l(t[1]??"r")?e():i(e)))},z=(t,r,n)=>function(t,e,r,n){return l(r)?t(e,r,n):o(()=>t(e,r,n))}(e.openSync,t,r,n??void 0);function X(t){try{e.closeSync(t)}catch(t){if("EINTR"!==n(t))throw t}}function Z(t){try{return o(()=>e.statSync(t)),!0}catch{return!1}}import{join as W}from"node:path";import{fileURLToPath as Q}from"node:url";import{randomUUID as tt}from"node:crypto";import{dirname as et}from"node:path";async function rt(t){return JSON.parse(await I(t,"utf8"))}async function nt(t,e,r=384){let n=`${t}.tmp-${process.pid}-${tt()}`,i=await K(n,"wx",r),o=!1;try{try{await i.writeFile(`${JSON.stringify(e,null,2)}\n`,"utf8"),await i.sync()}finally{await i.close()}await k(n,t),o=!0,await async function(t){try{let e=await K(t,"r");try{await e.sync()}finally{await e.close()}}catch(t){let e=t instanceof Error&&"code"in t?t.code:void 0;if("win32"!==process.platform||!["EISDIR","EPERM"].includes(String(e)))throw t}}(et(t))}finally{o||await ot(n)}}async function it(t,e){let r=await rt(t);await nt(t,{...r,...e})}async function ot(t){try{await R(t)}catch(t){if(!(t instanceof Error&&"code"in t&&"ENOENT"===t.code))throw t}}import{spawn as at,spawnSync as st}from"node:child_process";import{execFile as lt}from"node:child_process";var ct=null;function ut(){return ct??=async function(){if("darwin"!==process.platform)return null;try{let{dlopen:t,FFIType:e}=await(import("bun:ffi")),r=t("/usr/lib/libSystem.B.dylib",{proc_pidinfo:{args:[e.i32,e.i32,e.u64,e.ptr,e.i32],returns:e.i32}});return(t,e,n,i,o)=>Number(r.symbols.proc_pidinfo(t,e,n,i,o))}catch{return null}}(),ct}var dt=null;async function ft(t){if("win32"!==process.platform)return null;if(!Number.isSafeInteger(t)||t<=0)return null;dt??=async function(){if("win32"!==process.platform)return null;try{let{dlopen:t,FFIType:e}=await(import("bun:ffi"));return t("kernel32.dll",{OpenProcess:{args:[e.u32,e.i32,e.u32],returns:e.ptr},GetProcessTimes:{args:[e.ptr,e.ptr,e.ptr,e.ptr,e.ptr],returns:e.i32},CloseHandle:{args:[e.ptr],returns:e.i32}}).symbols}catch{return null}}();let e=await dt;if(null===e)return null;let r=e.OpenProcess(4096,0,t);if(null===r||0===r||0n===r)return null;try{let t=new BigUint64Array(1),n=e.GetProcessTimes(r,t,new BigUint64Array(1),new BigUint64Array(1),new BigUint64Array(1)),i=t[0]??0n;return 0===n||0n===i?null:i}finally{e.CloseHandle(r)}}async function pt(t,e){return await new Promise(r=>{lt(t,e,{encoding:"utf8",timeout:2e3,windowsHide:!0},(t,e)=>{if(null!==t)return void r(null);let n=e.trim();r(n.length>0?n:null)})})}var mt=function(t,e){let r;return n=>n!==e?t(n):(r??=t(n).then(t=>(null===t&&(r=void 0),t),t=>{throw r=void 0,t}),r)}(async function(t){if("linux"===process.platform)return await async function(t){try{let e=await I(`/proc/${t}/stat`,"utf8"),r=e.lastIndexOf(")");if(r<0)return null;let n=e.slice(r+2).trim().split(/\s+/)[19];return void 0===n?null:`linux-proc-start-ticks:${n}`}catch{return null}}(t);if("darwin"===process.platform||"freebsd"===process.platform){if("dead"===ht(t))return null;let e=await async function(t){if("darwin"!==process.platform)return null;if(!Number.isSafeInteger(t)||t<=0)return null;let e=await ut();if(null===e)return null;let r=new Uint8Array(136),n=0;try{n=e(t,3,0n,r,136)}catch{return null}if(136!==n)return null;let i=new DataView(r.buffer,r.byteOffset,r.byteLength),o=Number(i.getBigUint64(120,!0));return o>0?o:null}(t);if(null!==e)return`proc-start-epoch:${e}`;let r=await pt("/bin/ps",["-o","lstart=","-p",String(t)]);return null===r?null:`ps-lstart:${r.replace(/\s+/g," ")}`}return"win32"===process.platform?await async function(t){if("dead"===ht(t))return null;let e=await ft(t);if(null!==e)return`win32-creation-filetime:${e}`;let r=await pt("powershell.exe",["-NoProfile","-Command",`(Get-Process -Id ${t} -ErrorAction SilentlyContinue).StartTime.ToUniversalTime().ToString('o')`]);return null===r?null:`win32-creation-date:${r}`}(t):null},process.pid);function wt(t){let e=t.indexOf(":");return e<=0?null:t.slice(0,e)}function ht(t){try{return process.kill(t,0),"alive"}catch(t){let e=function(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}(t);return"ESRCH"===e?"dead":"EPERM"===e?"alive":"unknown"}}function yt(){return"1"===process.env.OMO_MEMORY_SUPERVISOR_ALLOW_TEST_SEAMS}function gt(){if(yt()){let t=process.env.OMO_MEMORY_SUPERVISOR_PLATFORM;if("posix"===t||"win32"===t)return t}return"win32"===process.platform?"win32":"posix"}function vt(t,e){let r=yt()?process.env.OMO_MEMORY_SUPERVISOR_CLOCK_PATH:void 0;if(void 0===r){let r=setTimeout(e,Math.max(0,t-Date.now()));return()=>clearTimeout(r)}let n=!1,i=()=>{if(n)return;let i=Et(r);!Number.isFinite(i)||i<t||(n=!0,o?.close(),clearInterval(a),e())};if(Et(r)>=t)return n=!0,e(),()=>{};let o=Y(r,i),a=setInterval(i,bt);return i(),()=>{n||(n=!0,o.close(),clearInterval(a))}}var bt=25;function Et(t){let e=j(t).map(t=>/^(\d+)-(-?\d+(?:\.\d+)?)$/.exec(t)).filter(t=>null!==t).sort((t,e)=>Number(t[1])-Number(e[1])).at(-1);return void 0===e?Number.NaN:Number(e[2])}function St(t,e){if(!yt())return;let r=process.env.OMO_MEMORY_SUPERVISOR_TASKKILL_RUN_DIR;void 0!==r&&H(`${r}/${t}-${process.pid}.json`,`${JSON.stringify({targetPid:e})}\n`,"utf8")}function xt(t){if(!yt())return;let e=process.env[t];if(void 0===e)return;let r=JSON.parse(e);if(!Array.isArray(r)||!r.every(t=>"string"==typeof t)||0===r.length)throw TypeError(`${t} must be a non-empty string array`);return r}function _t(t,e,r){let[n,...i]=t;if(void 0===n)throw TypeError("termination command is required");if(r){let t=st(n,[...i,...e],{env:process.env,stdio:"ignore",windowsHide:!0});if(void 0!==t.error)throw t.error;return}at(n,[...i,...e],{env:process.env,stdio:"ignore",windowsHide:!0}).once("error",t=>process.stderr.write(`${t.message}\n`))}function It(t,e){St(`posix-${e}`,t);let r=xt("OMO_MEMORY_SUPERVISOR_POSIX_SIGNAL_COMMAND");if(void 0===r)try{process.kill(-t,e)}catch(t){if(!(t instanceof Error&&"code"in t&&"ESRCH"===t.code))throw t}else _t(r,["--signal-group",String(t),e],!1)}function Nt(t){void 0!==t&&St("win32-graceful",t)}function Ot(t,e){"win32"===t?(Nt(e.pid),e.kill()):void 0!==e.pid&&It(e.pid,"SIGTERM")}function kt(t,e,r=!1){void 0!==e&&("win32"===t?function(t,e){_t(xt("OMO_MEMORY_SUPERVISOR_TASKKILL_COMMAND")??["taskkill"],["/pid",String(t),"/T","/F"],e)}(e,r):It(e,"SIGKILL"))}async function Pt(t){return await mt(t)}import{join as Tt}from"node:path";function Mt(t){return"object"==typeof t&&null!==t}function Rt(t,e){try{return t?.[e]}catch(t){return void Error}}function At(t,e){let r=Rt(t,e);return Mt(r)?r:void 0}function $t(t){if(!t)return"";if("string"==typeof t)return t.toLowerCase();if(!Mt(t))try{return JSON.stringify(t).toLowerCase()}catch(t){if(!(t instanceof Error))throw t;return""}let e=At(t,"data"),r=[e,At(t,"error"),t,At(e,"error")].filter(t=>void 0!==t);for(let t of r){let e=Rt(t,"message");if("string"==typeof e&&e.length>0)return e.toLowerCase()}let n=Rt(t,"name");if("string"==typeof n&&n.length>0){let t=n.match(/:\s*(.+)/);if(t)return t[1]?.trim().toLowerCase()??""}try{return JSON.stringify(t).toLowerCase()}catch(t){if(!(t instanceof Error))throw t;return""}}function Lt(t,e){if(function(t){return"object"==typeof t&&null!==t}(t))try{return t[e]}catch(t){return void Error}}function Ct(t){return"terminal_quota_exhausted"===function(t){let e=Lt(t,"data"),r=Lt(t,"detail")??Lt(e,"detail")??t,n=Lt(r,"error")??r,i=Lt(n,"type")??Lt(r,"type");return"string"==typeof i?i.toLowerCase():void 0}(t)||(e=$t(t),!/\bnon[-\s]+terminal\s+quota\b/i.test(e)&&!/\bnon[-\s]+terminal\s+billing\s+limit\b/i.test(e)&&(/\bterminal\s+quota\b/i.test(e)||/\bterminal\s+billing\s+limit\b/i.test(e)||/\bhard\s+billing\s+limit\b/i.test(e)));var e}function Dt(t){if(Ct(t))return"abort";let e=$t(t),r=function(t){if(!Mt(t))return;let e=At(t,"data"),r=[t,e,At(t,"error"),At(e,"error")].filter(t=>void 0!==t);for(let t of r){let e=Rt(t,"name");if("string"==typeof e&&e.length>0)return e}}(t)?.toLowerCase().replace(/[_-]/g,"");return r?.includes("messageabortederror")||r?.includes("aborterror")?"abort":"contextoverflowerror"===r?"context_overflow":r?.includes("ailoadapikeyerror")||r?.includes("loadapi")||/api.?key.?is.?missing/i.test(e)&&/environment variable/i.test(e)?"missing_api_key":/api.?key/i.test(e)&&/must be a string/i.test(e)?"invalid_api_key":r?.includes("providermodelnotfounderror")||r?.includes("modelnotfounderror")||r?.includes("unknownerror")&&/model\s+not\s+found/i.test(e)?"model_not_found":r?.includes("quotaexceeded")||r?.includes("insufficientquota")||r?.includes("billingerror")||r?.includes("resourceexhausted")||r?.includes("insufficientcredits")||r?.includes("usagelimit")||/quota.?exceeded/i.test(e)||/exceeded.*quota/i.test(e)||/quota\b.*\breset/i.test(e)||/usage\s*quota/i.test(e)||/subscription.?(?:quota|limit)/i.test(e)||/insufficient.?(?:quota|balance|funds?|credits?)/i.test(e)||/credits?\s+exhausted/i.test(e)||/\b(?:session|weekly|monthly|daily|hourly|\d+[-\s]hour|plan|call)\s+limit\b/i.test(e)||/\bhit\s+your\b[^.]*\blimit\b/i.test(e)||/\bin\s+arrears\b/i.test(e)||/\brecharge\s+and\s+try\b/i.test(e)||/billing.?(?:hard.?)?limit/i.test(e)||/exhausted\s+your\s+capacity/i.test(e)||/resource.?exhausted/i.test(e)||/out\s+of\s+credits?/i.test(e)||/payment.?required/i.test(e)||/usage\s+limit/i.test(e)||/credit\s+balance.*too\s+low/i.test(e)||/limit\s+exhausted/i.test(e)||/使用上限/.test(e)||/用量上限/.test(e)||/达到.*限制/.test(e)||/额度.*不足/.test(e)||/余额.*不足/.test(e)||/已耗尽/.test(e)||function(t){return/预扣费额度失败/i.test(t)&&/用户剩余额度/i.test(t)||/用户剩余额度/i.test(t)&&/需要预扣费额度/i.test(t)}(e)?"quota_exceeded":void 0}var Ut=new Set(["providermodelnotfounderror","ratelimiterror","modelunavailableerror","providerconnectionerror","authenticationerror"]),qt=new Set(["messageabortederror","permissiondeniederror","contextlengtherror","timeouterror","validationerror","syntaxerror","usererror"]),jt=["rate_limit","rate limit","usage_limit_reached","usage limit has been reached","quota","all credentials for model","cooling down","exhausted your capacity","not found","unavailable","insufficient","too many requests","over limit","overloaded","bad gateway","bad request","unknown provider","provider not found","model_not_supported","model not supported","model is not supported","connection error","network error","timeout","service unavailable","internal_server_error","free usage","usage exceeded","credit","balance","temporarily unavailable","try again","请稍后重试","503","502","504","429","529","selected provider is forbidden","provider is forbidden","频率限制","请求过于频繁","暂时不可用","服务不可用","server_error","an error occurred while processing","upstream request failed"],Ft=["rate limit","cooling down","credentials for model"];function Jt(t){let e=t.name?.toLowerCase();if(void 0!==e&&qt.has(e))return!1;if(Ct(t))return!1;if("quota_exceeded"===Dt(t))return!0;if(void 0!==e&&Ut.has(e))return!0;let r=t.message?.toLowerCase()??"";return!(!(n=r).includes("retrying in")||!Ft.some(t=>n.includes(t)))||(null!=t.statusCode&&(429===t.statusCode||503===t.statusCode||529===t.statusCode)||jt.some(t=>r.includes(t)));var n}var Gt=[/prompt is too long/i,/request_too_large/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \d+ tokens/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/model_context_window_exceeded/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i,/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,/(?:request[ _])?(?:body|entity|payload)[_ ]too[_ ]large/i,/Request payload is \d+ (?:bytes, over the \d+ byte|tokens, over the \d+ token) limit Kiro accepts\./i,/Model context limit reached\. Conversation size exceeds model capacity\./i],Ht=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];var Bt=/^Error: Model "([^"]+)" not found\. Use --list-models to see available models\.$/m,Vt=/^(?:Error:\s*)?No API key found for\s+([^\s.]+)/m,Yt=/(?:^|\s)(\d{3})\s*:/;function Kt(t){if(t.timedOut||0===t.code)return;let e=`${t.stderr}\n${t.stdout}`,r=Bt.exec(e)?.[1];if(void 0!==r)return{kind:"model_not_visible",id:r};let n=Vt.exec(e)?.[1];if(void 0!==n)return{kind:"auth_missing",provider:n};let i=function(t){for(let e of[t.stderr,t.stdout]){let t=e.split("\n").map(t=>t.trim()).find(t=>t.length>0);if(void 0!==t)return t.slice(0,200)}return}(t);if(void 0===i)return;if(o=i,!Ht.some(t=>t.test(o))&&Gt.some(t=>t.test(o)))return{kind:"context_overflow",detail:i};var o;let a=Number.parseInt(Yt.exec(i)?.[1]??"",10);return Jt({message:i,...Number.isNaN(a)?{}:{statusCode:a}})?{kind:"provider_unavailable",detail:i}:void 0}import{randomUUID as zt}from"node:crypto";import{dirname as Xt,join as Zt}from"node:path";import{randomUUID as Wt}from"node:crypto";import{hostname as Qt}from"node:os";import te from"node:path";import ee from"node:path";var re=new Set;function ne(t){re.add(t)}function ie(t){re.delete(t)}var oe=/\.candidate-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ae(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}function se(t,e){try{t.onFailure?.(e)}catch{}}function le(t){if("win32"!==process.platform)return!1;let e=ae(t);return"EBUSY"===e||"EPERM"===e||"EACCES"===e}import{randomUUID as ce}from"node:crypto";import{hostname as ue}from"node:os";function de(t){return"string"==typeof t&&t.length>0}function fe(t){let e;try{e=JSON.parse(t)}catch{return null}if("object"!=typeof e||null===e||Array.isArray(e))return null;let r=e;return!Number.isInteger(r.pid)||Number(r.pid)<=0?null:de(r.process_start)&&de(r.hostname)&&de(r.nonce)?!de(r.created_at)||Number.isNaN(Date.parse(r.created_at))?null:de(r.purpose)&&(void 0===r.run_id||de(r.run_id))?{pid:Number(r.pid),process_start:r.process_start,hostname:r.hostname,nonce:r.nonce,created_at:r.created_at,purpose:r.purpose,...void 0===r.run_id?{}:{run_id:r.run_id}}:null:null}async function pe(t,e={}){if(0===t.length)throw Error("lock purpose must not be empty");let r=await mt(process.pid);return{pid:process.pid,process_start:r??"unavailable",hostname:ue(),nonce:ce(),created_at:(new Date).toISOString(),purpose:t,...void 0===e.runId?{}:{run_id:e.runId}}}var me=new Set(["EACCES","EPERM","ENOTSUP"]);class we extends Error{lockPath;owner;retriable=!0;constructor(t,e){super(`Lock is held: ${t}`),this.lockPath=t,this.owner=e,this.name="LockContentionError"}}function he(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}function ye(t,e){if(void 0!==e)return e(t);if("win32"!==process.platform)return!1;let r=he(t);return"EBUSY"===r||"EPERM"===r||"EACCES"===r}async function ge(t){for(let e=0;e<3;e+=1)try{return await(xe.unlink??R)(t),ie(t),!0}catch(r){if("ENOENT"===he(r))return ie(t),!0;if(!ye(r,xe.isSharingError))throw ne(t),_e(te.dirname(t)),r;if(e+1===3)return ne(t),_e(te.dirname(t)),!1}return!1}function ve(t,e){return e?.throwIfAborted(),new Promise((r,n)=>{let i=setTimeout(a,t),o=()=>a(e?.reason??new DOMException("The operation was aborted","AbortError"));function a(t){clearTimeout(i),e?.removeEventListener("abort",o),void 0===t?r():n(t)}e?.addEventListener("abort",o,{once:!0})})}async function be(t){try{let e=await I(t,"utf8"),r=await M(t,{bigint:!0});return{raw:e,record:fe(e),dev:r.dev,ino:r.ino,mtimeMs:Number(r.mtimeMs)}}catch(t){let e=he(t);if("ENOENT"===e)return null;if("\\"===te.sep&&"EPERM"===e)return{raw:"",record:null,dev:0,ino:0,mtimeMs:Date.now()};throw t}}async function Ee(t,e){await x(te.dirname(t),{recursive:!0,mode:448});let{candidatePath:r,handle:n}=await async function(t){for(let e=0;;e+=1){let r=`${t}.candidate-${Wt()}`;try{return{candidatePath:r,handle:await K(r,"wx",384)}}catch(n){if(await ge(r)||_e(te.dirname(t)),"EINTR"!==he(n)||e>=128)throw n}}}(t);try{try{await c(n,`${JSON.stringify(e)}\n`,"utf8"),await n.sync()}finally{await n.close()}try{return await(xe.link??E)(r,t),!0}catch(r){if(function(t){let e=he(t);return"EEXIST"===e||"ENOENT"===e}(r))return!1;if(me.has(he(r)??""))return await async function(t,e){let r;try{r=await K(t,"wx",384)}catch(t){if("EEXIST"===he(t))return!1;throw t}try{return await(xe.writeFallback??c)(r,`${JSON.stringify(e)}\n`,"utf8"),await r.sync(),!0}finally{await r.close()}}(t,e);throw r}}finally{await ge(r)||_e(te.dirname(t))}}var Se=new Set,xe={};function _e(t){Se.delete(t)}async function Ie(t){if(t.hostname!==Qt())return!1;let e=ht(t.pid);if("dead"===e)return!0;if("unknown"===e)return!1;let r=await mt(t.pid);return null!==r&&"unavailable"!==t.process_start&&function(t,e){let r=wt(t);return null!==r&&r===wt(e)&&t!==e}(t.process_start,r)}function Ne(t,e){return t.dev===e.dev&&t.ino===e.ino&&t.mtimeMs===e.mtimeMs&&t.raw===e.raw}async function Oe(t,e,r){return null!==t.record?Ie(t.record):e-t.mtimeMs>r}async function ke(t,e,r){let n=await be(t);if(null===n||!await Oe(n,e,r))return!1;let i=`${t}.reaping-${Wt()}`;try{await k(t,i)}catch(t){if("ENOENT"===he(t))return!1;if(ye(t))return!1;throw t}let o=await be(i);if(null!==o&&Ne(o,n))return await R(i),!0;try{await E(i,t)}catch(t){if("EEXIST"!==he(t))throw t}return await R(i),!1}async function Pe(t,e,r,n,i){if(!await Oe(e,n,i))return!1;let o=`${t}.recovery`,a={...r,nonce:Wt(),created_at:(new Date).toISOString(),purpose:`${r.purpose}:recovery`};for(let t=0;!await Ee(o,a);t+=1)if(t>0||!await ke(o,n,i))return!1;try{let r=await be(t);if(null===r)return!0;if(!Ne(r,e))return!1;if(!await Oe(r,n,i))return!1;let s=await be(o);return null!==s&&s.record?.nonce===a.nonce&&(await R(t),!0)}finally{await Me(o,a)}}async function Te(t,e,r={}){let n=r.waitTimeoutMs??0,i=r.retryDelayMs??25,o=r.incompleteLockGraceMs??5e3,a=r.now??Date.now;if(n<0||i<=0||o<0)throw Error("lock wait options must be positive");let s=te.dirname(t);Se.has(s)||(Se.add(s),await async function(t,e=Date.now,r={}){let n;try{n=await N(t)}catch(e){if("ENOENT"===ae(e)){for(let e of re)ee.dirname(e)===t&&ie(e);return 0}throw e}let i=0;for(let o of n){if(!oe.test(o))continue;let n=ee.join(t,o);try{let t=await M(n);if(!re.has(n)&&e()-t.mtimeMs<=36e5)continue;let o=!1;for(let t=0;t<3;t+=1)try{await(r.unlink??R)(n),ie(n),o=!0;break}catch(e){if("ENOENT"===ae(e)){ie(n),o=!0;break}if(!(r.isSharingError?.(e)??le(e)))throw e;t+1===3&&se(r,n)}o&&(i+=1)}catch(t){"ENOENT"===ae(t)&&ie(n),se(r,n)}}return i}(s,Date.now,{...void 0===xe.unlink?{}:{unlink:xe.unlink},...void 0===xe.isSharingError?{}:{isSharingError:xe.isSharingError},onFailure:()=>_e(s)}).catch(()=>{_e(s)}));let l=a()+n;for(;;){r.signal?.throwIfAborted();let n=await be(t);if(null===n){if(await Ee(t,e))return;if(r.signal?.throwIfAborted(),n=await be(t),null===n)continue}if(!await Pe(t,n,e,a(),o)){if(r.signal?.throwIfAborted(),a()>=l)throw new we(t,n.record);await ve(Math.min(i,Math.max(1,l-a())),r.signal)}}}async function Me(t,e){let r=await be(t);if(null===r||r.record?.nonce!==e.nonce)return!1;try{return await R(t),!0}catch(t){if("ENOENT"===he(t))return!1;throw t}}async function Re(t,e,r,n){await Te(t,e,n);try{return await r()}finally{await Me(t,e)}}Promise.resolve();var Ae=[["\\bAKIA[0-9A-Z]{16}\\b",""],["\\b(?:bearer|token|api[_-]?key|secret|password|passwd|pwd)\\s*[=:]\\s*\\S{1,256}","i"],["\\bAuthorization\\s*:\\s*Bearer\\s+\\S{1,256}","i"],["\\bsk-(?:proj-)?[-_A-Za-z0-9]+\\b",""],["\\b(?:ghp|github_pat|glpat|xox[baprs])-[-_A-Za-z0-9]+\\b",""]];Ae.map(([t,e])=>new RegExp(t,e)),Ae.map(([t,e])=>new RegExp(t,`${e}g`));new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});import{dirname as $e}from"node:path";import{fileURLToPath as Le}from"node:url";$e(Le(import.meta.url));import{dirname as Ce}from"node:path";import{fileURLToPath as De}from"node:url";Ce(De(import.meta.url)),new Date(0).toISOString();var Ue="\\p{Script=Hangul}\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\u30fc";new RegExp(`[${Ue}]+|(?:(?![${Ue}])[\\p{L}\\p{M}\\p{N}])+`,"gu"),new RegExp(`^[${Ue}]+$`,"u"),new RegExp(`[${Ue}]`,"u"),new RegExp(`[${Ue}]`,"gu"),new RegExp(`[\\p{L}${Ue}]`,"gu");import{dirname as qe}from"node:path";import{fileURLToPath as je}from"node:url";qe(je(import.meta.url));function Fe(t){return Zt(t,"terminal-claim.json")}function Je(t,e,r){return t.runId===e.runId&&t.attempt===e.attempt&&(void 0===r||t.kind===r)}function Ge(t,e){let r=`${t}.${process.pid}.${zt()}.candidate`;!function(t,e){let r=z(t,"wx",384);try{H(r,`${JSON.stringify(e,null,2)}\n`,"utf8"),L(r)}finally{X(r)}}(r,e);try{C(r,t)}catch(t){if("EEXIST"===ze(t))return!1;throw t}finally{Ve(r)}return function(t){let e;try{e=z(t,"r")}catch(t){if("win32"===process.platform&&["EISDIR","EPERM"].includes(ze(t)??""))return;throw t}try{L(e)}catch(t){if("win32"!==process.platform||!["EPERM","EACCES","EINVAL"].includes(ze(t)??""))throw t}finally{X(e)}}(Xt(t)),!0}function He(t){let e;try{e=q(t,"utf8")}catch(t){if("ENOENT"===ze(t))return;throw t}try{return{raw:e,claim:Ke(JSON.parse(e))}}catch{return{raw:e,claim:void 0}}}async function Be(t,e,r,n,i,o){let a=await pe("reflection-finalize",{runId:i.runId});return Re(Zt(t,"terminal-claim-recovery.lock"),a,async()=>{let t=He(e);if(void 0!==t){if(t.raw!==r.raw)return t.claim;if("invalid"===n){if(void 0!==t.claim)return t.claim}else{if(void 0===t.claim)return;if("publish"!==t.claim.kind||!Ye(t.claim,o))return t.claim}Ve(e)}},{waitTimeoutMs:Number.POSITIVE_INFINITY})}function Ve(t){try{G(t)}catch(t){if("ENOENT"!==ze(t))throw t}}function Ye(t,e){return"dead"===(e.getPidLiveness??ht)(t.claimantPid)}function Ke(t){if(!function(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}(t)||1!==t.version||"publish"!==t.kind&&"abandon"!==t.kind||"string"!=typeof t.runId||!Number.isInteger(t.attempt)||!Number.isInteger(t.claimantPid)||Number(t.claimantPid)<=0)throw TypeError("Invalid run terminal claim");return{version:1,kind:t.kind,runId:t.runId,attempt:Number(t.attempt),claimantPid:Number(t.claimantPid)}}function ze(t){return t instanceof Error&&"code"in t?String(t.code):void 0}import{join as Xe}from"node:path";async function Ze(t,e,r){let n={runId:e.runId,attempt:e.attempt??1},i=await async function(t,e,r,n={},i=process.pid){let o=Fe(t),a={version:1,kind:r,runId:e.runId,attempt:e.attempt,claimantPid:i},s=0;for(;;){if(Ge(o,a))return a;let i=He(o);if(void 0===i)continue;let l=i.claim;if(void 0===l){if(s>0)throw TypeError("Invalid run terminal claim");s+=1,await(n.beforeRecovery?.("invalid"));let r=await Be(t,o,i,"invalid",e,n);if(void 0!==r)return r;continue}if(Je(l,e,r))return l;if("publish"!==l.kind||!Ye(l,n))return l;await(n.beforeRecovery?.("dead-publish"));let c=await Be(t,o,i,"dead-publish",e,n);if(void 0!==c)return c}}(t,n,"publish");Je(i,n,"publish")&&(await nt(Tt(t,"publishing.json"),{version:1,...n,finishedAt:r.finishedAt}),await async function(t,e,r,n=Re,i=pe){let o=await i("reflection-finalize",{runId:e});return n(Xe(t,"terminalization.lock"),o,r,{waitTimeoutMs:Number.POSITIVE_INFINITY})}(t,e.runId,async()=>{if(Z(Tt(t,"final.json"))||Z(Tt(t,"abandoned.json")))return;if(!Je(function(t){return Ke(JSON.parse(q(Fe(t),"utf8")))}(t),n,"publish"))return;let i=void 0!==Kt({code:r.childExit.code,stdout:q(e.stdoutPath,"utf8"),stderr:q(e.stderrPath,"utf8"),timedOut:r.timedOut});i&&void 0!==e.nextAttempt&&await it(Tt(t,"ledger.json"),{attempt:e.nextAttempt.attempt,model:e.nextAttempt.model,...void 0===e.nextAttempt.thinking?{thinking:void 0}:{thinking:e.nextAttempt.thinking},launching:!0,pid:void 0,processStart:void 0,childPid:void 0,childProcessStart:void 0}),await nt(Tt(t,"outcome.json"),r),i&&await ot(Fe(t))}))}function We(t){try{B(3,`${JSON.stringify(t)}\n`)}catch(t){if(!(t instanceof Error&&"code"in t&&["EPIPE","EBADF"].includes(String(t.code))))throw t}}var Qe=process.argv.slice(2);try{if("--child-bootstrap"===Qe[0]){if(void 0===Qe[1])throw TypeError("run directory is required");await async function(e){if(!await async function(){for await(let t of process.stdin)if(Buffer.byteLength(t)>0)return!0;return!1}())return;let r=await rt(W(e,"launch.json")),n=gt(),i=t(r.command,[...r.args],{cwd:r.cwd,env:r.env,detached:!1,stdio:["ignore","inherit","inherit"],windowsHide:!0});We({code:i.pid??null,signal:"MODEL_PID"});let o=()=>{"win32"!==n&&"win32"!==process.platform||i.kill()};process.on("SIGTERM",o),process.on("SIGINT",o);let a=vt(r.hardDeadlineAt,()=>{"win32"===n?Ot(n,i):It(process.pid,"SIGTERM")}),s=vt(r.hardDeadlineAt+r.terminationGraceMs,()=>{kt(n,process.pid)});We(await new Promise(t=>{let e=!1;i.once("error",()=>{e||(e=!0,t({code:null,signal:null}))}),i.once("close",(r,n)=>{e||(e=!0,t({code:r,signal:n}))})}).finally(()=>{a(),s()}))}(Qe[1])}else{if(void 0===Qe[0])throw TypeError("run directory is required");await async function(e){let r=W(e,"launch.json"),n=W(e,"ledger.json"),i=await rt(r),o=gt();await it(n,{launching:!1,pid:process.pid,processStart:await Pt(process.pid)});let a,s=z(i.stdoutPath,"w"),l=z(i.stderrPath,"w"),c=t(process.execPath,[Q(import.meta.url),"--child-bootstrap",e],{env:process.env,detached:!0,stdio:["pipe",s,l,"pipe"],windowsHide:!0}),u=c.pid,d="",f=c.stdio[3];null!=f&&"setEncoding"in f&&(f.setEncoding("utf8"),f.on("data",t=>{d+=t;for(let t of d.split("\n"))try{let e=JSON.parse(t);"MODEL_PID"===e.signal&&"number"==typeof e.code&&(a=e.code)}catch(t){if(!(t instanceof SyntaxError))throw t}}));let p=(t=!1)=>{try{kt(o,u,t)}catch(t){process.stderr.write(`${t instanceof Error?t.message:String(t)}\n`)}};if(process.once("exit",()=>p(!0)),process.once("SIGTERM",()=>{p(),u=void 0,process.exit(143)}),process.once("SIGINT",()=>{p(),u=void 0,process.exit(130)}),void 0===c.pid)throw Error("child bootstrap did not receive a pid");await it(n,{childPid:c.pid,childProcessStart:await Pt(c.pid)}),c.stdin?.end("1\n");let m,w=!1,h=Promise.resolve();"win32"===o&&(h=new Promise(t=>{m=t}));let y=vt(i.hardDeadlineAt,()=>{w=!0,"win32"===o?Nt(c.pid):Ot(o,c)}),g=vt(i.hardDeadlineAt+i.terminationGraceMs,()=>{kt(o,a??u),m?.()}),v=await new Promise((t,e)=>{let r=!1;c.once("error",t=>{r||(r=!0,e(t))}),c.once("close",(e,n)=>{r||(r=!0,t({code:e,signal:n}))})}),b=function(t){let e=t.trim().split("\n").at(-1);if(void 0!==e&&0!==e.length)try{let t=JSON.parse(e),r="number"==typeof t.code||null===t.code?t.code:void 0,n="string"==typeof t.signal||null===t.signal?t.signal:void 0;return void 0===r||void 0===n||"MODEL_PID"===n?void 0:{code:r,signal:n}}catch{return}}(d);"win32"===o&&w&&void 0===b&&await h,y(),g(),u=void 0,X(s),X(l);let E=function(){let t=yt()?process.env.OMO_MEMORY_SUPERVISOR_CLOCK_PATH:void 0;return void 0===t?Date.now():Et(t)}(),S=(new Date).toISOString(),x={version:1,runId:i.runId,attempt:i.attempt,finishedAt:S,childExit:b??v,timedOut:w||Number.isFinite(E)&&E>=i.hardDeadlineAt};await Ze(e,i,x),await ot(r),process.exit(0)}(Qe[0])}}catch(t){process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}\n`),process.exitCode=1}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
// omo:
|
|
1
|
+
// omo:4B3EMPhyVjc-cEIEPDWaoUfzgFrRo73PxxalWbndSJc:MmVgcjtDBoOOErwpVIqw-iA0YUS4NhHAdvcTrJ6Z2ys
|
|
2
2
|
import{createHash as e,randomUUID as t}from"node:crypto";import{chmodSync as n,existsSync as r,mkdirSync as i,readFileSync as o,renameSync as s,rmSync as a,writeFileSync as l}from"node:fs";import{join as u}from"node:path";import{DatabaseSync as c}from"node:sqlite";function d(t){return e("sha256").update(o(t)).digest("hex")}import{tmpdir as p}from"node:os";import{join as h}from"node:path";var f=Number.MAX_SAFE_INTEGER;function m(e){if(void 0===e)return!1;let{compat:t}=e;return"object"==typeof t&&null!==t&&"supportsImageDetailOriginal"in t&&!1===t.supportsImageDetailOriginal||("anthropic-messages"===e.api||"anthropic"===e.provider||/claude/i.test(e.id))}class g extends Error{constructor(){super("Computer use is off for this session; the user can turn it on with /computer on."),this.name="ComputerDisabledError"}}class y{#e;#t;#n=new Set;#r;#i;#o=!1;constructor(e){this.#e=e.service,this.#t=e.settings}get service(){return this.#e}settings(){return this.#t()}get enabled(){return this.#r??this.#t().enabled}get active(){return this.#o}get running(){return void 0!==this.#i}setEnabled(e){this.#r=e}onActivationChange(e){return this.#n.add(e),()=>this.#n.delete(e)}async activate(e){if(!this.enabled)throw new g;let t=this.#t();await this.#s(t,e);let n=await this.#e.ensureStopPath(t.stopHotkey);return this.#a(!0),n}async deactivate(){await this.close(),this.#a(!1)}async close(){this.#i=void 0,await this.#e.close()}async stopPathStatus(){return this.running?this.#e.stopPathStatus():void 0}async stop(){return this.running?this.#e.stop():void 0}async resume(){return this.running?this.#e.resume():void 0}async capabilities(){return this.running?this.#e.capabilities():void 0}async#s(e,t){let n=function(e,t){let{auditLog:n,screenshotGc:r}=e;return{display:e.display,macosCanary:e.macosCanary,allowHostRelayOnlyStop:e.allowHostRelayOnlyStop,auditPath:n.enabled?h(t.sessionManager.getSessionDir(),".computer-audit.jsonl"):null,artifactDir:p(),screenshotGc:{staleMs:r.enabled?r.staleMs:f,scanIntervalMs:r.scanIntervalMs},captureCaps:{maxWidth:e.maxWidth,maxHeight:e.maxHeight,coordinateSafe:m(t.model),maxBytes:e.screenshotMaxBytes}}}(e,t),r=JSON.stringify(n);this.#i?.key!==r&&(this.#i={key:r,done:this.#e.open(n)});let i=this.#i;try{await i.done}catch(e){throw this.#i===i&&(this.#i=void 0),e}}#a(e){if(this.#o!==e){this.#o=e;for(let t of this.#n)t(e)}}}import{Errors as v}from"typebox/value";class b extends Error{code="COMPUTER_INVALID_ARGUMENTS";reason;constructor(e){super(`COMPUTER_INVALID_ARGUMENTS: ${e}`),this.name="ComputerArgumentsError",this.reason=e}}function w(e){return new Map(e.map(e=>[String(Reflect.get(e.properties.action??{},"const")),e]))}function _(e,t,n){let r=[...e.keys()].join(", ");if("object"!=typeof t||null===t)return new b(`${n} must be an object`);let i=Reflect.get(t,"action");if("string"!=typeof i)return new b(`${n}: "action" must be one of ${r}`);let o=e.get(i);if(void 0===o)return new b(`${n}: unknown action "${i}"; expected one of ${r}`);let s=Object.keys(t).filter(e=>!(e in o.properties));if(s.length>0)return new b(`${n}: action "${i}" does not take ${s.join(", ")}`);let[a]=v(o,t),l=void 0===a||""===a.instancePath?"":` at ${a.instancePath}`;return new b(`${n}: action "${i}"${l}: ${a?.message??"invalid arguments"}`)}import{Type as k}from"typebox";import{Check as x}from"typebox/value";var O=k.Union([k.Literal("left"),k.Literal("right"),k.Literal("middle")]),$={timeout:k.Optional(k.Number({exclusiveMinimum:0,description:"Maximum time in seconds for this action."})),include_screenshot:k.Optional(k.Boolean({description:"Capture a screenshot after the action."}))},S={x:k.Number(),y:k.Number()},E={additionalProperties:!1},z=[k.Object({action:k.Literal("screenshot"),...$},E),k.Object({action:k.Literal("click"),...S,button:k.Optional(O),...$},E),k.Object({action:k.Literal("double_click"),...S,button:k.Optional(O),...$},E),k.Object({action:k.Literal("move"),...S,button:k.Optional(O),...$},E),k.Object({action:k.Literal("drag"),...S,to_x:k.Number(),to_y:k.Number(),button:k.Optional(O),...$},E),k.Object({action:k.Literal("scroll"),...S,scroll_x:k.Number(),scroll_y:k.Number(),...$},E),k.Object({action:k.Literal("type"),text:k.String(),...$},E),k.Object({action:k.Literal("keypress"),keys:k.Array(k.String(),{minItems:1}),...$},E),k.Object({action:k.Literal("wait"),ms:k.Integer({minimum:0}),...$},E)],P=k.Union([...z]),I=k.Object({action:k.Literal("batch"),actions:k.Array(P,{minItems:1}),...$},E),T=k.Union([P,I]),A=["screenshot","click","double_click","move","drag","scroll","type","keypress","wait"],N={x:k.Optional(k.Number({description:"click, double_click, move, drag (start), scroll (required): x pixel"})),y:k.Optional(k.Number({description:"click, double_click, move, drag (start), scroll (required): y pixel"})),button:k.Optional(k.Enum(["left","right","middle"],{type:"string",description:"click, double_click, move, drag: mouse button (default left)"})),to_x:k.Optional(k.Number({description:"drag (required): end x pixel"})),to_y:k.Optional(k.Number({description:"drag (required): end y pixel"})),scroll_x:k.Optional(k.Number({description:"scroll (required): horizontal scroll distance in pixels on every OS (one wheel notch is about 40 px); positive scrolls right"})),scroll_y:k.Optional(k.Number({description:"scroll (required): vertical scroll distance in pixels on every OS (one wheel notch is about 40 px); positive moves the view toward the end of the content (down)"})),text:k.Optional(k.String({description:"type (required): text to type"})),keys:k.Optional(k.Array(k.String(),{minItems:1,description:"keypress (required): keys pressed together"})),ms:k.Optional(k.Integer({minimum:0,description:"wait (required): milliseconds"})),...$},j=k.Object({action:k.Enum([...A,"batch"],{type:"string",description:"The action to perform, or batch to run `actions` in order"}),actions:k.Optional(k.Array(k.Object({action:k.Enum([...A],{type:"string",description:"The action to perform"}),...N},E),{minItems:1,description:"batch (required): actions to execute in order"})),...N},E),R=w(z),C=w([...z,I]);var M=new Set(["screenshot","wait"]);class D extends Error{reason;constructor(e,t){super(t),this.name="ComputerRunError",this.reason=e}}class Z{#l=[];text(e){this.#l.push({type:"text",text:e})}image(e,t){this.#l.push({type:"image",data:e,mimeType:t})}finish(){return[...this.#l]}}function U(e,t){return(n,r)=>e.resume(Promise.resolve().then(()=>(function(e,t,n){let r=Object.hasOwn(t,n)?t[n]:"exec";if(e.readOnly&&"exec"===r)throw new D("readOnly",`read-only run: '${n}' requires read_only: false`);e.signal.throwIfAborted()}(e.context,t,n),r(e))))}var L={capabilities:"read",displays:"read",windows:"read",window:"read",focusedWindow:"read",screenshot:"read",click:"exec",doubleClick:"exec",move:"exec",drag:"exec",scroll:"exec",type:"exec",press:"exec",elementAt:"read",focusedElement:"read",ref:"read","clipboard.read":"read","clipboard.write":"exec"},F={screenshot:"read",click:"exec",doubleClick:"exec",move:"exec",drag:"exec",scroll:"exec",type:"exec",press:"exec",raise:"exec",ax:"read",find:"read",ref:"read"},J={value:"read",setValue:"exec",bounds:"read",attributes:"read",actions:"read",perform:"exec",press:"exec",click:"exec",focus:"exec",parent:"read",children:"read"},V={window:{label:"window",methods:F},ref:{label:"element",methods:J}};class q extends Error{reason;constructor(e,t){super(t),this.name="ComputerCallError",this.reason=e}}function W(e,t){return Object.hasOwn(e,t)?e[t]:void 0}function B(e){return Object.keys(e).join(", ")}function H(e){return"read"===function(e){let[t,n,...r]=e;if(void 0===t)throw new q("empty","Action 'call' requires a non-empty 'chain'.");if(r.length>0)throw new q("tooLong","Call chains support one handle hop at most; use computer.run(fn) for longer sequences.");let i=W(L,t.method);if(void 0===i)throw new q("unknownMethod",`Unknown desktop method "${t.method}". Desktop helpers support: ${B(L)}.`);if(void 0===n)return i;let o=Object.hasOwn(V,t.method)?V[t.method]:void 0;if(void 0===o)throw new q("notChainable",`Only desktop.window(id)/desktop.ref(ref) results accept a chained call; got desktop.${t.method}().`);let s=W(o.methods,n.method);if(void 0===s)throw new q("unknownMethod",`Unknown ${o.label} method "${n.method}". Supported ${o.label} methods: ${B(o.methods)}.`);return s}(e)}var K="1",G="senpi-desktop/1",X=["audit","stopPath.changed","engine.log"],Y=["PermissionDenied","CaptureFailed","InputFailed","BackgroundUnavailable","WindowNotFound","InvalidTarget","InvalidKey","InvalidCoordinateFrame","StaleRef","AxUnsupported","AxFailed","Timeout","Closed","Internal","StopPathUnavailable","Suspended","ScreenLocked","Cancelled","CursorRestoreFailed","FocusRestoreFailed","TransactionFailed"],Q=new Set(["engine.hello","session.open","session.close","capabilities","displays","windows","capture","click","moveMouse","drag","scroll","typeText","keyChord","raiseWindow","clipboard.read","clipboard.write","ax.snapshot","ax.query","ax.elementAt","ax.focused","ax.node","ax.attributes","ax.children","ax.parent","ax.perform","ax.setValue","ax.focus","ax.click","stopPath.start","stopPath.status","stopPath.heartbeat","stopPath.stop","stopPath.resume","$/cancel","$/test.advanceClock"]),ee=new Set(Y),te=new Set(["global","host-relay","none"]),ne=["unknown","hostOnly","testOnly"],re={suspended:"boolean",globalLive:"boolean",hostRelayLive:"boolean",heartbeatFresh:"boolean",stopPath:"string",reason:"string?"},ie={backend:"string",displayServer:"string?",capture:"boolean",input:"boolean",ax:"boolean",backgroundWindowInput:"boolean",capturePermission:"string",inputPermission:"string",axPermission:"string",displayCount:"number",focusGuard:"boolean",stopPath:"string",stopReason:"string?",integrityLevel:"string?",screenLocked:"boolean"},oe={action:"string",target:"string",delivery:"string",frameId:"string?",code:"string?",durationMs:"number",focusRestored:"boolean?",textLength:"number?",textDelivered:"number?",textSha256:"string?"};function se(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ae(e,t){return!!se(e)&&Object.entries(t).every(([t,n])=>{let r=e[t];return n.endsWith("?")?null==r||typeof r===n.slice(0,-1):typeof r===n})}function le(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function ue(e,t){return"string"==typeof e&&t.has(e)}function ce(e){return ae(e,re)&&ue(e.stopPath,te)}function de(e){return ae(e,ie)&&le(e.deliveryModes)}function pe(e){if(!se(e))return null;let t=Y.find(t=>t===e.code);if(void 0!==t){let n=function(e){if(!se(e)||"screen_recording"!==e.permission&&"accessibility"!==e.permission||"string"!=typeof e.settingsUrl||"string"!=typeof e.app||"boolean"!=typeof e.relaunchRequired)return;return{permission:e.permission,settingsUrl:e.settingsUrl,app:e.app,relaunchRequired:e.relaunchRequired}}(e.permission);return{code:t,hint:"string"==typeof e.hint?e.hint:null,...void 0===n?{}:{permission:n}}}let n=ne.find(t=>t===e.reason);return void 0===n?null:{reason:n}}import{spawn as he}from"node:child_process";import{createInterface as fe}from"node:readline";class me extends Error{code="abi-mismatch";enginePath;expected;actual;constructor(e,t){let n={abi:G,protocolVersion:K};super(`desktop engine ABI mismatch at ${e}: expected abi ${n.abi} protocol ${n.protocolVersion}, engine reported abi ${t.abi} protocol ${t.protocolVersion}`),this.name="DesktopEngineAbiMismatchError",this.enginePath=e,this.expected=n,this.actual=t}}import{spawnSync as ge}from"node:child_process";import{createHash as ye}from"node:crypto";import{accessSync as ve,constants as be,existsSync as we,readFileSync as _e,realpathSync as ke}from"node:fs";import{dirname as xe,join as Oe,sep as $e}from"node:path";import{fileURLToPath as Se}from"node:url";var Ee="senpi-desktop-engine-checksums.txt",ze=["darwin-arm64","darwin-x64","linux-x64","win32-x64"];function Pe(e){switch(e){case"darwin-arm64":case"darwin-x64":case"linux-x64":return`senpi-desktop-engine-${e}`;case"win32-x64":return`senpi-desktop-engine-${e}.exe`;default:return null}}function Ie(e){let t=new Map;for(let n of e.trimEnd().split(/\r?\n/)){let e=/^([a-fA-F0-9]{64}) ([A-Za-z0-9.-]+)$/.exec(n),r=e?.[2],i=e?.[1];if(void 0===r||void 0===i||!ze.some(e=>Pe(e)===r))return{checksums:null,error:"Invalid desktop engine checksum entry or asset name"};if(t.has(r))return{checksums:null,error:`Duplicate SHA-256 checksum for ${r}`};t.set(r,i)}return{checksums:t,error:null}}var Te,Ae="senpi-desktop-engine",Ne="com.apple.quarantine",je=Oe(xe(Se(import.meta.url)),"..");function Re(e=process.platform,t=process.arch,n=("linux"===e&&e===process.platform?function(){return Te??=function(e,t){let n="object"==typeof e&&null!==e?Reflect.get(e,"header"):void 0,r="object"==typeof n&&null!==n?Reflect.get(n,"glibcVersionRuntime"):void 0;return"string"==typeof r&&r.length>0?"glibc":/\/ld-musl-[^/\s]+\.so\.1$/m.test(t()??"")?"musl":"glibc"}(process.report?.getReport(),Ce),Te}():void 0)){return"linux"===e&&"musl"===n?`${e}-${t}-musl`:`${e}-${t}`}function Ce(){try{return _e("/proc/self/maps","utf8")}catch(e){if(e instanceof Error&&"code"in e)return;throw e}}function Me(e=process.platform){return"win32"===e?`${Ae}.exe`:Ae}function De(e={}){let t=Re(e.platform,e.arch,e.libc),n=Me(e.platform),r=e.packageDir??je,i=e.execDir??xe(process.execPath),o=e.repoRoot??Oe(r,"..",".."),s=Oe("native","prebuilds",t,n),a=e.runtimeDir??process.env.OMO_PACKAGE_DIR;return[...a?[Oe(a,s)]:[],Oe(i,s),Oe(r,s),Oe(o,"target","release",n)]}function Ze(e={}){let t=e.platform??process.platform,n=Re(t,e.arch,e.libc),r=De(e),i=e.execDir??xe(process.execPath),o=e.runtimeDir??process.env.OMO_PACKAGE_DIR?1:0,s=e.isQuarantined??(e=>Le(e,t)),a=[],l=[];for(let[e,t]of r.entries())if(we(t)){if(s(t)){if(e!==o||!Ue(t,i,n)){l.push(t),a.push(`${t}: blocked because ${Ne} is present (macOS Gatekeeper)`);continue}a.push(`${t}: quarantined; accepted: inside the launcher's install and matching native/prebuilds/senpi-desktop-engine-checksums.txt`)}if(Fe(t))return{path:t,diagnostic:null};a.push(`${t}: not executable (chmod +x)`)}else a.push(`${t}: missing`);let u=l.length>0?"quarantined":"native-unavailable",c=a.every(e=>e.endsWith(": missing"))&&null===Pe(n)?"no-release-asset":void 0;return{path:null,diagnostic:{code:u,host:n,attemptedPaths:r,message:"quarantined"===u?`The ${Ae} binary for ${n} is quarantined by macOS Gatekeeper: ${l.join(", ")}.`:"no-release-asset"===c?`No senpi-desktop-engine is built for ${n}; computer use is unavailable on this host.`:`No ${Ae} binary is available for ${n}.`,cause:a.join("; "),...void 0===c?{}:{reason:c}}}}function Ue(e,t,n){try{let r=`${Oe(ke(t),"native","prebuilds")}${$e}`;if(!ke(e).startsWith(r))return!1;let i=Pe(n);if(null===i)return!1;let o=Ie(_e(Oe(t,"native","prebuilds",Ee),"utf8"));if(null!==o.error)return!1;let s=o.checksums.get(i);return void 0!==s&&ye("sha256").update(_e(e)).digest("hex")===s.toLowerCase()}catch(e){if(e instanceof Error&&"code"in e)return!1;throw e}}function Le(e,t=process.platform){if("darwin"!==t)return!1;let n=ge("/usr/bin/xattr",["-p",Ne,e],{stdio:["ignore","ignore","ignore"],timeout:2e3});return void 0===n.error&&0===n.status}function Fe(e){try{return ve(e,be.X_OK),!0}catch(e){if(e instanceof Error&&"code"in e)return!1;throw e}}import{createHash as Je,randomUUID as Ve}from"node:crypto";import{accessSync as qe,chmodSync as We,constants as Be,existsSync as He,mkdirSync as Ke,mkdtempSync as Ge,readFileSync as Xe,readdirSync as Ye,renameSync as Qe,rmSync as et,writeFileSync as tt}from"node:fs";import{homedir as nt}from"node:os";import{join as rt}from"node:path";import{spawnSync as it}from"node:child_process";function ot(e){let t=it("/usr/bin/codesign",["--verify","--strict",'-R=identifier "ai.sisyphuslabs.senpi-desktop-engine" and anchor apple generic and certificate leaf[subject.OU] = "523JNR86LZ" and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists',e],{stdio:"ignore",timeout:5e3});return void 0===t.error&&0===t.status}var st="-musl";function at(e,t){let{host:n,version:r}=e,i=Pe(n),o=[];if(null===i)return{path:null,attemptedPaths:o};let s=n.slice(0,n.indexOf("-")),a=e.cacheDir??rt(nt(),".omo","cache","senpi-desktop-engine"),l=rt(a,r,n);if(He(l))for(let e of Ye(l)){let n=/^([0-9a-f]{64})-[0-9a-f-]{36}$/.exec(e);if(null===n)continue;let r=rt(l,e,i);if(o=[...o,r],t?.(r),He(r)&&Je("sha256").update(Xe(r)).digest("hex")===n[1]&&!Le(r,s))try{return qe(r,Be.X_OK),{path:r,sha256:n[1]}}catch(e){if(!(e instanceof Error&&"code"in e))throw e}}return{path:null,attemptedPaths:o}}async function lt(e){let{host:t,version:n}=e,r=[],i=e=>({path:null,diagnostic:{code:"native-unavailable",host:t,attemptedPaths:r,message:`No senpi-desktop-engine binary is available for ${t}.`,cause:e}});try{let o=t.indexOf("-");if(o<1||o===t.length-1)return i(`Invalid host: ${t}`);let s=t.slice(0,o),a=t.slice(o+1),l="linux"===s&&a.endsWith(st)?"musl":"glibc",u="musl"===l?a.slice(0,-5):a,c=Ze({...e.locatorOptions,platform:s,arch:u,libc:l});if(r=c.diagnostic?.attemptedPaths??[],null!==c.path){let r=e.locatorOptions?.runtimeDir??process.env.OMO_PACKAGE_DIR,o=r&&rt(r,"native","prebuilds",t,Me(s));if("darwin"===s&&c.path===o&&r&&(e.isReleaseEngine??ot)(c.path)){let e=JSON.parse(Xe(rt(r,"package.json"),"utf8"));return"object"==typeof e&&null!==e&&"omo"===Reflect.get(e,"name")&&Reflect.get(e,"version")===n?{path:c.path,sha256:Je("sha256").update(Xe(c.path)).digest("hex")}:i("Extracted desktop engine does not belong to the requested omo release")}return{path:c.path}}if("quarantined"===c.diagnostic.code)return i(c.diagnostic.cause);let d=Pe(t);if(null===d)return{path:null,diagnostic:{...c.diagnostic,reason:"no-release-asset",message:`No senpi-desktop-engine is built for ${t}; computer use is unavailable on this host.`}};if(!/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$/.test(n))return i(`Invalid omo release version: ${n}`);let p=e.cacheDir??rt(nt(),".omo","cache","senpi-desktop-engine"),h=rt(p,n,t),f=at(e,e=>{r=[...r,e]});if(null!==f.path)return f;if(!1===e.allowDownload)return i("No installed release engine");let m=e.fetch??globalThis.fetch,g=`https://github.com/code-yeongyu/oh-my-openagent/releases/download/v${n}`;r=[...r,rt(h,d)];let[y,v]=await Promise.all([m(`${g}/${d}`,{signal:AbortSignal.timeout(3e4)}),m(`${g}/${Ee}`,{signal:AbortSignal.timeout(3e4)})]);if(!y.ok)return i(`${d}: HTTP ${y.status}`);if(!v.ok)return i(`${Ee}: HTTP ${v.status}`);let b=Ie(await v.text());if(null!==b.error)return i(b.error);let w=b.checksums.get(d);if(void 0===w)return i(`No SHA-256 checksum for ${d}`);let _=Buffer.from(await y.arrayBuffer()),k=Je("sha256").update(_).digest("hex");if(k.toLowerCase()!==w.toLowerCase())return i(`SHA-256 mismatch for ${d}`);Ke(h,{recursive:!0});let x=Ge(rt(h,".download-")),O=rt(h,`${k}-${Ve()}`);try{let e=rt(x,d);tt(e,_),We(e,493),Qe(x,O)}finally{et(x,{recursive:!0,force:!0})}return{path:rt(O,d),sha256:k}}catch(e){return i(e instanceof Error?e.message:String(e))}}async function ut(e,p,h=lt){let f=await h(e);if(null===f.path)return f;let m=e.isReleaseEngine??ot;return e.host.startsWith("darwin-")&&void 0!==f.sha256&&m(f.path)?(await Promise.resolve().then(()=>{}),function(e,p,h){i(e.directory,{recursive:!0});let f=u(e.directory,"senpi-desktop-engine"),m=new c(u(e.directory,"launch.lock"));try{if(m.exec("PRAGMA busy_timeout = 30000"),m.exec("BEGIN EXCLUSIVE"),!r(f)||d(f)!==e.sha256){let r=u(e.directory,`.engine-${t()}`);try{if(l(r,o(e.path),{flag:"wx",mode:493}),n(r,493),d(r)!==e.sha256)throw Error("Desktop engine source SHA-256 changed");if(!h(r))throw Error("Desktop engine release signature verification failed");s(r,f)}finally{a(r,{force:!0})}}if(d(f)!==e.sha256)throw Error("Stable desktop engine SHA-256 mismatch");return l(u(e.directory,"release.json"),JSON.stringify({version:e.version,sha256:e.sha256})),{path:f,value:p(f)}}finally{m.close()}}({path:f.path,sha256:f.sha256,version:e.version,directory:rt(e.installDir??rt(nt(),".omo","engines","senpi-desktop-engine"),e.host)},t=>Le(t)?{path:null,diagnostic:{code:"quarantined",host:e.host,attemptedPaths:[t],message:"The stable desktop engine is quarantined by macOS Gatekeeper.",cause:`${t}: blocked because com.apple.quarantine is present`}}:{path:t,value:p(t)},m).value):{path:f.path,value:p(f.path)}}class ct extends Error{diagnostic;constructor(e){super(`${e.message} ${e.cause}`),this.name="DesktopEngineUnavailableError",this.diagnostic=e}}function dt(e){return()=>pt(e??function(){let e=Ze();if(null===e.path)throw new ct(e.diagnostic);return e.path}())}function pt(e){return he(e,["--stdio"],{stdio:"pipe",windowsHide:!0})}class ht{path;exited;#u;#c="";#d="";#p=!0;constructor(e,t){this.#u=e,this.path=e.spawnfile,e.stderr.setEncoding("utf8"),e.stderr.on("data",e=>{this.#c=(this.#c+e).slice(-4096)}),e.stdin.on("error",e=>this.#h(`stdin: ${e.message}`)),e.on("error",e=>this.#h(`spawn: ${e.message}`)),fe({input:e.stdout}).on("line",t.onLine),this.exited=new Promise(n=>{e.on("close",(e,r)=>{this.#p=!1,t.onExit(this.#f(e,r)),n()})})}get alive(){return this.#p}write(e){this.#p&&!this.#u.stdin.writableEnded&&this.#u.stdin.write(`${JSON.stringify({jsonrpc:"2.0",...e})}\n`)}end(){this.#u.stdin.end()}kill(){this.#p&&(this.#p=!1,this.#u.kill())}#h(e){this.#d=""===this.#d?e:`${this.#d}; ${e}`}#f(e,t){return`desktop engine exited (code ${e??"null"}, signal ${t??"null"})${""===this.#d?"":`; ${this.#d}`}; stderr: ${this.#c.trim()||"<empty>"}`}}class ft extends Error{code;engineRestarted;constructor(e,t,n=!1){super(t),this.name="DesktopServiceError",this.code=e,this.engineRestarted=n}}class mt extends Error{method;rpcCode;data;constructor(e,t){super(t.message),this.name="DesktopEngineRpcError",this.method=e,this.rpcCode=t.code,this.data=pe(t.data)}}class gt{#m;#g;#y=new Map;#v=1;#f;constructor(e,t){this.#g=t,this.#m=new ht(e,{onLine:e=>this.#b(e),onExit:e=>this.#w(e)})}get enginePath(){return this.#m.path}get alive(){return void 0===this.#f&&this.#m.alive}get exited(){return this.#m.exited}request(e,t,n={}){if(!this.alive)return Promise.reject(new ft("Closed",this.#f??"desktop engine was killed"));if(n.signal?.aborted)return Promise.reject(new ft("Cancelled",`${e} was cancelled before it was sent`));let r=this.#v++,{promise:i,resolve:o,reject:s}=Promise.withResolvers(),a={method:e,resolve:o,reject:s,release:()=>{},cancelled:void 0};this.#y.set(r,a);let{signal:l,timeoutMs:u}=n,c=()=>this.#_(r,new ft("Cancelled",`${e} was cancelled`)),d=void 0===u?void 0:setTimeout(()=>this.#_(r,new ft("Timeout",`${e} timed out after ${u} ms`)),u);return l?.addEventListener("abort",c,{once:!0}),a.release=()=>{clearTimeout(d),l?.removeEventListener("abort",c)},this.#m.write({id:r,method:e,params:t}),i}end(){this.#m.end()}kill(){this.#m.kill()}#_(e,t){let n=this.#y.get(e);if(void 0===n||void 0!==n.cancelled)return;n.release(),n.cancelled=t;let r=setTimeout(()=>{this.#k(e),n.reject(new ft(t.code,`${t.message}; desktop engine restarted; captures and ax refs were reset`,!0)),this.#m.kill()},750);n.release=()=>clearTimeout(r),this.#m.write({method:"$/cancel",params:{id:e}})}#k(e){let t=this.#y.get(e);return this.#y.delete(e),t?.release(),t}#b(e){let t=function(e){try{return JSON.parse(e)}catch(e){if(e instanceof SyntaxError)return;throw e}}(e);if(!se(t))return this.#m.kill(),void(this.#f=`desktop engine wrote a non-protocol line ${JSON.stringify(e.slice(0,200))}`);if("string"==typeof t.method&&void 0===t.id)return void this.#g.onNotification(t.method,t.params);let n="number"==typeof t.id?this.#k(t.id):void 0;if(void 0===n)return;if(void 0!==n.cancelled)return void n.reject(n.cancelled);if("result"in t)return void n.resolve(t.result);let{error:r}=t;se(r)&&"number"==typeof r.code&&"string"==typeof r.message?n.reject(new mt(n.method,{code:r.code,message:r.message,data:r.data})):n.reject(new ft("Internal",`desktop engine sent a malformed reply to ${n.method}`))}#w(e){this.#f??=e;let t=new ft("Closed",this.#f);for(let e of[...this.#y.keys()])this.#k(e)?.reject(t);this.#g.onExit()}}var yt={id:"string",name:"string",x:"number",y:"number",width:"number",height:"number",scale:"number",pixelX:"number",pixelY:"number",pixelWidth:"number",pixelHeight:"number",isPrimary:"boolean"},vt={id:"string",title:"string",app:"string",pid:"number?",x:"number",y:"number",width:"number",height:"number",focused:"boolean",elevated:"boolean?"},bt={ref:"string",role:"string",nativeRole:"string",title:"string?",value:"string?",description:"string?",enabled:"boolean",focused:"boolean",x:"number?",y:"number?",width:"number?",height:"number?",childCount:"number"},wt={mode:"string",data:"string?",mimeType:"string?",artifactPath:"string?",width:"number",height:"number",sourceWidth:"number",sourceHeight:"number",scale:"number",target:"string",frameId:"string",note:"string?"},_t=e=>ae(e,yt),kt=e=>ae(e,vt),xt=e=>ae(e,bt)&&(void 0===e.actions||null===e.actions||le(e.actions)),Ot=e=>ae(e,wt),$t=e=>se(e)&&"string"==typeof e.text,St=e=>Array.isArray(e)&&e.every(e=>le(e)&&2===e.length);function Et(e){return t=>Array.isArray(t)&&t.every(e)}function zt(e){return t=>null===t||e(t)}function Pt(e,t,n){if(!n(t))throw new ft("Internal",`desktop engine sent a malformed ${e} result`);return t}function It(e={}){let{button:t,count:n,modifiers:r,delivery:i}=e;return{button:t,count:n,modifiers:r,deliveryMode:i}}function Tt(e){return"string"!=typeof e?e:e.split("+").map(e=>e.trim()).filter(e=>e.length>0)}class At{#x;method;constructor(e,t,n){this.#x=t,this.method=U(e,n)}send(e,t,n){return this.method(e,async({call:e})=>{await e(t,n)})}screenshot(e){return this.method("screenshot",t=>async function(e,t,n={}){let{snapshot:r,output:i,screenshots:o}=e.context,s={maxWidth:r.captureMaxWidth,maxHeight:r.captureMaxHeight,maxBytes:r.captureMaxBytes},a=Pt("capture",await e.call("capture",{target:t,caps:s}),Ot),l=a.artifactPath??void 0;void 0!==l&&o.push({path:l,width:a.width,height:a.height,sourceWidth:a.sourceWidth,sourceHeight:a.sourceHeight,target:a.target}),!0!==n.silent&&(i.text(function(e){let t=`${e.width}x${e.height}`,n=e.width!==e.sourceWidth||e.height!==e.sourceHeight?` (scaled from ${e.sourceWidth}x${e.sourceHeight})`:"",r=e.artifactPath?` -> ${e.artifactPath}`:"";return`screenshot ${e.target} ${t}${n}${r}`}(a)),"artifact-only"!==a.mode&&a.data&&a.mimeType?i.image(a.data,a.mimeType):i.text(a.note??"screenshot is available only as the artifact above"));let{width:u,height:c,sourceWidth:d,sourceHeight:p,scale:h,frameId:f}=a;return{target:a.target,frameId:f,width:u,height:c,sourceWidth:d,sourceHeight:p,scale:h,...void 0===l?{}:{path:l}}}(t,this.#x,e))}click(e,t,n){return this.send("click","click",{target:this.#x,x:e,y:t,opts:It(n)})}doubleClick(e,t,n){let r=It({...n,count:2});return this.send("doubleClick","click",{target:this.#x,x:e,y:t,opts:r})}move(e,t){return this.send("move","moveMouse",{target:this.#x,x:e,y:t})}drag(e,t){let n=e.map(([e,t])=>({x:e,y:t}));return this.send("drag","drag",{target:this.#x,path:n,opts:It(t)})}scroll(e,t,n={}){let{dx:r=0,dy:i=0}=n;return this.send("scroll","scroll",{target:this.#x,x:e,y:t,dx:r,dy:i,opts:It(n)})}type(e,t){return this.send("type","typeText",{target:this.#x,text:e,opts:It(t)})}press(e,t){let n={target:this.#x,keys:Tt(e),opts:It(t)};return this.send("press","keyChord",n)}}class Nt extends At{id;app;title;pid;bounds;focused;constructor(e,t){super(e,t.id,F),this.id=t.id,this.app=t.app,this.title=t.title,this.pid=t.pid??void 0,this.bounds={x:t.x,y:t.y,width:t.width,height:t.height},this.focused=t.focused}raise(){return this.send("raise","raiseWindow",{windowId:this.id})}ax(e){return this.method("ax",async({call:t})=>Pt("ax.snapshot",await t("ax.snapshot",{target:this.id,opts:e}),$t).text)}find(e){return this.method("find",async t=>Pt("ax.query",await t.call("ax.query",{target:this.id,query:e}),Et(xt)).map(e=>new Rt(t,e)))}ref(e){return this.method("ref",t=>jt(t,e))}}async function jt(e,t){return new Rt(e,Pt("ax.node",await e.call("ax.node",{ref:t}),xt))}class Rt{ref;role;nativeRole;title;description;enabled;focused;childCount;#O;constructor(e,t){this.#O=U(e,J),this.ref=t.ref,this.role=t.role,this.nativeRole=t.nativeRole,this.title=t.title??void 0,this.description=t.description??void 0,this.enabled=t.enabled,this.focused=t.focused,this.childCount=t.childCount}#$(e,t,n){return this.#O(e,async({call:e})=>{await e(t,{ref:this.ref,...n})})}#S(e,t){return this.#O(e,async({call:e})=>t(Pt("ax.node",await e("ax.node",{ref:this.ref}),xt)))}value(){return this.#S("value",e=>e.value??void 0)}setValue(e){return this.#$("setValue","ax.setValue",{value:e})}bounds(){return this.#S("bounds",({x:e,y:t,width:n,height:r})=>null==e||null==t||null==n||null==r?null:{x:e,y:t,width:n,height:r})}attributes(){return this.#O("attributes",async({call:e})=>Object.fromEntries(Pt("ax.attributes",await e("ax.attributes",{ref:this.ref}),St)))}actions(){return this.#S("actions",e=>e.actions??[])}perform(e){return this.#$("perform","ax.perform",{action:e})}press(){return this.#$("press","ax.perform",{action:"press"})}click(e){return this.#$("click","ax.click",{opts:It(e)})}focus(){return this.#$("focus","ax.focus",{})}parent(){return this.#O("parent",async e=>{let t=Pt("ax.parent",await e.call("ax.parent",{ref:this.ref}),zt(xt));return null===t?null:new Rt(e,t)})}children(){return this.#O("children",async e=>Pt("ax.children",await e.call("ax.children",{ref:this.ref}),Et(xt)).map(t=>new Rt(e,t)))}}function Ct(e,t={}){let n=t.app?.toLocaleLowerCase(),r=t.title?.toLocaleLowerCase();return(!n||e.app.toLocaleLowerCase().includes(n))&&(!r||e.title.toLocaleLowerCase().includes(r))}function Mt(e){let t=U(e,L),n=async({call:e})=>Pt("windows",await e("windows",{}),Et(kt)),r=async(t,n)=>{let r=Pt(t,await e.call(t,n),zt(xt));return null===r?null:new Rt(e,r)},i=new At(e,"desktop",L);return{capabilities:()=>t("capabilities",async({call:e})=>Pt("capabilities",await e("capabilities",{}),de)),displays:()=>t("displays",async({call:e})=>Pt("displays",await e("displays",{}),Et(_t))),windows:e=>t("windows",async t=>(await n(t)).filter(t=>Ct(t,e))),window:r=>t("window",async t=>{let i=(await n(t)).filter(e=>"string"==typeof r?e.id===r:Ct(e,r)),[o,...s]=i;if(void 0===o)throw new D("window",`no window matches ${JSON.stringify(r)}`);if(s.length>0){let e=i.map(e=>`${e.id} ${e.app} ${JSON.stringify(e.title)}`);throw new D("window",`multiple windows match ${JSON.stringify(r)}:\n${e.join("\n")}`)}return new Nt(e,o)}),focusedWindow:()=>t("focusedWindow",async t=>{let r=(await n(t)).find(e=>e.focused);return void 0===r?null:new Nt(e,r)}),screenshot:i.screenshot.bind(i),click:i.click.bind(i),doubleClick:i.doubleClick.bind(i),move:i.move.bind(i),drag:i.drag.bind(i),scroll:i.scroll.bind(i),type:i.type.bind(i),press:i.press.bind(i),elementAt:(e,n)=>t("elementAt",()=>r("ax.elementAt",{target:"desktop",x:e,y:n})),focusedElement:()=>t("focusedElement",()=>r("ax.focused",{})),ref:e=>t("ref",t=>jt(t,e)),clipboard:{read:()=>t("clipboard.read",async({call:e})=>Pt("clipboard.read",await e("clipboard.read",{}),$t).text),write:e=>t("clipboard.write",async({call:t})=>{await t("clipboard.write",{text:e})})}}}import{randomUUID as Dt}from"node:crypto";import{format as Zt}from"node:util";import Ut from"node:vm";function Lt(e,t){t.throwIfAborted();let{promise:n,resolve:r,reject:i}=Promise.withResolvers(),o=()=>{clearTimeout(s),i(t.reason)},s=setTimeout(()=>{t.removeEventListener("abort",o),r()},e);return t.addEventListener("abort",o,{once:!0}),n}function Ft(e,t){return async(n,r={})=>{if("number"==typeof n)return Lt(n,e);if("function"!=typeof n)throw new D("wait","wait(...) expects milliseconds or a predicate function to poll");let i=Math.max(r.interval??100,10);return async function(e,t,n,r){let i=new AbortController,o=setTimeout(()=>i.abort(),n);try{for(;;){let o=await e();if(t.throwIfAborted(),o)return o;if(i.signal.aborted)throw new D("wait",`wait(predicate) timed out after ${n} ms; the predicate never returned truthy`);await Lt(r,t)}}finally{clearTimeout(o)}}(()=>n(),e,function(e,t){let n=Math.max(1,e-1e3);return 0===t||t===Number.POSITIVE_INFINITY?n:void 0!==t&&Number.isFinite(t)&&t>0?Math.min(t,n):Math.min(3e4,n)}(t,r.timeout),i)}}var Jt="computer-run.js";function Vt(e){return se(e)&&"ERR_SCRIPT_EXECUTION_TIMEOUT"===e.code}function qt(e){if(void 0!==e){try{return structuredClone(e)}catch(e){if(!(e instanceof DOMException))throw e}try{return JSON.parse(JSON.stringify(e)??"null")}catch(t){if(!(t instanceof TypeError))throw t;return String(e)}}}async function Wt(e,t){let{code:n,snapshot:r,timeoutMs:i}=e,o=Dt(),s=new AbortController,{signal:a}=s,l=Date.now()+i,u=e=>s.abort(e),c=()=>new D("timeout",`computer run timed out after ${i} ms`),d=setTimeout(()=>u(c()),i),p=()=>u(new D("aborted","computer run was aborted"));e.signal?.addEventListener("abort",p,{once:!0}),e.signal?.aborted&&p();let h=[],f=t.service.onAudit(e=>h.push(function(e,t,n){let{action:r,target:i,delivery:o,durationMs:s,focusRestored:a,textLength:l,textSha256:u,keys:c}=e,d=e.code??null;return{timestamp:(new Date).toISOString(),sessionId:t,runId:n,action:r,target:i,delivery:o,frameId:e.frameId??null,code:d,status:null===d?"success":"Suspended"===d?"suspended":"error",durationMs:s,...null==a?{}:{focusRestored:a},...null==l?{}:{textLength:l},...null==u?{}:{textSha256:u},...null==c?{}:{keys:c}}}(e,r.sessionId,o))),m={signal:a,readOnly:r.readOnly,snapshot:r,output:new Z,screenshots:[]},g=new Ut.Script(""),y=()=>{if(!a.aborted)try{g.runInContext(_,{timeout:Math.max(1,l-Date.now())})}catch(e){u(Vt(e)?c():e)}},v=e=>{let t=()=>setImmediate(y);return e.then(t,t),e},b=Ft(a,i),w=(...e)=>m.output.text(Zt(...e)),_=Ut.createContext({desktop:Mt({context:m,call:(e,n)=>t.service.call(e,n,{signal:a}),resume:v}),wait:(e,t)=>v(b(e,t)),assert:(e,t)=>{if(!e)throw new D("assertion",t??"Assertion failed")},tool:new Proxy({},{get:(e,n)=>e=>(a.throwIfAborted(),v(t.executeTool(String(n),e,{signal:a})))}),console:{log:w,info:w,warn:w,error:w,debug:w}},{name:Jt,microtaskMode:"afterEvaluate"});try{a.throwIfAborted();let e=new Ut.Script(`(async () => {\n${n}\n})()`,{filename:Jt,lineOffset:-1}).runInContext(_,{timeout:i}),t=await new Promise((t,n)=>{a.addEventListener("abort",()=>n(a.reason),{once:!0}),a.throwIfAborted(),Promise.resolve(e).then(t,n),setImmediate(y)});return{displays:m.output.finish(),returnValue:qt(t),screenshots:[...m.screenshots],audit:[...h]}}catch(e){throw Vt(e)?c():e}finally{clearTimeout(d),e.signal?.removeEventListener("abort",p),f(),a.aborted||s.abort(new D("ended","computer run has ended"))}}class Bt extends Error{method;constructor(e,t){super(`desktop engine notification ${JSON.stringify(e)} ${t}`),this.name="DesktopNotificationError",this.method=e}}function Ht(e,t){return e.add(t),()=>{e.delete(t)}}class Kt{#E=new Set;#z=new Set;#P=new Set;onAudit(e){return Ht(this.#E,e)}onStopPathChange(e){return Ht(this.#z,e)}onError(e){return Ht(this.#P,e)}emitError(e){for(let t of this.#P)t(e)}dispatch(e,t){let n=X.find(t=>t===e);void 0!==n?this.#I(n,t):this.emitError(new Bt(e,"is not part of the engine protocol"))}#I(e,t){switch(e){case"audit":if(ae(n=t,oe)&&ue(n.action,Q)&&(void 0===n.code||null===n.code||ue(n.code,ee))&&(void 0===n.keys||null===n.keys||le(n.keys)))for(let e of this.#E)e(t);else this.emitError(new Bt(e,"is malformed"));return;case"stopPath.changed":if(ce(t))for(let e of this.#z)e(t);else this.emitError(new Bt(e,"is malformed"));return;case"engine.log":return;default:!function(e){throw Error(`unhandled engine notification ${JSON.stringify(e)}`)}(e)}var n}}class Gt{#T;#A=new Kt;#N=Promise.resolve();#j;#R;#C;constructor(e={}){this.#T=e.createChild??dt(),this.#A.onStopPathChange(e=>{this.#C=e})}onAudit(e){return this.#A.onAudit(e)}onStopPathChange(e){return this.#A.onStopPathChange(e)}onError(e){return this.#A.onError(e)}open(e){return this.#M(async()=>{this.#R={params:e,chord:this.#R?.chord};let t=this.#j;return!0===t?.rpc.alive?this.#D(t,e):(void 0!==t&&this.#Z(t),(await this.#U(this.#R)).capabilities)})}ensureStopPath(e){return this.#M(async()=>{let t=await this.#L();if(t.armedChord===e)return this.#z(t,"stopPath.status",{});let n=await this.#z(t,"stopPath.start",{chord:e});return t.armedChord=e,void 0!==this.#R&&(this.#R.chord=e),n})}async call(e,t,n={}){return(await this.#F()).rpc.request(e,t,n)}async capabilities(){let e=await this.call("capabilities",{},{timeoutMs:1e4});if(!de(e))throw Xt("capabilities");return e}async stopPathStatus(){return this.#z(await this.#F(),"stopPath.status",{})}async stop(){return this.#z(await this.#F(),"stopPath.stop",{source:"host-relay"})}async resume(){let e=await this.#F();return this.#z(e,"stopPath.resume",{token:e.resumeToken})}close(){return this.#M(async()=>{this.#R=void 0;let e=this.#j;if(void 0===e)return;if(this.#Z(e),!e.rpc.alive)return;try{await Yt((async()=>{await e.rpc.request("session.close",{}),e.rpc.end(),await e.rpc.exited})(),1500,"Timed out closing desktop engine")}finally{e.rpc.kill()}})}#M(e){let t=this.#N.then(e);return this.#N=t.then(()=>{},()=>{}),t}#F(){let e=this.#j;return!0===e?.rpc.alive?Promise.resolve(e):this.#M(()=>this.#L())}async#L(){let e=this.#j;if(!0===e?.rpc.alive)return e;if(void 0!==e&&this.#Z(e),void 0===this.#R)throw new ft("Closed","desktop session is not open");return(await this.#U(this.#R)).connection}async#U(e){let t=new gt(await this.#T(),{onNotification:(e,t)=>this.#A.dispatch(e,t),onExit:()=>{this.#j?.rpc===t&&this.#Z(this.#j)}}),n={rpc:t,resumeToken:"",armedChord:void 0,heartbeat:void 0};try{let t=await Yt(this.#J(n,e),1e4,"Timed out starting desktop engine");return this.#j=n,n.heartbeat=setInterval(()=>this.#V(n),500),{connection:n,capabilities:t}}catch(e){throw t.kill(),e}}async#J(e,t){let n=function(e){if(se(e)&&"string"==typeof e.abi&&"string"==typeof e.protocolVersion)return{abi:e.abi,protocolVersion:e.protocolVersion}}(await e.rpc.request("engine.hello",{}));if(void 0===n)throw Xt("engine.hello");if(n.abi!==G||n.protocolVersion!==K)throw new me(e.rpc.enginePath,n);let r=await this.#D(e,t.params);return void 0!==t.chord&&(await this.#z(e,"stopPath.start",{chord:t.chord}),e.armedChord=t.chord),!0===this.#C?.suspended&&await this.#z(e,"stopPath.stop",{source:"host-relay"}),r}async#D(e,t){let n=function(e){if(se(e)&&"string"==typeof e.resumeToken&&de(e.capabilities))return{capabilities:e.capabilities,resumeToken:e.resumeToken}}(await e.rpc.request("session.open",t,{timeoutMs:1e4}));if(void 0===n)throw Xt("session.open");return e.resumeToken=n.resumeToken,n.capabilities}async#z(e,t,n){let r=await e.rpc.request(t,n);if(!ce(r))throw Xt(t);return this.#C=r,r}#V(e){e.rpc.request("stopPath.heartbeat",{}).catch(e=>{if(!(e instanceof ft&&"Closed"===e.code)){if(!(e instanceof ft||e instanceof mt))throw e;this.#A.emitError(e)}})}#Z(e){clearInterval(e.heartbeat),this.#j===e&&(this.#j=void 0)}}function Xt(e){return new ft("Internal",`desktop engine sent a malformed ${e} result`)}function Yt(e,t,n){return new Promise((r,i)=>{let o=setTimeout(()=>i(new ft("Timeout",n)),t);e.then(e=>{clearTimeout(o),r(e)},e=>{clearTimeout(o),i(e)})})}var Qt={name:"computer_actions",label:"Computer actions",description:["Drive the user's real desktop with OpenAI computer-use actions (experimental): screenshot, click, double_click, move, drag, scroll, type, keypress, wait, or a batch of them.","x,y are pixels of the latest screenshot. A batch stops at the first failed action; an in-batch screenshot becomes the frame for the actions after it.","Pass only the fields the chosen action takes (each field's description names its actions); anything else is refused with COMPUTER_INVALID_ARGUMENTS before any input.","Errors carry COMPUTER_* codes with a recovery hint. COMPUTER_SUSPENDED or COMPUTER_SUPERVISOR_NOT_LIVE means the user stopped you: stop and wait."].join("\n"),exposure:"search",searchText:"OpenAI computer-use actions (experimental): screenshot, click, type, keypress, scroll, drag, batch",searchKeywords:["computer use","cua","openai computer","click","screenshot","keypress"],searchGroup:"desktop",parameters:j,executionMode:"sequential"},en={Suspended:"COMPUTER_SUSPENDED",StopPathUnavailable:"COMPUTER_SUPERVISOR_NOT_LIVE",PermissionDenied:"COMPUTER_PERMISSION_REQUIRED",InvalidCoordinateFrame:"COMPUTER_DISPLAY_STALE",ScreenLocked:"COMPUTER_SCREEN_LOCKED",CaptureFailed:"COMPUTER_SCREENSHOT_FAILED",CursorRestoreFailed:"COMPUTER_CURSOR_RESTORE_FAILED",FocusRestoreFailed:"COMPUTER_FOCUS_RESTORE_FAILED",BackgroundUnavailable:"COMPUTER_BACKGROUND_UNAVAILABLE",Cancelled:"COMPUTER_CANCELLED",Timeout:"COMPUTER_CANCELLED",timeout:"COMPUTER_CANCELLED",aborted:"COMPUTER_CANCELLED"};function tn(e,t,n,r){let i=e.startsWith("COMPUTER_")?e:en[e]??"COMPUTER_ERROR",o=function(e,t){let n=`Stop and wait for the user (stop chord: ${t}); only the user resumes, with /computer resume.`;switch(e){case"COMPUTER_COORD_INVALID":return"Capture a fresh screenshot and use coordinates within its frame.";case"COMPUTER_DISPLAY_STALE":return"Capture a fresh screenshot before acting; the display changed since the last screenshot.";case"COMPUTER_SUSPENDED":case"COMPUTER_SUPERVISOR_NOT_LIVE":case"COMPUTER_CANCELLED":return n;case"COMPUTER_PERMISSION_REQUIRED":return"Do not retry until the user says the grant is done and the app was relaunched.";case"COMPUTER_PERMISSION_DENIED":return"A permission rule denied this action; do not retry it.";case"COMPUTER_CURSOR_RESTORE_FAILED":case"COMPUTER_FOCUS_RESTORE_FAILED":return"Input may have completed, but the previous state was not restored. Ask the user to inspect the desktop before retrying.";case"COMPUTER_BACKGROUND_UNAVAILABLE":return"This window cannot take background input; use the computer tool's accessibility actions instead.";default:return}}(i,n);return{code:i,message:`${i}: ${t}${void 0===o?"":` ${o}`}`,...r??{}}}import{Type as nn}from"typebox";var rn=nn.Object({method:nn.String({description:"desktop helper name, e.g. screenshot, window, click, clipboard.read"}),args:nn.Optional(nn.Array(nn.Unknown(),{description:"positional helper arguments"}))},{additionalProperties:!1}),on=nn.Number({minimum:1,maximum:600,description:"run: budget in seconds (default 60)"}),sn=[nn.Object({action:nn.Literal("call"),chain:nn.Array(rn,{description:"one desktop helper call, optionally followed by one call on the window/element it returns"})},{additionalProperties:!1}),nn.Object({action:nn.Literal("run"),code:nn.String({description:"JavaScript async function body; `desktop`, `wait`, `assert`, `tool` in scope; `return` sets the value"}),read_only:nn.Optional(nn.Boolean({description:"true = inspection only: screenshots and AX reads, input/mutation blocked"})),timeout:nn.Optional(on)},{additionalProperties:!1}),nn.Object({action:nn.Literal("capabilities")},{additionalProperties:!1}),nn.Object({action:nn.Literal("close")},{additionalProperties:!1})],an=nn.Union([...sn]),ln=nn.Object({action:nn.Enum(["call","run","capabilities","close"],{type:"string",description:"call: one desktop helper chain; run: a JavaScript body; capabilities: host report; close: end the session"}),chain:nn.Optional(nn.Array(rn,{description:"call (required): one desktop helper call, optionally followed by one call on the window/element it returns"})),code:nn.Optional(nn.String({description:"run (required): JavaScript async function body; `desktop`, `wait`, `assert`, `tool` in scope; `return` sets the value"})),read_only:nn.Optional(nn.Boolean({description:"run: true = inspection only: screenshots and AX reads, input/mutation blocked"})),timeout:nn.Optional(on)},{additionalProperties:!1});import{Check as un}from"typebox/value";import{readFileSync as cn}from"node:fs";import{dirname as dn,join as pn}from"node:path";import{fileURLToPath as hn}from"node:url";var fn,mn=["COMPUTER_PRELUDE_JAVASCRIPT","COMPUTER_PRELUDE_PYTHON","COMPUTER_DECLARATIONS","COMPUTER_DOCUMENTATION","COMPUTER_SAFETY"],gn=pn(dn(hn(import.meta.url)),"assets.generated.json");function yn(){if(void 0===fn){let e=JSON.parse(cn(gn,"utf8"));fn=function(e){let t=e&&"object"==typeof e?e:void 0,n=mn.filter(e=>"string"!=typeof t?.[e]);if(n.length>0)throw Error(`senpi-desktop-prelude asset JSON is malformed at ${gn}: missing ${n.join(", ")}`);return e}(e)}return fn}var vn={get javascript(){return yn().COMPUTER_PRELUDE_JAVASCRIPT},get python(){return yn().COMPUTER_PRELUDE_PYTHON},get declarations(){return yn().COMPUTER_DECLARATIONS},get documentation(){return yn().COMPUTER_DOCUMENTATION},get safety(){return yn().COMPUTER_SAFETY},exports:["computer"],methodAllowlist:["actions","attributes","ax","bounds","capabilities","children","click","clipboard.read","clipboard.write","displays","doubleClick","drag","elementAt","find","focus","focusedElement","focusedWindow","move","parent","perform","press","raise","ref","screenshot","scroll","setValue","type","value","window","windows"]},bn={name:"computer",label:"Computer",description:["Drive the user's real desktop (experimental): windows, screenshots, native mouse and keyboard input, the OS accessibility (AX) tree, and the clipboard. Not a browser.",'- `{action:"call", chain}` runs one desktop helper, optionally followed by one call on the window/element it returns, e.g. `[{method:"window",args:[{app:"Code"}]},{method:"screenshot"}]`.','- `{action:"run", code, read_only?, timeout?}` runs a JavaScript async function body with `desktop`, `wait`, `assert`, and `tool` in scope; `read_only: true` blocks input.','- `{action:"capabilities"}` reports backend, permissions, `stopPath`, and `focusGuard`; availability is unknown until `computer.capabilities()` returns in this session, so make no availability claim before it and repeat the host and reason on `native-unavailable`. `{action:"close"}` ends the desktop session.',"Pass only the fields of the chosen action; any other field is refused with COMPUTER_INVALID_ARGUMENTS.","In eval cells prefer the `computer` global, which wraps these actions. Pointer x,y are pixels of the latest screenshot of the same target."].join("\n"),exposure:"search",searchText:"Operate the real desktop (experimental): screenshots, clicks, typing, key chords, window list, accessibility tree, clipboard; macOS/Linux/Windows",searchKeywords:["computer use","computer-use","cua","desktop","gui","screenshot","click","type","keyboard","mouse","window","accessibility","ax","clipboard","automation"],searchGroup:"desktop",promptSnippet:"Operate the real desktop (experimental): screenshots, native input, accessibility tree, clipboard",promptGuidelines:vn.safety.split("\n").filter(e=>e.startsWith("- ")).map(e=>e.slice(2)),kernelPrelude:vn,parameters:ln,executionMode:"sequential"},wn=w(sn);function _n(e){return"string"==typeof e?e:JSON.stringify(e,null,2)??String(e)}function kn(e,t){return{content:[{type:"text",text:void 0===e?t:_n(e)}],details:{value:e}}}async function xn(e,t,n,r){let{handle:i,executeTool:o}=e;await i.activate(t);let s=function(e,t,n){return{cwd:t.cwd,sessionId:t.sessionManager.getSessionId(),captureMaxWidth:e.maxWidth,captureMaxHeight:e.maxHeight,captureMaxBytes:e.screenshotMaxBytes,display:e.display,readOnly:n,stopHotkey:e.stopHotkey,allowHostRelayOnlyStop:e.allowHostRelayOnlyStop}}(i.settings(),t,n.readOnly),a=1e3*n.timeoutSeconds,l=await Wt({code:n.code,snapshot:s,timeoutMs:a,...void 0===r?{}:{signal:r}},{service:i.service,executeTool:o}),u=[...l.displays];return void 0!==l.returnValue&&u.push({type:"text",text:_n(l.returnValue)}),0===u.length&&u.push({type:"text",text:"Done."}),{content:u,details:{value:l.returnValue,readOnly:n.readOnly,screenshots:l.screenshots,audit:l.audit}}}function On(e){let{handle:t}=e,n=(t,n,r)=>xn(e,t,n,r);return{...bn,async execute(e,r,i,o,s){let a=function(e){if(un(an,e))return e;throw _(wn,e,"computer")}(r);switch(a.action){case"call":{let e=H(a.chain),r=function(e){let t=e=>`${e.method}(...${JSON.stringify(e.args??[])})`,[n,r]=e;if(void 0===n)throw TypeError("renderCallChain: empty chain");return void 0===r?`return await desktop.${t(n)};`:`return await (await desktop.${t(n)}).${t(r)};`}(a.chain);return $n(n(s,{code:r,readOnly:e,timeoutSeconds:60},i),t)}case"run":{let e=a.timeout??60;return $n(n(s,{code:a.code,readOnly:!0===a.read_only,timeoutSeconds:e},i),t)}case"capabilities":return await t.activate(s),kn(await t.service.capabilities(),"capabilities unavailable");case"close":return await t.close(),kn(void 0,"Closed the desktop session.");default:return function(e){throw TypeError(`unhandled computer action ${JSON.stringify(e)}`)}(a)}}}}async function $n(e,t){try{return await e}catch(e){if(!(e instanceof mt&&null!==e.data&&"code"in e.data&&"PermissionDenied"===e.data.code))throw e;let n=tn(e.data.code,e.message,t.settings().stopHotkey,e.data.permission);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{value:n},isError:!0}}}function Sn(e){let t=null;return{...Qt,async execute(n,r,i,o,s){let a,l=e.handle.settings().stopHotkey;try{a=function(e){if(x(T,e))return e;let t="object"==typeof e&&null!==e?Reflect.get(e,"actions"):void 0;if("batch"===Reflect.get(e??{},"action")&&Array.isArray(t)){let e=t.findIndex(e=>!x(P,e));if(e>=0)throw _(R,t[e],`computer_actions actions[${e}]`)}throw _(C,e,"computer_actions")}(r)}catch(e){if(!(e instanceof b))throw e;let t=tn(e.code,e.reason,l);return{content:[{type:"text",text:t.message}],details:{value:t},isError:!0}}let u,c=Math.min(a.timeout??60,600),d=function(e){let t="batch"===e.action?e.actions:[e];return Array.isArray(t)&&t.length>0&&t.every(e=>"object"==typeof e&&null!==e&&M.has(String(Reflect.get(e,"action"))))}(a),p=function(e,t){return`const actions = ${JSON.stringify(e)};\nlet bounds = ${JSON.stringify(t)};\nconst steps = [];\nconst outside = (x, y) => bounds !== null && (x < 0 || y < 0 || x >= bounds.width || y >= bounds.height);\nconst shoot = async () => { const shot = await desktop.screenshot(); bounds = { width: shot.width, height: shot.height }; };\nfor (const [index, a] of actions.entries()) {\n\tconst points = a.action === "drag" ? [[a.x, a.y], [a.to_x, a.to_y]] : "x" in a ? [[a.x, a.y]] : [];\n\tconst off = points.find(([x, y]) => outside(x, y));\n\tif (off !== undefined) {\n\t\tconst message = a.action + " coordinates (" + off[0] + "," + off[1] + ") are outside the latest screenshot bounds " + bounds.width + "x" + bounds.height + ".";\n\t\tsteps.push({ index, action: a.action, status: "error", code: "COMPUTER_COORD_INVALID", message });\n\t\treturn { steps, bounds, failedIndex: index };\n\t}\n\ttry {\n\t\tconst button = a.button === undefined ? {} : { button: a.button };\n\t\tswitch (a.action) {\n\t\t\tcase "screenshot": await shoot(); break;\n\t\t\tcase "click": await desktop.click(a.x, a.y, button); break;\n\t\t\tcase "double_click": await desktop.doubleClick(a.x, a.y, button); break;\n\t\t\tcase "move": await desktop.move(a.x, a.y); break;\n\t\t\tcase "drag": await desktop.drag([[a.x, a.y], [a.to_x, a.to_y]], button); break;\n\t\t\tcase "scroll": await desktop.scroll(a.x, a.y, { dx: a.scroll_x, dy: a.scroll_y }); break;\n\t\t\tcase "type": await desktop.type(a.text); break;\n\t\t\tcase "keypress": await desktop.press(a.keys); break;\n\t\t\tcase "wait": await wait(a.ms); break;\n\t\t}\n\t\tif (a.include_screenshot === true && a.action !== "screenshot") await shoot();\n\t\tsteps.push({ index, action: a.action, status: "success" });\n\t} catch (error) {\n\t\tconst code = error?.data?.code ?? error?.reason ?? error?.name ?? "Error";\n\t\tsteps.push({ index, action: a.action, status: "error", code, message: String(error?.message ?? error), permission: error?.data?.permission });\n\t\treturn { steps, bounds, failedIndex: index };\n\t}\n}\nreturn { steps, bounds, failedIndex: null };`}(function(e){return"batch"===e.action?e.actions:[e]}(a),t);try{u=await xn(e,s,{code:p,readOnly:d,timeoutSeconds:c},i)}catch(e){if(!(e instanceof Error))throw e;let t=e instanceof mt&&null!==e.data&&"code"in e.data?e.data:void 0,n=t?.code??Reflect.get(e,"reason")??Reflect.get(e,"code")??e.name,r=tn(String(n),e.message,l,t?.permission);return{content:[{type:"text",text:r.message}],details:{value:r},isError:!0}}let h=u.details.value;if("object"!=typeof(f=h)||null===f||!Array.isArray(Reflect.get(f,"steps")))return u;var f;t=h.bounds;let m=u.content.filter(e=>"image"===e.type),g=null===h.failedIndex?void 0:h.steps[h.failedIndex];if(void 0===g){let e=`${h.steps.length} action(s) done: ${h.steps.map(e=>e.action).join(", ")}.`;return{...u,content:[...m,{type:"text",text:e}]}}let y=tn(g.code??"Error",g.message??"action failed",l,g.permission),v=`Action ${g.index+1} (${g.action}) failed. ${void 0===y.permission?y.message:JSON.stringify(y)}`;return{content:[...m,{type:"text",text:v}],details:{...u.details,value:{...h,failure:y}},isError:!0}}}}import{Type as En}from"typebox";import{Check as zn,Errors as Pn}from"typebox/value";En.Object({enabled:En.Optional(En.Boolean({description:"Register the computer tool (experimental; default: host supported)"})),display:En.Optional(En.String({description:"`all` composites every display; otherwise a display id"})),maxWidth:En.Optional(En.Integer({minimum:1,default:3840})),maxHeight:En.Optional(En.Integer({minimum:1,default:2400})),screenshotMaxBytes:En.Optional(En.Integer({minimum:1,default:5e6})),stopHotkey:En.Optional(En.String({minLength:1,description:"Stop chord, e.g. ctrl+alt+shift+escape"})),allowHostRelayOnlyStop:En.Optional(En.Boolean({default:!1})),macosCanary:En.Optional(En.Union([En.Literal("session"),En.Literal("off")],{default:"session"})),auditLog:En.Optional(En.Object({enabled:En.Optional(En.Boolean({default:!0}))},{additionalProperties:!1})),screenshotGc:En.Optional(En.Object({enabled:En.Optional(En.Boolean({default:!0})),staleMs:En.Optional(En.Integer({minimum:0,default:432e5})),scanIntervalMs:En.Optional(En.Integer({minimum:0,default:18e5}))},{additionalProperties:!1})),enginePath:En.Optional(En.String({minLength:1,description:"Override the located engine binary"})),cuaAdapter:En.Optional(En.Boolean({default:!1,description:"Also register computer_actions (OpenAI computer-use actions)"}))},{additionalProperties:!1});import{readFileSync as In}from"node:fs";import{dirname as Tn,join as An}from"node:path";import{accessSync as Nn,constants as jn,existsSync as Rn}from"node:fs";import{homedir as Cn}from"node:os";import{join as Mn}from"node:path";function Dn(e,t,n,r=e=>Le(e,n)){let i={host:t,attemptedPaths:[e]};if(!Rn(e))return{...i,code:"native-unavailable",message:`No senpi-desktop-engine binary is available for ${t}.`,cause:`${e}: missing`};if(r(e))return{...i,code:"quarantined",message:`The senpi-desktop-engine binary for ${t} is quarantined by macOS Gatekeeper: ${e}.`,cause:`${e}: blocked because com.apple.quarantine is present (macOS Gatekeeper)`};if("win32"===n)return/\.exe$/i.test(e)?void 0:Zn(i,t,`${e}: not executable (expected a .exe file)`);try{return void Nn(e,jn.X_OK)}catch(n){if(!(n instanceof Error&&"code"in n))throw n;return Zn(i,t,`${e}: not executable (chmod +x)`)}}function Zn(e,t,n){return{...e,code:"native-unavailable",message:`No senpi-desktop-engine binary is available for ${t}.`,cause:n}}function Un(e,t,n,r={}){let i=r.platform??process.platform,o=Re(i,r.arch,r.libc);if(void 0!==e){let t=Dn(e,o,i,r.isQuarantined);return void 0===t?{path:e,source:"explicit"}:{diagnostic:t}}let s={...r,runtimeDir:r.runtimeDir??t.OMO_PACKAGE_DIR??""},a=Ze(s);if(null!==a.path){let e=De(s),t=s.runtimeDir?["runtime-dir","sidecar","package-prebuild","dev-build"]:["sidecar","package-prebuild","dev-build"];return{path:a.path,source:t[e.indexOf(a.path)]}}if("quarantined"===a.diagnostic.code)return{diagnostic:a.diagnostic};if(void 0!==n){let e=at({host:o,version:n,cacheDir:Mn(t.HOME??Cn(),".omo","cache","senpi-desktop-engine")});if(null!==e.path)return{path:e.path,source:"cache"}}return null===Pe(o)?{diagnostic:a.diagnostic}:{notInstalled:a.diagnostic}}function Ln(e,t){let n;try{n=JSON.parse(In(An(e,"package.json"),"utf8"))}catch{return}if("object"!=typeof n||null===n)return;let r=Reflect.get(n,"name"),i=Reflect.get(n,"version");return"string"==typeof r&&t.includes(r)&&"string"==typeof i&&i.length>0?i:void 0}function Fn(e){let t=e.OMO_PACKAGE_DIR?.trim();if(t){let e=Ln(t,["omo"]);if(void 0!==e)return e}let n=e.OMO_BIN?.trim();return n?Ln(Tn(Tn(n)),["omo-ai"]):void 0}function Jn(e=process.env,t){return n=>{if(void 0!==n)return function(e){let t=Re(),n=Dn(e,t,process.platform);return void 0!==n?()=>{throw new ct(n)}:dt(e)}(n);let r=Fn(e);return void 0!==r?function(e){let t=e.acquire??lt,n=e.spawnEngine??pt;return async()=>{let r=await ut({version:e.version,host:e.host??Re()},n,t);if(null===r.path)throw new ct(r.diagnostic);return r.value}}({version:r}):void 0===t?dt():()=>{let e=Ze(t);if(null===e.path)throw new ct(e.diagnostic);return dt(e.path)()}}}function Vn(e,t,n={}){let r=Fn(t),i=Un(e,t,r,n);if("path"in i){let e="cache"===i.source?`, omo v${r}`:"";return`found ${i.path} (${i.source}${e})`}if("diagnostic"in i)return"no-release-asset"===i.diagnostic.reason?i.diagnostic.message:`${i.diagnostic.message} ${i.diagnostic.cause}`;let o=Pe(i.notInstalled.host);return void 0!==r&&null!==o?`would download ${o} from omo v${r} on first use`:`native-unavailable for ${i.notInstalled.host}: ${i.notInstalled.cause}`}class qn extends Error{diagnostic;constructor(e,t){super(`Desktop engine unavailable (${e}): ${t.message}`,{cause:t}),this.name="ComputerEngineUnavailableError",this.diagnostic=e}}class Wn extends Gt{#q="not started";#W;constructor(e={}){super(e),this.#W=e.onError}get engineState(){return this.#q}async open(e){try{let t=await super.open(e);return this.#q="ready",t}catch(e){if(!(e instanceof Error))throw e;this.#W?.(e);let t=function(e){return e instanceof ct?e.diagnostic.code:e instanceof me?"abi-mismatch":void 0}(e);if(void 0===t)throw e;throw this.#q=t,new qn(t,e)}}async call(e,t,n={}){return this.#B(super.call(e,t,n))}ensureStopPath(e){return this.#B(super.ensureStopPath(e))}stopPathStatus(){return this.#B(super.stopPathStatus())}stop(){return this.#B(super.stop())}resume(){return this.#B(super.resume())}async#B(e){try{return await e}catch(e){if(!(e instanceof Error))throw e;throw this.#W?.(e),e}}}import{spawn as Bn}from"node:child_process";import{createInterface as Hn}from"node:readline";function Kn(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function Gn(e,t="|"){return e.map(e=>vr(e)).join(t)}function Xn(e,t){return"bigint"==typeof t?t.toString():t}class Yn{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return void 0!==e&&(this._value=e(),this._getter=void 0),this._value}}function Qn(e){return new Yn(e)}function er(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function tr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function nr(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function rr(e){return nr(e._zod.def)??e._zod.def.shape}function ir(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return tr(this,t,e),e},enumerable:!0,configurable:!0})}function or(e,t,n){t in e?tr(e,t,n):e[t]=n}function sr(e,t,n,r){let i=rr(t);for(let o of n){let n=Object.getOwnPropertyDescriptor(i,o);n.enumerable&&(n.get?ir(e,o,()=>{let e=t._zod.def.shape[o];return r?r(e,o):e}):or(e,o,r?r(n.value,o):n.value))}}function ar(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function lr(e){return JSON.stringify(e)}var ur="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function cr(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var dr=Qn(()=>{if(Gr.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function pr(e){if(!1===cr(e))return!1;let t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;let n=t.prototype;return!1!==cr(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function hr(e){return pr(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var fr=new Set(["string","number","symbol"]);function mr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gr(e,t,n){let r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function yr(e){let t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function vr(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}var br={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},wr={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function _r(e,t){let n=rr(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function kr(e,t){let n={};return sr(n,e,Reflect.ownKeys(rr(e))),function(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?ir(e,n,()=>t[n]):or(e,n,r.value))}}(n,t),n}function xr(e,t,n,r="partial"){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let o=n?new Set(_r(t,n)):void 0,s={};return sr(s,t,Reflect.ownKeys(rr(t)),e&&((t,n)=>o&&!o.has(n)?t:new e({type:"optional",innerType:t}))),gr(t,ar(t._zod.def,{shape:s,checks:[]}))}function Or(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function $r(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!1===e.issues[n]?.continue)return!0;return!1}function Sr(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Er(e){return"string"==typeof e?e:e?.message}function zr(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function Pr(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has("$ZodType")&&(i.has("$ZodCheck")?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let o=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,s=e.message?e.message:Er(e.inst?._zod.def?.error?.(e))??Er(o?.(e))??Er(t?.error?.(e))??Er(n.customError?.(e))??Er(n.localeError?.(e))??"Invalid input",a={};for(let t of Object.keys(e))"inst"!==t&&"schema"!==t&&"continue"!==t&&"input"!==t&&"__proto__"!==t&&(a[t]=e[t]);return a.path??(a.path=[]),a.message=s,t?.reportInput&&(a.input=e.input),a}var Ir=/[\uD800-\uDBFF]/;function Tr(e){let t=e.length;if(!Ir.test(e))return t;let n=t;for(let r=0;r<t-1;r++)55296==(64512&e.charCodeAt(r))&&56320==(64512&e.charCodeAt(r+1))&&(n--,r++);return n}function Ar(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function Nr(...e){let[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}function jr(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function Rr(e,t,n){return jr(e,t,n,!1)}function Cr(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return jr(this,n,r(this))},set(e){jr(this,n,e)}})}return t}function Mr(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return null==this?n:jr(this,t,n.bind(this))},set(e){jr(this,t,e)}})}var Dr,Zr=!1,Ur={configurable:!0,get(){Zr=!0}};function Lr(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&Dr!==e._zod?Dr=void 0:(Dr=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Ur);let e=Zr;Zr=!1;try{let r=n(this);return Zr?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),Zr=Zr||e,r}catch(n){throw delete this[t],Zr=Zr||e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function Fr(e,t,n,r){let i=function(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}var Jr;function Vr(e){let t=()=>e;return t["~constantCatch"]=!0,t}var qr={value:void 0,enumerable:!1},Wr="captureStackTrace"in Error?Error:null;function Br(e,t,n,r){function i(e){this.def=e,this.constr=c,this.traits=new Set}i.prototype={};let o=n,s=o&&new WeakSet;function a(n,r){if(n._zod){if(n._zod.traits.has(e))return}else{qr.value=new i(r);try{Object.defineProperty(n,"_zod",qr)}finally{qr.value=void 0}}if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),function(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):Mr(e,n,r.value)}}(i,o))}let a=c.prototype;for(let e in a)Object.prototype.hasOwnProperty.call(a,e)&&(e in n||(n[e]=a[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}function c(e){let t=r?.Parent?function(e){let t=Wr;if(t){let n=t.stackTraceLimit;if("number"==typeof n){try{t.stackTraceLimit=0}catch{return Wr=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}(u):this;a(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(u,"name",{value:e}),Object.defineProperty(c,"init",{value:a}),Object.defineProperty(c,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(c,"name",{value:e}),c}class Hr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Kr extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(Jr=globalThis).__zod_globalConfig??(Jr.__zod_globalConfig={});var Gr=globalThis.__zod_globalConfig;function Xr(e){return e&&Object.assign(Gr,e),Gr}var Yr={get:function(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Xn,2)),e.message},set:function(e){this._zod.message=e},enumerable:!0,configurable:!0},Qr={value:void 0,enumerable:!1},ei=new WeakSet([Object.prototype,Error.prototype]),ti=(e,t)=>{e.name="$ZodError",Qr.value=t,Object.defineProperty(e,"issues",Qr),Qr.value=void 0,Object.defineProperty(e,"message",Yr);let n=Object.getPrototypeOf(e);ei.has(n)||(ei.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},ni=Br("$ZodError",ti);Br("$ZodError",ti,void 0,{Parent:Error});function ri(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||("__proto__"===t?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function ii(e,t){return{callee:t?.callee??e,Err:t?.Err}}var oi=e=>{let t=(n,r,i,o)=>{let s=i?{...i,async:!1}:{async:!1},a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new Hr;if(a.issues.length){let n=new(o?.Err??e)(a.issues.map(e=>Pr(e,s,Xr())));throw ur(n,o?.callee??t),n}return a.value};return t},si=e=>{let t=async(n,r,i,o)=>{let s=i?{...i,async:!0}:{async:!0},a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){let n=new(o?.Err??e)(a.issues.map(e=>Pr(e,s,Xr())));throw ur(n,o?.callee??t),n}return a.value};return t},ai=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Hr;return o.issues.length?li(e,o.issues,i):{success:!0,data:o.value}};function li(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>Pr(e,n,Xr()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}var ui=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?li(e,o.issues,i):{success:!0,data:o.value}},ci=Symbol.for("zod.compile.invalid"),di=Symbol.for("zod.compile.fallback"),pi=(e,t,n)=>{let r=e._zod.bag.validator;if(void 0!==r){if(r(t)!==ci)return!0;if(!0===r.definite&&void 0===n)return!1}return function(e,t,n){let r,i=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=e._zod.bag.fallbackRun;o?(i[di]=!0,r=o({value:t,issues:[]},i)):r=e._zod.run({value:t,issues:[]},i);if(r instanceof Promise)throw new Hr;return 0===r.issues.length}(e,t,n)};var hi=/^[cC][0-9a-z]{6,}$/,fi=/^[0-9a-z]+$/,mi=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,gi=/^[0-9a-vA-V]{20}$/,yi=/^[A-Za-z0-9]{27}$/,vi=/^[a-zA-Z0-9_-]{21}$/;var bi=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,wi=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,_i=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ki=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var xi=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Oi=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,$i=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Si=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ei=/^https?$/,zi=/^\+[1-9]\d{6,14}$/,Pi="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";var Ii=new RegExp(`^${Pi}$`);function Ti(e){return"number"==typeof e.precision?-1===e.precision?"(?:[01]\\d|2[0-3]):[0-5]\\d":0===e.precision?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}var Ai=/^[\s\S]{0,}$/,Ni=/^-?\d+(?:\.\d+)?$/,ji=/^(?:true|false)$/i,Ri=/^[^A-Z]*$/,Ci=/^[^a-z]*$/,Mi=Br("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Di=e=>{let t=e.value;return!(n=t,null==n||void 0===t.length);var n},Zi={number:"number",bigint:"bigint",object:"date"},Ui=Br("$ZodCheckLessThan",(e,t)=>{Mi.init(e,t);let n=Zi[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Zi[typeof r.value]??n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Li=Br("$ZodCheckGreaterThan",(e,t)=>{Mi.init(e,t);let n=Zi[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Zi[typeof r.value]??n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Fi=Br("$ZodCheckMultipleOf",(e,t)=>{Mi.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?t.value===BigInt(0)||n.value%t.value!==BigInt(0):0!==function(e,t){let n=e/t,r=Math.round(n),i=4*Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}(n.value,t.value))&&n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Ji=Br("$ZodCheckNumberFormat",(e,t)=>{Mi.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[i,o]=br[t.format];e._zod.check=s=>{let a=s.value;if(n){if(!Number.isInteger(a))return void s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Vi=Br("$ZodCheckMaxLength",(e,t)=>{var n;Mi.init(e,t),(n=e._zod.def).when??(n.when=Di),e._zod.check=n=>{let r=n.value,i=r.length;if(("string"==typeof r&&i>t.maximum?Tr(r):i)<=t.maximum)return;let o=Ar(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),qi=Br("$ZodCheckMinLength",(e,t)=>{var n;Mi.init(e,t),(n=e._zod.def).when??(n.when=Di),e._zod.check=n=>{let r=n.value,i=r.length;if(("string"==typeof r&&i>=t.minimum&&i<2*t.minimum?Tr(r):i)>=t.minimum)return;let o=Ar(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Wi=Br("$ZodCheckLengthEquals",(e,t)=>{var n;Mi.init(e,t),(n=e._zod.def).when??(n.when=Di),e._zod.check=n=>{let r=n.value,i=r.length,o="string"==typeof r&&i>=t.length&&i<=2*t.length?Tr(r):i;if(o===t.length)return;let s=Ar(r),a=o>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Bi=Br("$ZodCheckStringFormat",(e,t)=>{var n,r;Mi.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Hi=Br("$ZodCheckRegex",(e,t)=>{Bi.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ki=Br("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ri),Bi.init(e,t)}),Gi=Br("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ci),Bi.init(e,t)}),Xi=Br("$ZodCheckIncludes",(e,t)=>{Mi.init(e,t);let n=mr(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Yi=Br("$ZodCheckStartsWith",(e,t)=>{Mi.init(e,t);let n=new RegExp(`^${mr(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Qi=Br("$ZodCheckEndsWith",(e,t)=>{Mi.init(e,t);let n=new RegExp(`.*${mr(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),eo=Br("$ZodCheckOverwrite",(e,t)=>{Mi.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class to{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});let t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {\n${t.join("\n")}\n};`)(...Object.values(this.closed))}}var no={major:4,minor:6,patch:5},ro=Br("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=no;let r=e._zod.def.checks,i=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(0===i.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i,o=Or(t);for(let s of n){if(s._zod.def.when){if($r(t))continue;if(!s._zod.def.when(t))continue}else if(o)continue;let n=t.issues.length,a=s._zod.check(t);if(a instanceof Promise&&!1===r?.async)throw new Hr;if(i||a instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await a,t.issues.length!==n&&(zr(t.issues,n,e),o||(o=Or(t,n)))});else{if(t.issues.length===n)continue;zr(t.issues,n,e),o||(o=Or(t,n))}}return i?i.then(()=>t):t},n=(n,r,o)=>{if(Or(n))return n.aborted=!0,n;let s=t(r,i,o);if(s instanceof Promise){if(!1===o.async)throw new Hr;return s.then(t=>e._zod.parse(t,o))}return e._zod.parse(s,o)};e._zod.run=(r,o)=>{if(o.skipChecks)return e._zod.parse(r,o);if("backward"===o.direction){let t=e._zod.parse({value:r.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,o)):n(t,r,o)}let s=e._zod.parse(r,o);if(s instanceof Promise){if(!1===o.async)throw new Hr;return s.then(e=>t(e,i,o))}return t(s,i,o)}}},{get"~standard"(){return Rr(this,"~standard",oo(this))},set"~standard"(e){jr(this,"~standard",e)}}),io=(e,t)=>e.issues.length?{issues:e.issues.map(e=>Pr(e,t,Xr()))}:{value:e.value};function oo(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return io(r,n)}catch(e){}return async function(e,t){let n={async:!0};return io(await e._zod.run({value:t,issues:[]},n),n)}(e,t)},vendor:"zod",version:1}}var so=Br("$ZodString",(e,t)=>{ro.init(e,t),e._zod.pattern=t.pattern??Ai,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),ao=Br("$ZodStringFormat",(e,t)=>{Bi.init(e,t),so.init(e,t)}),lo=Br("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=wi),ao.init(e,t)}),uo=Br("$ZodUUID",(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=_i(e))}else t.pattern??(t.pattern=_i());ao.init(e,t)}),co=Br("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ki),ao.init(e,t)});function po(e){try{return typeof URL<"u"&&"function"==typeof URL.canParse?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function ho(e,t){return"normalize"in t||"hostname"in t||"protocol"in t?function(e,t){if(!t.normalize&&t.protocol?.source===Ei.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<"u"){let t=URL;if("function"==typeof t.parse)return t.parse(e)??2}return new URL(e)}catch{return 2}}(e,t):po(e)||2}var fo=/[\t\n\r]/g;function mo(e){return e.replace(fo,"")}var go=Br("$ZodURL",(e,t)=>{ao.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=ho(r,t);return 1===i?void n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort}):2===i?void n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort}):!0===i?void(n.value=mo(r)):(t.hostname&&!function(e,t){return t.lastIndex=0,t.test(e.hostname)}(i,t.hostname)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!function(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}(i,t.protocol)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),void(n.value=t.normalize?i.href:mo(r)))}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),yo=Br("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$","u")),ao.init(e,t)}),vo=Br("$ZodNanoID",(e,t)=>{if(void 0!==t.length&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);var n;t.pattern??(t.pattern=void 0===t.length?vi:(n=t.length,new RegExp(`^[a-zA-Z0-9_-]{${n}}$`))),ao.init(e,t)}),bo=Br("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=hi),ao.init(e,t)}),wo=Br("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=fi),ao.init(e,t)}),_o=Br("$ZodULID",(e,t)=>{t.pattern??(t.pattern=mi),ao.init(e,t)}),ko=Br("$ZodXID",(e,t)=>{t.pattern??(t.pattern=gi),ao.init(e,t)}),xo=Br("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=yi),ao.init(e,t)}),Oo=Br("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){let t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${Ti({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${Ti({precision:e.precision})}`:n;return new RegExp(`^${Pi}T(?:${r})$`)}(t)),ao.init(e,t)}),$o=Br("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Ii),ao.init(e,t)}),So=Br("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${Ti(t)}$`)),ao.init(e,t)}),Eo=Br("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=bi),ao.init(e,t)}),zo=Br("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=xi),ao.init(e,t)}),Po=/^[0-9a-fA-F:.]+$/;function Io(e){return!!Po.test(e)&&po(`http://[${e}]`)}var To=Br("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Oi),ao.init(e,t),e._zod.check=n=>{Io(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),Ao=Br("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=$i),ao.init(e,t)});var No=Br("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Si),ao.init(e,t),e._zod.check=n=>{(function(e){let t=e.split("/");if(2!==t.length)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`===r&&!(i<0||i>128)&&Io(n)})(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function jo(e){if(""===e)return!0;if(/\s/.test(e))return!1;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var Ro=/^[0-9a-zA-Z+/]*={0,2}$/,Co=Br("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ro),ao.init(e,t),e._zod.check=n=>{jo(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Mo=/^[A-Za-z0-9_-]*$/;var Do=Br("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Mo),ao.init(e,t),e._zod.check=n=>{(function(e){if(!Mo.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return jo(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Zo=Br("$ZodE164",(e,t)=>{t.pattern??(t.pattern=zi),ao.init(e,t)});var Uo=Br("$ZodJWT",(e,t)=>{ao.init(e,t),e._zod.check=n=>{(function(e,t=null){try{let n=e.split(".");if(3!==n.length)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!("typ"in i&&"JWT"!==i?.typ||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Lo=Br("$ZodNumber",(e,t)=>{ro.init(e,t),e._zod.pattern=Ni,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}let i=n.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return n;let o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}}),Fo=Br("$ZodNumberFormat",(e,t)=>{Ji.init(e,t),Lo.init(e,t)}),Jo=Br("$ZodBoolean",(e,t)=>{ro.init(e,t),e._zod.pattern=ji,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(e){}let i=n.value;return"boolean"==typeof i||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),Vo=Br("$ZodUnknown",(e,t)=>{ro.init(e,t),e._zod.parse=e=>e}),qo=Br("$ZodNever",(e,t)=>{ro.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Wo(e,t,n){e.issues.length&&t.issues.push(...Sr(n,e.issues)),t.value[n]=e.value}var Bo=Br("$ZodArray",(e,t)=>{ro.init(e,t);let n=Gr.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=n?n.alloc(e,r,Array(o.length),i):Array(o.length);let s=[],a=i?.abortEarly;for(let e=0;e<o.length;e++){let n=o[e],l=t.element._zod.run({value:n,issues:[]},i);if(l instanceof Promise)s.push(l.then(t=>Wo(t,r,e)));else if(Wo(l,r,e),a&&0!==l.issues.length&&Or(l))break}return s.length?Promise.all(s).then(()=>r):r}});function Ho(e,t,n,r,i,o){let s=n in r,a="optional"===o;if(s||!a||"optional"!==i){if(e.issues.length){if(void 0!==i&&a&&!s)return;t.issues.push(...Sr(n,e.issues))}s||void 0!==i?void 0===e.value?(s||"defaulted"===i&&!a)&&(t.value[n]=void 0):t.value[n]=e.value:e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]})}}var Ko=[];function Go(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Ko,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let o=(s=e.shape,Object.keys(s).filter(e=>void 0!==s[e]._zod.optin&&"optional"===s[e]._zod.optout));var s;return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function Xo(e,t,n,r,i,o,s){let a=[],l=i.keySet,u=i.catchall._zod,c=u.def.type,{optin:d,optout:p}=u,h=0;for(let i in t){if(s&&n.issues.length!==h){if(Or(n,h))break;h=n.issues.length}if(l.has(i))continue;if("__proto__"===i){"never"===c&&a.push(i);continue}if("never"===c){a.push(i);continue}let o=u.run({value:t[i],issues:[]},r);o instanceof Promise?e.push(o.then(e=>Ho(e,n,i,t,d,p))):Ho(o,n,i,t,d,p)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:o,continue:!0}),e.length?Promise.all(e).then(()=>n):n}var Yo=Br("$ZodObject",(e,t)=>{ro.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape"),r=n?.get?n.get.raw:t.shape??{};if(r){let e=()=>{let n={...r};return Object.defineProperty(t,"shape",{value:n}),e.raw=n,n};e.raw=r,Object.defineProperty(t,"shape",{get:e})}let i=Qn(()=>Go(t));Lr(e,"propValues",e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||tr(n,e,new Set);for(let t of r.values)n[e].add(t);void 0!==r.optin&&n[e].add(void 0)}}return n});let o,s=cr,a=t.catchall,l=Gr.memoizer;l?.attach(e),e._zod.parse=(t,n)=>{o??(o=i.value);let r=t.value;if(!s(r))return t.issues.push({expected:"object",code:"invalid_type",input:r,inst:e}),t;t.value=l?l.alloc(e,t,{},n):{};let u=[],c=o.shape,d=n?.abortEarly,p=t.issues.length;for(let e of o.allKeys){if(d&&t.issues.length!==p){if(Or(t,p))break;p=t.issues.length}if("__proto__"===e)continue;let i=c[e],o=i._zod.optin,s=i._zod.optout,a=i._zod.run({value:r[e],issues:[]},n);a instanceof Promise?u.push(a.then(n=>Ho(n,t,e,r,o,s))):Ho(a,t,e,r,o,s)}return a?Xo(u,r,t,n,i.value,e,!0===d):u.length?Promise.all(u).then(()=>t):t}}),Qo=Br("$ZodObjectJIT",(e,t)=>{Yo.init(e,t);let n,r,i=e._zod.parse,o=Qn(()=>Go(t)),s=Gr.memoizer,a=cr,l=!Gr.jitless,u=l&&dr.value,c=t.catchall;e._zod.parse=(d,p)=>{r??(r=o.value);let h=d.value;return a(h)?l&&u&&!1===p?.async&&!0!==p.jitless?(n||(n=(t=>{let n=o.value,r=n.symbolKeys,i=new to(["payload","ctx"],{shape:t,inst:e,memo:s,syms:r}),a=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,l=(e,t)=>`\n let ${e}_ab = false;\n for (let i = 0; i < ${e}.issues.length; i++) {\n const iss = ${e}.issues[i];\n iss.path = iss.path ? [${t}, ...iss.path] : [${t}];\n payload.issues.push(iss);\n if (iss.continue !== true) ${e}_ab = true;\n }\n if (${e}_ab && ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }`;i.write("const input = payload.value;");let u=Object.create(null),c=0;for(let e of n.allKeys)u[e]="key_"+c++;i.write(s?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let e of n.allKeys){if("__proto__"===e)continue;let n=u[e],o="symbol"==typeof e?`syms[${r.indexOf(e)}]`:lr(e),s=`${o} in input`,c=t[e],d=c?._zod?.optin,p=void 0!==d,h="optional"===c?._zod?.optout;if(i.write(`const ${n} = ${a(o)};`),p&&h){let e="optional"===d?`${n}_present`:`${n}.value !== undefined || ${n}_present`;i.write(`\n const ${n}_present = ${s};\n if (!${n}.issues.length || ${n}_present) {\n if (${n}.issues.length) {${l(n,o)}\n }\n\n if (${e}) {\n newResult[${o}] = ${n}.value;\n }\n }\n\n `)}else p?(i.write(`\n if (${n}.issues.length) {${l(n,o)}\n }\n `),"defaulted"===d?i.write(`newResult[${o}] = ${n}.value;`):i.write(`\n if (${n}.value !== undefined || ${s}) {\n newResult[${o}] = ${n}.value;\n }\n `)):i.write(`\n const ${n}_present = ${s};\n if (${n}.issues.length) {${l(n,o)}\n }\n if (!${n}_present && !${n}.issues.length) {\n payload.issues.push({\n code: "invalid_type",\n expected: "nonoptional",\n input: undefined,\n path: [${o}]\n });\n if (ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }\n }\n\n if (${n}_present) {\n newResult[${o}] = ${n}.value;\n }\n\n `)}return i.write("payload.value = newResult;"),i.write("return payload;"),i.compile()})(t.shape)),d=n(d,p),c?Xo([],h,d,p,r,e,!0===p?.abortEarly):d):i(d,p):(d.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),d)}});function es(e,t,n,r){for(let n of e)if(0===n.issues.length)return t.value=n.value,t;let i=e.filter(e=>!Or(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Pr(e,r,Xr())))}),t)}var ts=Br("$ZodUnion",(e,t)=>{ro.init(e,t),Lr(e,"optin",e=>e.def.options.some(e=>"defaulted"===e._zod.optin)?"defaulted":e.def.options.some(e=>void 0!==e._zod.optin)?"optional":void 0),Lr(e,"optout",e=>e.def.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Lr(e,"values",e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),Lr(e,"pattern",e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return new RegExp(`^(${t.map(e=>er(e.source)).join("|")})$`)}});let n=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let o=!1,s=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)s.push(t),o=!0;else{if(0===t.issues.length)return t;s.push(t)}}return o?Promise.all(s).then(t=>es(t,r,e,i)):es(s,r,e,i)}}),ns=Br("$ZodIntersection",(e,t)=>{ro.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),o=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([t,n])=>is(e,t,n)):is(e,i,o)}});function rs(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(pr(e)&&pr(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),i={...e,...t};Object.prototype.hasOwnProperty.call(i,"__proto__")&&delete i.__proto__;for(let n of r){if("__proto__"===n)continue;let r=rs(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=rs(e[r],t[r]);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function is(e,t,n){let r,i=new Map,o=new Map,s=(e,t)=>{let n;if("unrecognized_keys"!==e.code||e.path?.length){if("invalid_key"!==e.code||"record"!==e.origin||1!==e.path?.length)return!1;{let t=String(e.path[0]);o.has(t)||o.set(t,e),n=[t]}}else r??(r=e),n=e.keys;for(let e of n)i.has(e)||i.set(e,{}),i.get(e)[t]=!0;return!0};for(let n of t.issues)s(n,"l")||e.issues.push(n);for(let t of n.issues)s(t,"r")||e.issues.push(t);let a=[...i].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length){let t=r?a.filter(e=>r.keys.includes(e)):[];t.length&&e.issues.push({...r,keys:t});for(let n of a)!t.includes(n)&&o.has(n)&&e.issues.push(o.get(n))}let l=rs(t.value,n.value);if(!l.valid){if(Or(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(l.mergeErrorPath)}`)}return e.value=l.data,e}var os=Br("$ZodEnum",(e,t)=>{ro.init(e,t);let n=Kn(t.entries),r=new Set(n);e._zod.values=r,Lr(e,"pattern",e=>{let t=Kn(e.def.entries).filter(e=>fr.has(typeof e));return new RegExp(t.length?`^(${t.map(e=>mr(e.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(t,i)=>{let o=t.value;return r.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}}),ss=Br("$ZodLiteral",(e,t)=>{ro.init(e,t);let n=new Set(t.values);e._zod.values=n,Lr(e,"pattern",e=>{let t=e.def.values;return new RegExp(t.length?`^(${t.map(e=>"string"==typeof e?mr(e):e?mr(e.toString()):String(e)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,i)=>{let o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),as=Br("$ZodTransform",(e,t)=>{ro.init(e,t),e._zod.optin="optional",Gr.memoizer?.guard(e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new Kr(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new Hr;return n.value=i,n}});function ls(e,t){return e.value=t.issues.length?void 0:t.value,e}var us=Br("$ZodOptional",(e,t)=>{ro.init(e,t),Lr(e,"optin",e=>"defaulted"===e.def.innerType._zod.optin?"defaulted":"optional"),e._zod.optout="optional",Lr(e,"values",e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),Lr(e,"pattern",e=>{let t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${er(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(void 0===e.value){if("defaulted"!==t.innerType._zod.optin)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>ls(e,t)):ls(e,r)}return t.innerType._zod.run(e,n)}}),cs=Br("$ZodExactOptional",(e,t)=>{us.init(e,t),Lr(e,"values",e=>e.def.innerType._zod.values),Lr(e,"pattern",e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),ds=Br("$ZodNullable",(e,t)=>{ro.init(e,t),Lr(e,"optin",e=>e.def.innerType._zod.optin),Lr(e,"optout",e=>e.def.innerType._zod.optout),Lr(e,"pattern",e=>{let t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${er(t.source)}|null)$`):void 0}),Lr(e,"values",e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),ps=Br("$ZodDefault",(e,t)=>{ro.init(e,t),e._zod.optin="defaulted",Lr(e,"values",e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>hs(e,t)):hs(r,t)}});function hs(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var fs=Br("$ZodPrefault",(e,t)=>{ro.init(e,t),e._zod.optin="defaulted",Lr(e,"values",e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),ms=Br("$ZodNonOptional",(e,t)=>{ro.init(e,t),Lr(e,"values",e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>gs(t,e)):gs(i,e)}});function gs(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function ys(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>Pr(e,r,Xr()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var vs=Br("$ZodCatch",(e,t)=>{ro.init(e,t),Lr(e,"optin",e=>"defaulted"===e.def.innerType._zod.optin?"defaulted":"optional"),Lr(e,"optout",e=>e.def.innerType._zod.optout),Lr(e,"values",e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>ys(e,r,t,n)):ys(e,r,t,n)}}),bs=Br("$ZodPipe",(e,t)=>{ro.init(e,t),Lr(e,"values",e=>e.def.in._zod.values),Lr(e,"optin",e=>e.def.in._zod.optin),Lr(e,"optout",e=>e.def.out._zod.optout),Lr(e,"propValues",e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>ws(e,t.in,n)):ws(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>ws(e,t.out,n)):ws(r,t.out,n)}});function ws(e,t,n){return e.issues.some(e=>"unrecognized_keys"!==e.code)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var _s=Br("$ZodReadonly",(e,t)=>{ro.init(e,t),Lr(e,"propValues",e=>e.def.innerType._zod.propValues),Lr(e,"values",e=>e.def.innerType._zod.values),Lr(e,"optin",e=>e.def.innerType?._zod?.optin),Lr(e,"optout",e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(ks):ks(r)}});function ks(e){return e.memo||(e.value=Object.freeze(e.value)),e}var xs=Br("$ZodCustom",(e,t)=>{Mi.init(e,t),ro.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Os(t,n,r,e));Os(i,n,r,e)}});function Os(e,t,n,r){if(!e){let e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Nr(e))}}class $s extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}var Ss="~memo",Es=[];function zs(e){return null!==e&&"object"==typeof e}function Ps(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var Is=new WeakMap;function Ts(e,t,n){let r=Is.get(e);if(void 0!==r)return r?2:0;if(t.has(e))return 2;t.add(e);let i=0,o=e=>{if(2!==i&&e?._zod){let r=Ts(e,t,n);r>i&&(i=r)}},s=e=>{e>i&&(i=e)},a=e._zod.def;switch(a.type){case"object":{let e=nr(a);s(e?((e,r)=>{let i=0;for(let o of Reflect.ownKeys(e)){let s=Object.getOwnPropertyDescriptor(e,o);if(r&&!s.enumerable)continue;let a=s.get?1:s.value?._zod?Ts(s.value,t,n):0;a>i&&(i=a)}return i})(e,!0):1),o(a.catchall);break}case"array":o(a.element);break;case"tuple":for(let e of a.items)o(e);o(a.rest);break;case"record":case"map":o(a.keyType),o(a.valueType);break;case"set":o(a.valueType);break;case"union":for(let e of a.options)o(e);break;case"intersection":o(a.left),o(a.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":o(a.innerType);break;case"pipe":o(a.in),o(a.out);break;case"function":o(a.input),o(a.output);break;case"lazy":{let r=a._cachedInner??(n?e._zod.innerType:void 0);s(r?Ts(r,t,!1):1);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let e in a){let t=Object.getOwnPropertyDescriptor(a,e);if(!t||t.get)continue;let n=t.value;if(n&&"object"==typeof n)if(n._zod)o(n);else if(Array.isArray(n))for(let e of n)o(e)}}return t.delete(e),function(e,t){1!==t&&Is.set(e,2===t);return t}(e,i)}var As,Ns=[],js={alloc(e,t,n){let r=As;if(!r)return n;As=void 0;let i={value:n,issues:null};return r.set(t.value,i),Ns.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if("backward"!==n.direction&&function(e,t){let n=e[Ss]?.backEdges;return void 0!==n&&zs(t)&&n.has(t)}(n,e.value))throw new $s;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r,i,o=!1;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,s=(a,l)=>{if(void 0===n){let r=Ts(e,new Set,!1);if(0===r)return e._zod.parse=t,e._zod.run===s&&(e._zod.run=t),t(a,l);2===r||o?n=!0:o=!0}let u=a.value;if(!zs(u))return t(a,l);let c,d=l[Ss];d||(d={buckets:new WeakMap,backEdges:void 0},l[Ss]=d),r===l?c=i:(c=function(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}(d,e),r=l,i=c);let p=c.get(u);if(p)return a.value=p.value,p.issues?p.issues.length&&a.issues.push(...Ps(p.issues)):(a.memo=!0,d.backEdges??(d.backEdges=new WeakSet),d.backEdges.add(p.value)),a;As=c;let h=Ns.length,f=t(a,l);As=void 0;let m=Ns.length>h?Ns.pop():void 0;return f instanceof Promise?f.then(e=>(m&&(m.issues=e.issues.length?Ps(e.issues):Es),e)):(m&&(m.issues=f.issues.length?Ps(f.issues):Es),f)};e._zod.parse=s,e._zod.run===t&&(e._zod.run=s)})}};var Rs,Cs=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(t){return e[t]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function i(e,t){return"number"!==e||"number"!=typeof t||Number.isFinite(t)?r[e]??e:String(t)}return e=>{switch(e.code){case"invalid_type":return`Invalid input: expected ${i(e.expected)}, received ${i(function(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(null===e)return"null";if(Array.isArray(e))return"array";let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&"constructor"in t&&t.constructor)return t.constructor.name}}return t}(e.input),e.input)}`;case"invalid_value":return 1===e.values.length?`Invalid input: expected ${vr(e.values[0])}`:`Invalid option: expected one of ${Gn(e.values,"|")}`;case"too_big":{let n=e.exact?"exactly ":e.inclusive?"<=":"<",r=t(e.origin);return r?`Too big: expected ${e.origin??"value"} to have ${n}${e.maximum.toString()} ${r.unit??"elements"}`:`Too big: expected ${e.origin??"value"} to be ${n}${e.maximum.toString()}`}case"too_small":{let n=e.exact?"exactly ":e.inclusive?">=":">",r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case"invalid_format":{let t=e;return"starts_with"===t.format?`Invalid string: must start with "${t.prefix}"`:"ends_with"===t.format?`Invalid string: must end with "${t.suffix}"`:"includes"===t.format?`Invalid string: must include "${t.includes}"`:"regex"===t.format?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${e.divisor}`;case"unrecognized_keys":return`Unrecognized key${e.keys.length>1?"s":""}: ${Gn(e.keys,", ")}`;case"invalid_key":return`Invalid key in ${e.origin}`;case"invalid_union":return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(" | ")}`:!1===e.inclusive?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${e.origin}`;default:return"Invalid input"}}};class Ms{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}(Rs=globalThis).__zod_globalRegistry??(Rs.__zod_globalRegistry=new Ms);var Ds=globalThis.__zod_globalRegistry;function Zs(e){return e.checks&&(e.checks=[...e.checks]),e}function Us(e,t){return new Ui({check:"less_than",...yr(t),value:e,inclusive:!1})}function Ls(e,t){return new Ui({check:"less_than",...yr(t),value:e,inclusive:!0})}function Fs(e,t){return new Li({check:"greater_than",...yr(t),value:e,inclusive:!1})}function Js(e,t){return new Li({check:"greater_than",...yr(t),value:e,inclusive:!0})}function Vs(e,t){return new Fi({check:"multiple_of",...yr(t),value:e})}function qs(e,t){return new Vi({check:"max_length",...yr(t),maximum:e})}function Ws(e,t){return new qi({check:"min_length",...yr(t),minimum:e})}function Bs(e,t){return new Wi({check:"length_equals",...yr(t),length:e})}function Hs(e){return new eo({check:"overwrite",tx:e})}function Ks(e,t){let n=function(e,t){let n=new Mi({check:"custom",...yr(t)});return n._zod.check=e,n}(t=>(t.addIssue=e=>{if("string"==typeof e)t.issues.push(Nr(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),"input"in r||(r.input=t.value),r.inst??(r.inst=n),r.continue??(r.continue=!n._zod.def.abort),t.issues.push(Nr(r))}},e(t.value,t)),t);return n}function Gs(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&tr(e,t,n[t]);return e}function Xs(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Ds,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function Ys(e,t,n,r,i){let o="function"==typeof t.unrepresentable?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if("any"===o)return!1;if(void 0===o||"throw"===o)throw Error(i);return Object.assign(n,o),!0}function Qs(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;let s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,r);else{let n=s.schema,o=t.processors[i.type];if(!o)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);o(e,t,n,r)}let o=e._zod.parent;o&&(s.ref||(s.ref=o),Qs(o,t,r),t.seen.get(o).isParent=!0)}let l=t.metadataRegistry.get(e);return l&&Gs(s.schema,l),"input"===t.io&&ua(e)&&(delete s.schema.examples,delete s.schema.default),"input"===t.io&&"_prefault"in s.schema&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function ea(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function ta(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{if(t[1].schema.$ref)return;let r=t[1],{ref:i,defId:o}=(t=>{let r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let o=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=o,{defId:o,ref:`${i("__shared")}#/${r}/${ea(o)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:"#"};let o=t[1].schema.id??"__schema"+e.counter++;return{defId:o,ref:i+ea(o)}})(t);r.def={...r.schema},o&&(r.defId=o);let s=r.schema;for(let e in s)delete s[e];s.$ref=i};if("throw"===e.cycles)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t!==n[0]){if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){i(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&"ref"===e.reused)&&i(n)}else i(n)}e.external&&(e.sharedDefsExtractedFor=e.external)}function na(e){let t=e.anyOf;if(!Array.isArray(t)||0===t.length||void 0!==e.type)return;let n=[];for(let e of t){if(!e||"object"!=typeof e)return;na(e);let t=Object.keys(e);if(1!==t.length||"type"!==t[0])return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if("string"!=typeof e)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=1===n.length?n[0]:n}var ra=new Set(["type","properties","required","additionalProperties"]),ia=["oneOf","anyOf"];function oa(e){let t=e.additionalProperties;return void 0===t||!1===t||"object"!=typeof t||null===t?null:Object.keys(t).length?t:null}function sa(e){let t=[];for(let n of e){if("object"!=typeof n||"object"!==n.type)return null;for(let e in n)if(!ra.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??oa(n);null!=t&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}tr(n,r,1===e.length?e[0]:sa(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:"object",properties:n};if(r.size&&(i.required=[...r]),t.every(e=>!1===e.additionalProperties))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=oa(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}1===e.length?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function aa(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of ra)if(t in e)return;let n=t.filter(e=>ia.some(t=>Array.isArray(e[t]))),r=null;if(n.length){let e=n[0],i=ia.find(t=>Array.isArray(e[t]));if(1!==Object.keys(e).length)return;let o=t.filter(t=>t!==e),s=e[i].map(e=>sa([...o,e]));if(s.some(e=>!e))return;r={[i]:s}}else r=sa(t);r&&(delete e.allOf,Gs(e,r))}function la(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=t=>{let n=e.seen.get(t);if(null===n.ref)return;let i=n.def??n.schema,o={...i},s=n.ref;if(n.ref=null,s){r(s);let n=e.seen.get(s),a=n.schema;if(!a.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Gs(i,a):(i.allOf=i.allOf??[],i.allOf.push(a)),Gs(i,o),t._zod.parent===s)for(let e in i)"$ref"!==e&&"allOf"!==e&&(e in o||delete i[e]);if(a.$ref&&n.def)for(let e in i)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let a=t._zod.parent;if(a&&a!==s){r(a);let t=e.seen.get(a);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if("openapi-3.0"!==e.target)for(let t of e.seen.entries())na(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])aa(e)}}let i={};if("draft-2020-12"===e.target?i.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?i.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Gs(i,n.defId?n.schema:n.def??n.schema);let o=e.metadataRegistry.get(t)?.id;void 0!==o&&i.id===o&&delete i.id;let s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,tr(s,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(s).length>0&&("draft-2020-12"===e.target?i.$defs=s:i.definitions=s);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:ca(t,"input",e.processors),output:ca(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw Error("Error converting schema to JSON.")}}function ua(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return ua(r.element,n);if("set"===r.type)return ua(r.valueType,n);if("lazy"===r.type)return ua(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type||"catch"===r.type)return ua(r.innerType,n);if("intersection"===r.type)return ua(r.left,n)||ua(r.right,n);if("record"===r.type||"map"===r.type)return ua(r.keyType,n)||ua(r.valueType,n);if("pipe"===r.type)return!!e._zod.traits.has("$ZodCodec")||(ua(r.in,n)||ua(r.out,n));if("object"===r.type){for(let e in r.shape)if(ua(r.shape[e],n))return!0;return!1}if("union"===r.type){for(let e of r.options)if(ua(e,n))return!0;return!1}if("tuple"===r.type){for(let e of r.items)if(ua(e,n))return!0;return!(!r.rest||!ua(r.rest,n))}return!1}var ca=(e,t,n={})=>r=>{let{libraryOptions:i,target:o}=r??{},s=Xs({...i??{},target:o,io:t,processors:n});return Qs(e,s),ta(s,e),la(s,e)},da=(e,t,n)=>{(void 0===e[t]||n>e[t])&&(e[t]=n)},pa=(e,t,n)=>{(void 0===e[t]||n<e[t])&&(e[t]=n)},ha=(e,t)=>{da(e,"minimum",t),pa(e,"maximum",t)},fa=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},ma=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},ga=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},ya=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},va=(e,t)=>da(e,"minimum",t.minimum),ba=(e,t)=>pa(e,"maximum",t.maximum),wa=e=>(t,n)=>{ya(t,n.format);let[r,i]=e[n.format];da(t,"minimum",r),pa(t,"maximum",i)},_a={greater_than:(e,t)=>da(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>pa(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>fa(e,t.value),number_format:wa(br),bigint_format:wa(wr),min_length:va,max_length:ba,length_equals:(e,t)=>ha(e,t.length),min_size:va,max_size:ba,size_equals:(e,t)=>ha(e,t.size),string_format:(e,t)=>{ya(e,t.format),t.pattern&&ma(e,t.pattern),"base64"!==t.format&&"base64url"!==t.format||(e.contentEncoding=t.format),(t.local||-1===t.precision)&&(e.laxFormat=!0)},mime_type:(e,t)=>ga(e,t.mime)};function ka(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let e of r)_a[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;void 0!==i.minimum&&da(t,"minimum",i.minimum),void 0!==i.exclusiveMinimum&&da(t,"exclusiveMinimum",i.exclusiveMinimum),void 0!==i.maximum&&pa(t,"maximum",i.maximum),void 0!==i.exclusiveMaximum&&pa(t,"exclusiveMaximum",i.exclusiveMaximum),void 0!==i.multipleOf&&fa(t,i.multipleOf),void 0!==i.format&&(t.format??(t.format=i.format),i.format.includes("int")&&(t.isInt=!0)),i.mime&&ga(t,i.mime);for(let e of i.patterns??[])ma(t,e);return t}var xa={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Oa=new Map([[Ro,/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/],[Mo,/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/]]),$a=e=>Oa.get(e)??e;function Sa(e){let t=e._zod.def;return"pipe"===t.type&&t.in._zod.traits.has("$ZodTransform")?Sa(t.out):"catch"===t.type?Sa(t.innerType):e._zod.optin}var Ea=Symbol();function za(e,t,n,r,i){let o=!1,s=JSON.stringify(e,(e,t)=>"bigint"!=typeof t?t:(o=!0,null));return o?(Ys(t,n,r,i,"BigInt defaults cannot be represented in JSON Schema"),Ea):JSON.parse(s)}var Pa=(e,t,n,r)=>{let i=e._zod.def;Qs(i.innerType,t,r),t.seen.get(e).ref=i.innerType},Ia=new WeakSet([Object.prototype,Error.prototype]);function Ta(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var Aa,Na=Br("ZodError",(e,t)=>{ni.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);Ia.has(n)||(Ia.add(n),Ta(n,"format",e=>t=>function(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let o of e.issues)if("invalid_union"===o.code&&o.errors.length)o.errors.map(e=>r({issues:e},[...i,...o.path]));else if("invalid_key"===o.code)r({issues:o.issues},[...i,...o.path]);else if("invalid_element"===o.code)r({issues:o.issues},[...i,...o.path]);else{let e=[...i,...o.path];if(0===e.length)n._errors.push(t(o));else{let r=n,i=0;for(;i<e.length;){let n=e[i],s=i===e.length-1;if("_errors"===n){s&&r._errors.push(t(o)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let a=r[n];s&&a._errors.push(t(o)),r=a,i++}}}};return r(e),n}(e,t)),Ta(n,"flatten",e=>t=>function(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?ri(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}(e,t)),Ta(n,"addIssue",e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Xn,2)}),Ta(n,"addIssues",e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Xn,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return 0===this.issues.length}}))},void 0,{Parent:Error}),ja=oi(Na),Ra=si(Na),Ca=ai(Na),Ma=ui(Na),Da=(e=>{let t=oi(e),n=(e,r,i,o)=>{let s=i?{...i,direction:"backward"}:{direction:"backward"};return t(e,r,s,ii(n,o))};return n})(Na),Za=(e=>{let t=oi(e),n=(e,r,i,o)=>t(e,r,i,ii(n,o));return n})(Na),Ua=(e=>{let t=si(e),n=async(e,r,i,o)=>{let s=i?{...i,direction:"backward"}:{direction:"backward"};return await t(e,r,s,ii(n,o))};return n})(Na),La=(e=>{let t=si(e),n=async(e,r,i,o)=>await t(e,r,i,ii(n,o));return n})(Na),Fa=(Aa=Na,(e,t,n)=>{let r=n?{...n,direction:"backward"}:{direction:"backward"};return ai(Aa)(e,t,r)}),Ja=(e=>(t,n,r)=>ai(e)(t,n,r))(Na),Va=(e=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return ui(e)(t,n,i)})(Na),qa=(e=>async(t,n,r)=>ui(e)(t,n,r))(Na);function Wa(){Gr.localeError||Xr({localeError:Cs()})}function Ba(){Gr.memoizer||Xr({memoizer:js})}var Ha=Br("ZodType",(e,t)=>(Wa(),ro.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(ar(t,{checks:[...t.checks??[],...e.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return gr(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(function(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...yr(n)})}(eu,e,t)}(e,t))},superRefine(e,t){return this.check(function(e,t){return Ks(e,t)}(e,t))},overwrite(e){return this.check(Hs(e))},optional(){return Jl(this)},exactOptional(){return new Vl({type:"optional",innerType:this})},nullable(){return Wl(this)},nullish(){return Jl(Wl(this))},nonoptional(e){return function(e,t){return new Kl({type:"nonoptional",innerType:e,...yr(t)})}(this,e)},array(){return Al(this)},or(e){return Cl([this,e])},and(e){return new Ml({type:"intersection",left:this,right:e})},transform(e){return Yl(this,new Ll({type:"transform",transform:e}))},default(e){return t=e,new Bl({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():hr(t)}});var t},prefault(e){return t=e,new Hl({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():hr(t)}});var t},catch(e){return new Gl({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:Vr(t)});var t},pipe(e){return Yl(this,e)},readonly(){return new Ql({type:"readonly",innerType:this})},describe(e){let t=this.clone();return Ds.add(t,{description:e}),t},meta(...e){if(0===e.length)return Ds.get(this);let t=this.clone();return Ds.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return 0===t.length?e(this):e(this,...t)},get"~standard"(){return Rr(this,"~standard",{...oo(this),jsonSchema:{input:ca(this,"input"),output:ca(this,"output")}})},set"~standard"(e){jr(this,"~standard",e)},parse:function e(t,n){return ja(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Ra(this,t,n,{callee:e})},safeParse(e,t){return Ca(this,e,t)},async safeParseAsync(e,t){return Ma(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){jr(this,"spa",e)},validate(e,t){return pi(this,e,t)},validateAsync(e,t){return(async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),0===i.issues.length})(this,e,t)},encode:function e(t,n){return Da(this,t,n,{callee:e})},decode:function e(t,n){return Za(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Ua(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await La(this,t,n,{callee:e})},safeEncode(e,t){return Fa(this,e,t)},safeDecode(e,t){return Ja(this,e,t)},async safeEncodeAsync(e,t){return Va(this,e,t)},async safeDecodeAsync(e,t){return qa(this,e,t)},toJSONSchema(e){return((e,t={})=>n=>{let r=Xs({...n,processors:t});return Qs(e,r),ta(r,e),la(r,e)})(this,{})(e)},get description(){return Ds.get(this)?.description},get _def(){return this._zod.def}}),Ka=Br("_ZodString",(e,t)=>{so.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{let r=n;r.type="string";let{minimum:i,maximum:o,format:s,patterns:a,contentEncoding:l,laxFormat:u}=ka(e);if("number"==typeof i&&(r.minLength=i),"number"==typeof o&&(r.maxLength=o),s&&(r.format=xa[s]??s,""===r.format&&delete r.format,("time"===s||u)&&delete r.format),l&&(r.contentEncoding=l),a&&a.size>0){let e=[...a].map($a);1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n)},Cr({format:e=>ka(e).format??null,minLength:e=>ka(e).minimum??null,maxLength:e=>ka(e).maximum??null},{regex(...e){return this.check(function(e,t){return new Hi({check:"string_format",format:"regex",...yr(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new Xi({check:"string_format",format:"includes",...yr(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new Yi({check:"string_format",format:"starts_with",...yr(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new Qi({check:"string_format",format:"ends_with",...yr(t),suffix:e})}(...e))},min(...e){return this.check(Ws(...e))},max(...e){return this.check(qs(...e))},length(...e){return this.check(Bs(...e))},nonempty(...e){return this.check(Ws(1,...e))},lowercase(e){return this.check(function(e){return new Ki({check:"string_format",format:"lowercase",...yr(e)})}(e))},uppercase(e){return this.check(function(e){return new Gi({check:"string_format",format:"uppercase",...yr(e)})}(e))},trim(){return this.check(Hs(e=>e.trim()))},normalize(...e){return this.check(function(e){return Hs(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(Hs(e=>e.toLowerCase()))},toUpperCase(){return this.check(Hs(e=>e.toUpperCase()))},slugify(){return this.check(Hs(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}})),Ga=Br("ZodString",(e,t)=>{so.init(e,t),Ka.init(e,t)},{email(e){return this.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...yr(t)})}(rl,e))},url(e){return this.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...yr(t)})}(sl,e))},jwt(e){return this.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...yr(t)})}(_l,e))},emoji(e){return this.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...yr(t)})}(al,e))},guid(e){return this.check(function(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...yr(t)})}(il,e))},uuid(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...yr(t)})}(ol,e))},uuidv4(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...yr(t)})}(ol,e))},uuidv6(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...yr(t)})}(ol,e))},uuidv7(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...yr(t)})}(ol,e))},nanoid(e){return this.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...yr(t)})}(ll,e))},cuid(e){return this.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...yr(t)})}(ul,e))},cuid2(e){return this.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...yr(t)})}(cl,e))},ulid(e){return this.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...yr(t)})}(dl,e))},base64(e){return this.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...yr(t)})}(vl,e))},base64url(e){return this.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...yr(t)})}(bl,e))},xid(e){return this.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...yr(t)})}(pl,e))},ksuid(e){return this.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...yr(t)})}(hl,e))},ipv4(e){return this.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...yr(t)})}(fl,e))},ipv6(e){return this.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...yr(t)})}(ml,e))},cidrv4(e){return this.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...yr(t)})}(gl,e))},cidrv6(e){return this.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...yr(t)})}(yl,e))},e164(e){return this.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...yr(t)})}(wl,e))},datetime(e){return this.check(function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...yr(t)})}(Qa,e))},date(e){return this.check(function(e,t){return new e({type:"string",format:"date",check:"string_format",...yr(t)})}(el,e))},time(e){return this.check(function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...yr(t)})}(tl,e))},duration(e){return this.check(function(e,t){return new e({type:"string",format:"duration",check:"string_format",...yr(t)})}(nl,e))}});function Xa(e){return function(e,t){return new e(Zs({type:"string",...yr(t)}))}(Ga,e)}var Ya=Br("ZodStringFormat",(e,t)=>{ao.init(e,t),Ka.init(e,t)}),Qa=Br("ZodISODateTime",(e,t)=>{Oo.init(e,t),Ya.init(e,t)}),el=Br("ZodISODate",(e,t)=>{$o.init(e,t),Ya.init(e,t)}),tl=Br("ZodISOTime",(e,t)=>{So.init(e,t),Ya.init(e,t)}),nl=Br("ZodISODuration",(e,t)=>{Eo.init(e,t),Ya.init(e,t)}),rl=Br("ZodEmail",(e,t)=>{co.init(e,t),Ya.init(e,t)}),il=Br("ZodGUID",(e,t)=>{lo.init(e,t),Ya.init(e,t)}),ol=Br("ZodUUID",(e,t)=>{uo.init(e,t),Ya.init(e,t)}),sl=Br("ZodURL",(e,t)=>{go.init(e,t),Ya.init(e,t)}),al=Br("ZodEmoji",(e,t)=>{yo.init(e,t),Ya.init(e,t)}),ll=Br("ZodNanoID",(e,t)=>{vo.init(e,t),Ya.init(e,t)}),ul=Br("ZodCUID",(e,t)=>{bo.init(e,t),Ya.init(e,t)}),cl=Br("ZodCUID2",(e,t)=>{wo.init(e,t),Ya.init(e,t)}),dl=Br("ZodULID",(e,t)=>{_o.init(e,t),Ya.init(e,t)}),pl=Br("ZodXID",(e,t)=>{ko.init(e,t),Ya.init(e,t)}),hl=Br("ZodKSUID",(e,t)=>{xo.init(e,t),Ya.init(e,t)}),fl=Br("ZodIPv4",(e,t)=>{zo.init(e,t),Ya.init(e,t)}),ml=Br("ZodIPv6",(e,t)=>{To.init(e,t),Ya.init(e,t)}),gl=Br("ZodCIDRv4",(e,t)=>{Ao.init(e,t),Ya.init(e,t)}),yl=Br("ZodCIDRv6",(e,t)=>{No.init(e,t),Ya.init(e,t)}),vl=Br("ZodBase64",(e,t)=>{Co.init(e,t),Ya.init(e,t)}),bl=Br("ZodBase64URL",(e,t)=>{Do.init(e,t),Ya.init(e,t)}),wl=Br("ZodE164",(e,t)=>{Zo.init(e,t),Ya.init(e,t)}),_l=Br("ZodJWT",(e,t)=>{Uo.init(e,t),Ya.init(e,t)}),kl=Br("ZodNumber",(e,t)=>{Lo.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=n,{minimum:o,maximum:s,multipleOf:a,exclusiveMaximum:l,exclusiveMinimum:u,isInt:c}=ka(e);i.type=c?"integer":"number";let d="number"==typeof u&&u>=(o??Number.NEGATIVE_INFINITY),p="number"==typeof l&&l<=(s??Number.POSITIVE_INFINITY),h="draft-04"===t.target||"openapi-3.0"===t.target;if(d?h?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:"number"==typeof o&&(i.minimum=o),p?h?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:"number"==typeof s&&(i.maximum=s),a){let n=new Set;for(let o of a)Number.isFinite(o)&&0!==o?n.add(Math.abs(o)):Ys(e,t,i,r,`A multipleOf divisor of ${o} cannot be represented in JSON Schema`);let[o,...s]=n;void 0!==o&&(i.multipleOf=o),s.length&&(i.allOf=[...i.allOf??[],...s.map(e=>({multipleOf:e}))])}})(e,t,n,r),e.isFinite=!0},Cr({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=ka(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=ka(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:n}=ka(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>ka(e).format??null},{gt(e,t){return this.check(Fs(e,t))},gte(e,t){return this.check(Js(e,t))},min(e,t){return this.check(Js(e,t))},lt(e,t){return this.check(Us(e,t))},lte(e,t){return this.check(Ls(e,t))},max(e,t){return this.check(Ls(e,t))},int(e){return this.check(Ol(e))},safe(e){return this.check(Ol(e))},positive(e){return this.check(Fs(0,e))},nonnegative(e){return this.check(Js(0,e))},negative(e){return this.check(Us(0,e))},nonpositive(e){return this.check(Ls(0,e))},multipleOf(e,t){return this.check(Vs(e,t))},step(e,t){return this.check(Vs(e,t))},finite(){return this}}));var xl=Br("ZodNumberFormat",(e,t)=>{Fo.init(e,t),kl.init(e,t)});function Ol(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...yr(t)})}(xl,e)}var $l=Br("ZodBoolean",(e,t)=>{Jo.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function Sl(e){return function(e,t){return new e({type:"boolean",...yr(t)})}($l,e)}var El=Br("ZodUnknown",(e,t)=>{Vo.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function zl(){return new El({type:"unknown"})}var Pl=Br("ZodNever",(e,t)=>{qo.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function Il(e){return function(e,t){return new e({type:"never",...yr(t)})}(Pl,e)}var Tl=Br("ZodArray",(e,t)=>{Ba(),Bo.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=n,o=e._zod.def,{minimum:s,maximum:a}=ka(e);"number"==typeof s&&(i.minItems=s),"number"==typeof a&&(i.maxItems=a),i.type="array",i.items=Qs(o.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Ws(e,t))},nonempty(e){return this.check(Ws(1,e))},max(e,t){return this.check(qs(e,t))},length(e,t){return this.check(Bs(e,t))},unwrap(){return this.element}});function Al(e,t){return function(e,t,n){return new e({type:"array",element:t,...yr(n)})}(Tl,e,t)}var Nl=Br("ZodObject",(e,t)=>{Ba(),Qo.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=n,o=e._zod.def,s=o.shape;if(Object.getOwnPropertySymbols(s).length&&Ys(e,t,i,r,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(let e in s)tr(i.properties,e,Qs(s[e],t,{...r,path:[...r.path,"properties",e]}));let a=[];for(let e of Object.keys(s)){let n=o.shape[e];("input"===t.io?void 0===Sa(n):void 0===n._zod.optout)&&a.push(e)}a.length>0&&(i.required=a),"never"===o.catchall?._zod.def.type?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=Qs(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(i.additionalProperties=!1)})(e,t,n,r),Fr(e,"shape",e=>e._zod.def.shape,!1)},{keyof(){return function(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Dl({type:"enum",entries:n,...yr(t)})}(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(ar(this._zod.def,{catchall:e}))},passthrough(){return this.clone(ar(this._zod.def,{catchall:zl()}))},loose(){return this.clone(ar(this._zod.def,{catchall:zl()}))},strict(){return this.clone(ar(this._zod.def,{catchall:Il()}))},strip(){return this.clone(ar(this._zod.def,{catchall:void 0}))},extend(e){return function(e,t){if(!pr(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let n=rr(e);for(let e of Reflect.ownKeys(t))if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return gr(e,ar(e._zod.def,{shape:kr(e,t)}))}(this,e)},safeExtend(e){return function(e,t){if(!pr(t))throw Error("Invalid input to safeExtend: expected a plain object");return gr(e,ar(e._zod.def,{shape:kr(e,t)}))}(this,e)},merge(e){return function(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n={};return sr(n,e,Reflect.ownKeys(rr(e))),sr(n,t,Reflect.ownKeys(rr(t))),gr(e,ar(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}(this,e)},pick(e){return function(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i={};return sr(i,e,_r(e,t)),gr(e,ar(n,{shape:i,checks:[]}))}(this,e)},omit(e){return function(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(_r(e,t)),o={};return sr(o,e,Reflect.ownKeys(rr(e)).filter(e=>!i.has(e))),gr(e,ar(n,{shape:o,checks:[]}))}(this,e)},partial(...e){return xr(Fl,this,e[0])},exactPartial(...e){return xr(Vl,this,e[0],"exactPartial")},required(...e){return function(e,t,n){let r=n?new Set(_r(t,n)):void 0,i={};return sr(i,t,Reflect.ownKeys(rr(t)),(t,n)=>r&&!r.has(n)?t:new e({type:"nonoptional",innerType:t})),gr(t,ar(t._zod.def,{shape:i}))}(Kl,this,e[0])}});function jl(e,t){let n={type:"object",shape:e??{},...yr(t)};return new Nl(n)}var Rl=Br("ZodUnion",(e,t)=>{ts.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def,o=!1===i.inclusive,s=i.options.map((e,n)=>Qs(e,t,{...r,path:[...r.path,o?"oneOf":"anyOf",n]}));o?n.oneOf=s:n.anyOf=s})(e,t,n,r),e.options=t.options});function Cl(e,t){return new Rl({type:"union",options:e,...yr(t)})}var Ml=Br("ZodIntersection",(e,t)=>{ns.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def,o=Qs(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=Qs(i.right,t,{...r,path:[...r.path,"allOf",1]}),a=e=>"allOf"in e&&1===Object.keys(e).length,l=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=l,t.intersections.push(l)})(e,t,n,r)});var Dl=Br("ZodEnum",(e,t)=>{os.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{let r=Kn(e._zod.def.entries);0!==r.length?(r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r):n.not={}})(e,0,n),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e){if(!n.has(r))throw Error(`Key ${r} not found in enum`);i[r]=t.entries[r]}return new Dl({...t,checks:[],...yr(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e){if(!n.has(t))throw Error(`Key ${t} not found in enum`);delete i[t]}return new Dl({...t,checks:[],...yr(r),entries:i})}});var Zl=Br("ZodLiteral",(e,t)=>{ss.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;if(0===i.values.length)return void(n.not={});let o=[];for(let s of i.values)if(void 0===s){if(Ys(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if("bigint"==typeof s){if(Ys(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(s))}else o.push(s);if(0===o.length);else if(1===o.length){let e=o[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else o.every(e=>"number"==typeof e)&&(n.type="number"),o.every(e=>"string"==typeof e)&&(n.type="string"),o.every(e=>"boolean"==typeof e)&&(n.type="boolean"),o.every(e=>null===e)&&(n.type="null"),n.enum=o})(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Ul(e,t){return new Zl({type:"literal",values:Array.isArray(e)?e:[e],...yr(t)})}var Ll=Br("ZodTransform",(e,t)=>{Ba(),as.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{Ys(e,t,n,r,"Transforms cannot be represented in JSON Schema")})(e,t,n,r),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new Kr(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(Nr(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),"input"in t||(t.input=n.value),t.inst??(t.inst=e),n.issues.push(Nr(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});var Fl=Br("ZodOptional",(e,t)=>{us.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pa(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function Jl(e){return new Fl({type:"optional",innerType:e})}var Vl=Br("ZodExactOptional",(e,t)=>{cs.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pa(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var ql=Br("ZodNullable",(e,t)=>{ds.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def,o=Qs(i.innerType,t,r),s=t.seen.get(e);"openapi-3.0"===t.target?(s.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Wl(e){return new ql({type:"nullable",innerType:e})}var Bl=Br("ZodDefault",(e,t)=>{ps.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;Qs(i.innerType,t,r),t.seen.get(e).ref=i.innerType;let o=za(i.defaultValue,e,t,n,r);o!==Ea&&(n.default=o)})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});var Hl=Br("ZodPrefault",(e,t)=>{fs.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;if(Qs(i.innerType,t,r),t.seen.get(e).ref=i.innerType,"input"!==t.io)return;let o=za(i.defaultValue,e,t,n,r);o!==Ea&&(n._prefault=o)})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var Kl=Br("ZodNonOptional",(e,t)=>{ms.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;Qs(i.innerType,t,r),t.seen.get(e).ref=i.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var Gl=Br("ZodCatch",(e,t)=>{vs.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i,o=e._zod.def;Qs(o.innerType,t,r),t.seen.get(e).ref=o.innerType;try{i=o.catchValue(void 0)}catch{return void Ys(e,t,n,r,"Dynamic catch values are not supported in JSON Schema")}n.default=i})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});var Xl=Br("ZodPipe",(e,t)=>{bs.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def,o=i.in._zod.traits.has("$ZodTransform"),s="input"===t.io?o?i.out:i.in:i.out;Qs(s,t,r),t.seen.get(e).ref=s})(e,t,0,r),e.in=t.in,e.out=t.out});function Yl(e,t){return new Xl({type:"pipe",in:e,out:t})}var Ql=Br("ZodReadonly",(e,t)=>{_s.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;Qs(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var eu=Br("ZodCustom",(e,t)=>{xs.init(e,t),Ha.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{Ys(e,t,n,r,"Custom types cannot be represented in JSON Schema")})(e,t,n,r)});var tu,nu=jl({protocolVersion:Xa(),engineVersion:Xa(),buildSha:Xa(),abi:Xa()}),ru=jl({backend:Xa(),displayServer:Xa().nullable().optional(),capture:Sl(),input:Sl(),ax:Sl(),backgroundWindowInput:Sl(),deliveryModes:Al(Xa()),capturePermission:Xa(),inputPermission:Xa(),axPermission:Xa(),displayCount:function(e,t){return new e(Zs({type:"number",checks:[],...yr(t)}))}(kl,tu).int().nonnegative(),focusGuard:Sl(),stopPath:Xa(),stopReason:Xa().nullable().optional(),integrityLevel:Xa().nullable().optional(),screenLocked:Sl()}),iu=jl({id:Cl([Ul(1),Ul(2)]),result:zl().optional(),error:zl().optional()});var ou=(e,t,n)=>Bn(e,[...t],{stdio:"pipe",windowsHide:!0,detached:!0,env:n});function su(e,t,n,r=ou){let i=r(e,["--stdio"],{...process.env,...t});return new Promise(t=>{let r,o=new Map,s="",a=e=>{void 0===r&&(r=e,i.stdin.end())},l=setTimeout(()=>{let o=r??{ok:!1,code:"timeout",message:`desktop engine probe timed out after ${n} ms at ${e}`};if(a(o),t(o),u.close(),i.stdin.destroy(),i.stdout.destroy(),i.stderr.destroy(),i.unref(),void 0!==i.pid)if("win32"===process.platform){let e=Bn("taskkill",["/pid",String(i.pid),"/T","/F"],{stdio:"ignore",windowsHide:!0});e.once("error",()=>i.kill("SIGKILL")),e.unref()}else try{process.kill(-i.pid,"SIGKILL")}catch(e){if(!(e instanceof Error&&"code"in e&&"ESRCH"===e.code))throw e}},n);i.stderr.setEncoding("utf8"),i.stderr.on("data",e=>{s=(s+e).slice(-4096)}),i.stdin.on("error",t=>{a({ok:!1,code:"handshake-failed",message:`desktop engine stdin failed at ${e}: ${t.message}`})}),i.on("error",t=>{a({ok:!1,code:"handshake-failed",message:`desktop engine spawn failed at ${e}: ${t.message}`})});let u=Hn({input:i.stdout}).on("line",t=>{let n;try{n=JSON.parse(t)}catch(t){if(!(t instanceof SyntaxError))throw t;return void a({ok:!1,code:"handshake-failed",message:`desktop engine emitted non-JSON output at ${e}`})}let r=iu.safeParse(n);r.success&&(void 0===r.data.error?(o.set(r.data.id,r.data.result),o.has(1)&&o.has(2)&&a(function(e,t,n){let r=nu.safeParse(e);if(!r.success)return{ok:!1,code:"handshake-failed",message:`malformed engine.hello result at ${n}`};if(r.data.abi!==G||r.data.protocolVersion!==K)return{ok:!1,code:"abi-mismatch",message:`desktop engine ABI mismatch at ${n}: expected abi ${G} protocol ${K}, engine reported abi ${r.data.abi} protocol ${r.data.protocolVersion}`};let i=ru.safeParse(t);return i.success?{ok:!0,value:{hello:r.data,capabilities:i.data}}:{ok:!1,code:"handshake-failed",message:`malformed capabilities result at ${n}`}}(o.get(1),o.get(2),e))):a({ok:!1,code:"handshake-failed",message:`desktop engine request ${r.data.id} failed at ${e}: ${JSON.stringify(r.data.error)}`}))});i.on("close",(n,i)=>{clearTimeout(l),t(r??{ok:!1,code:"handshake-failed",message:`desktop engine exited before the probe completed at ${e} (code ${n??"null"}, signal ${i??"null"}); stderr: ${s.trim()||"<empty>"}`})}),i.stdin.write(`${JSON.stringify({jsonrpc:"2.0",id:1,method:"engine.hello",params:{}})}\n`),i.stdin.write(`${JSON.stringify({jsonrpc:"2.0",id:2,method:"capabilities",params:{}})}\n`)})}async function au(e,t,n={}){let r=Un(e,t,Fn(t),n);if(!("path"in r))return"OS permissions: unknown until first use (no usable installed engine)";let i=await su(r.path,t,5e3);if(!i.ok)return`OS permissions: unknown (${i.code}: ${i.message})`;let o=i.value.capabilities;return`OS permissions: capturePermission=${o.capturePermission} inputPermission=${o.inputPermission} axPermission=${o.axPermission} (passive probe)`}function lu(e){let t=e.engineChild??Jn(),n=new Wn({createChild:t(e.settings.enginePath),onError:t=>e.onEngineError(function(e){return e instanceof ct?e.diagnostic.code:e instanceof me?"abi-mismatch":e instanceof mt?null!==e.data&&"code"in e.data?e.data.code:"other":e instanceof ft?e.code:"other"}(t))}),r=new y({service:n,settings:()=>e.settings}),i={handle:r,executeTool:e.executeTool};return{handle:r,service:n,computerTool:On(i),computerActionsTool:Sn(i),describeEngineSource:Vn,describeEnginePermissions:au}}export{lu as createComputerUseRuntime};
|