omo-ai 5.1.47 → 5.1.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/bin/lib/category-coverage.js +5 -4
  2. package/bin/lib/provider-map.json +1 -1
  3. package/package.json +2 -2
  4. package/plugin/CHANGELOG.md +22 -0
  5. package/plugin/extensions/gateway-store-worker.mjs +1 -1
  6. package/plugin/extensions/memory-run-supervisor.mjs +1 -1
  7. package/plugin/extensions/omo-claim-receipt.js +1 -1
  8. package/plugin/extensions/omo-computer-use.js +1 -1
  9. package/plugin/extensions/omo-device-account.js +1 -1
  10. package/plugin/extensions/omo-feedback.js +1 -1
  11. package/plugin/extensions/omo-init-deep-advisor.js +1 -1
  12. package/plugin/extensions/omo-member.js +1 -1
  13. package/plugin/extensions/omo-memory-commands.js +3 -3
  14. package/plugin/extensions/omo-memory-doctor.js +3 -3
  15. package/plugin/extensions/omo-memory-memfs.js +3 -3
  16. package/plugin/extensions/omo-memory-palace.js +3 -3
  17. package/plugin/extensions/omo-memory-sync.js +1 -1
  18. package/plugin/extensions/omo-onboarding-scan.js +3 -3
  19. package/plugin/extensions/omo-recall-store.js +1 -1
  20. package/plugin/extensions/omo-session-history.js +1 -1
  21. package/plugin/extensions/omo-side-panel.js +1 -1
  22. package/plugin/extensions/omo-task.js +2 -2
  23. package/plugin/extensions/omo-telemetry-posthog.js +1 -1
  24. package/plugin/extensions/omo-telemetry-recovery.js +1 -1
  25. package/plugin/extensions/omo-thread-client.js +1 -1
  26. package/plugin/extensions/omo.js +3 -3
  27. package/plugin/package.json +1 -1
  28. package/plugin/runtime/agent-toolkit-sdk/sdk.js +2 -2
  29. package/plugin/runtime/ast-grep-mcp/manifest.json +1 -1
  30. package/plugin/runtime/rollback-migrate.js +1 -1
  31. package/plugin/runtime/thread-sdk/sdk.js +2 -2
  32. package/plugin/skills/browser/runtime/omowright/manifest.json +1 -1
  33. package/plugin/skills/ulw-research/SKILL.md +58 -1
  34. package/plugin/skills/ulw-research/references/deliverable-phase.md +51 -9
  35. package/plugin/skills/ulw-research/references/report-gates.md +2 -1
  36. package/plugin/skills/ulw-research/scripts/contracts.mjs +3 -11
  37. package/plugin/skills/ulw-research/scripts/fact-commands-fill.mjs +86 -0
  38. package/plugin/skills/ulw-research/scripts/fact-commands-meaning.mjs +14 -22
  39. package/plugin/skills/ulw-research/scripts/fact-commands-polish.mjs +7 -2
  40. package/plugin/skills/ulw-research/scripts/fact-commands-verify.mjs +18 -4
  41. package/plugin/skills/ulw-research/scripts/fact-commands.mjs +6 -47
  42. package/plugin/skills/ulw-research/scripts/fact-fill.mjs +3 -2
  43. package/plugin/skills/ulw-research/scripts/fidelity-policy.mjs +183 -0
  44. package/plugin/skills/ulw-research/scripts/source-commands.mjs +8 -3
@@ -1,2 +1,2 @@
1
- // omo:wPVO5Lm_8uF_ZsnFvDzB5TJLq1J2bzt0nQCXAklf1uQ:VG4ttkTvjkvUvX1Mmu2dGc10CTeyUl0mHPEJyKwH_eI
1
+ // omo:Gn4DDj5mxTEabqA4p0TMA2XLI6XyhzgOaaAoE2YSDP8:VG4ttkTvjkvUvX1Mmu2dGc10CTeyUl0mHPEJyKwH_eI
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;#s=!1;constructor(e){this.#e=e.service,this.#t=e.settings}get service(){return this.#e}settings(){let e=this.#t();return void 0===this.#i?e:{...e,showCursor:this.#i}}get enabled(){return this.#r??this.#t().enabled}get active(){return this.#s}get running(){return void 0!==this.#o}setEnabled(e){this.#r=e}async setShowCursor(e,t){this.#i=e,this.running&&await this.#a(this.settings(),t)}onActivationChange(e){return this.#n.add(e),()=>this.#n.delete(e)}async activate(e){if(!this.enabled)throw new g;let t=this.settings();await this.#a(t,e);let n=await this.#e.ensureStopPath(t.stopHotkey);return this.#l(!0),n}async deactivate(){await this.close(),this.#l(!1)}async close(){this.#o=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#a(e,t){let n=function(e,t){let{auditLog:n,screenshotGc:r}=e;return{display:e.display,macosCanary:e.macosCanary,showCursor:e.showCursor,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.#o?.key!==r&&(this.#o={key:r,done:this.#e.open(n)});let i=this.#o;try{await i.done}catch(e){throw this.#o===i&&(this.#o=void 0),e}}#l(e){if(this.#s!==e){this.#s=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."}))},E={x:k.Number(),y:k.Number()},S={additionalProperties:!1},P=[k.Object({action:k.Literal("screenshot"),...$},S),k.Object({action:k.Literal("click"),...E,button:k.Optional(O),...$},S),k.Object({action:k.Literal("double_click"),...E,button:k.Optional(O),...$},S),k.Object({action:k.Literal("move"),...E,button:k.Optional(O),...$},S),k.Object({action:k.Literal("drag"),...E,to_x:k.Number(),to_y:k.Number(),button:k.Optional(O),...$},S),k.Object({action:k.Literal("scroll"),...E,scroll_x:k.Number(),scroll_y:k.Number(),...$},S),k.Object({action:k.Literal("type"),text:k.String(),...$},S),k.Object({action:k.Literal("keypress"),keys:k.Array(k.String(),{minItems:1}),...$},S),k.Object({action:k.Literal("wait"),ms:k.Integer({minimum:0}),...$},S)],z=k.Union([...P]),I=k.Object({action:k.Literal("batch"),actions:k.Array(z,{minItems:1}),...$},S),T=k.Union([z,I]),A=["screenshot","click","double_click","move","drag","scroll","type","keypress","wait"],C={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"})),...$},R=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"}),...C},S),{minItems:1,description:"batch (required): actions to execute in order"})),...C},S),N=w(P),j=w([...P,I]);var M=new Set(["screenshot","wait"]);var U=/^senpi-desktop-engine: refusing to run as its own responsible process \(pid [1-9]\d*\): spawn the engine as a child of the app, terminal or host that holds the computer-use grants, without the responsibility-disclaim attribute and not as a launchd job or through a shell exec$/,L=/^senpi-desktop-engine: refusing to run: the responsible process of engine pid [1-9]\d* cannot be resolved$/;class D extends Error{code="launch-context-unavailable";reason;diagnostic;constructor(e,t){super("COMPUTER_LAUNCH_CONTEXT_REQUIRED: Computer use cannot start safely from this host's current macOS launch context."+("unresolved"===e?" macOS responsibility could not be resolved.":"")+" Restart this host from a local terminal and keep that terminal app running, or use the OmO desktop app (Settings > Restart engine). Opening a new terminal or reconnecting to this same host does not repair its launch context."),this.name="DesktopLaunchContextError",this.reason=e,this.diagnostic=t}}class Z{#u="";#c=!1;#d=!1;#p=!1;#h=!1;#f;#m;#g="";disable(){this.#d=!0,this.#u=""}push(e){if(this.#d)return;let t=0;for(;t<e.length;){let n=e.indexOf("\n",t),r=e.slice(t,-1===n?e.length:n);if(this.#c||=Buffer.byteLength(this.#u+r,"utf8")>=512,this.#u+=r.slice(0,Math.max(0,512-this.#u.length)),-1===n)return;this.#y(),this.#u="",this.#c=!1,t=n+1}}finish(e,t,n){if(this.#u.startsWith("SENPI_DESKTOP_LAUNCH_REFUSED")&&(this.#h=!0),this.#d||this.#h||1!==e||null!==t)return;let r=this.#p?this.#f:this.#m;return void 0===r?void 0:new D(r,`${this.#g}\n${n}`)}#y(){if(this.#u.startsWith("SENPI_DESKTOP_LAUNCH_REFUSED")){this.#p&&(this.#h=!0),this.#p=!0;let e=this.#c?void 0:function(e){if(!e.startsWith("SENPI_DESKTOP_LAUNCH_REFUSED ")||Buffer.byteLength(e,"utf8")+1>512)return;let t,n=e.slice(29);try{t=JSON.parse(n)}catch(e){if(e instanceof SyntaxError)return;throw e}return"object"!=typeof t||null===t||Array.isArray(t)||2!==n.match(/"(?:\\.|[^"\\])*"\s*:/g)?.length||2!==Object.keys(t).length||!("version"in t)||1!==t.version||!("reason"in t)||"self-responsible"!==t.reason&&"unresolved"!==t.reason?void 0:t.reason}(this.#u);return void(void 0===e?this.#h=!0:(this.#f=e,this.#g=this.#u))}if(this.#c)return;let e=U.test(this.#u)?"self-responsible":L.test(this.#u)?"unresolved":void 0;void 0!==e&&(void 0!==this.#m&&this.#m!==e&&(this.#h=!0),this.#m=e)}}var F={capabilities:"read",displays:"read",display:"read",windows:"read",window:"read",focusedWindow:"read",screenshot:"read",zoom:"read",click:"exec",doubleClick:"exec",move:"exec",drag:"exec",scroll:"exec",type:"exec",press:"exec",holdKeys:"exec",holdMouse:"exec",elementAt:"read",focusedElement:"read",ref:"read","clipboard.read":"read","clipboard.write":"exec","control.acquire":"exec","control.release":"exec","control.state":"read"},J={screenshot:"read",zoom:"read",click:"exec",doubleClick:"exec",move:"exec",drag:"exec",scroll:"exec",type:"exec",press:"exec",holdKeys:"exec",holdMouse:"exec"},q={screenshot:"read",observe:"read",zoom:"read",click:"exec",doubleClick:"exec",move:"exec",drag:"exec",scroll:"exec",type:"exec",press:"exec",holdKeys:"exec",holdMouse:"exec",raise:"exec",ax:"read",find:"read",ref:"read","menu.items":"read","menu.select":"exec"},V={value:"read",setValue:"exec",bounds:"read",attributes:"read",actions:"read",perform:"exec",press:"exec",click:"exec",focus:"exec",parent:"read",children:"read"},W={display:{label:"display",methods:J},window:{label:"window",methods:q},ref:{label:"element",methods:V}};class H extends Error{reason;constructor(e,t){super(t),this.name="ComputerCallError",this.reason=e}}function K(e,t){return Object.hasOwn(e,t)?e[t]:void 0}function B(e){return Object.keys(e).join(", ")}function G(e){return"read"===function(e){let[t,n,...r]=e;if(void 0===t)throw new H("empty","Action 'call' requires a non-empty 'chain'.");if(r.length>0)throw new H("tooLong","Call chains support one handle hop at most; use computer.run(fn) for longer sequences.");let i=K(F,t.method);if(void 0===i)throw new H("unknownMethod",`Unknown desktop method "${t.method}". Desktop helpers support: ${B(F)}.`);if(void 0===n)return i;let o=Object.hasOwn(W,t.method)?W[t.method]:void 0;if(void 0===o)throw new H("notChainable",`Only desktop.display(id)/desktop.window(id)/desktop.ref(ref) results accept a chained call; got desktop.${t.method}().`);let s=K(o.methods,n.method);if(void 0===s)throw new H("unknownMethod",`Unknown ${o.label} method "${n.method}". Supported ${o.label} methods: ${B(o.methods)}.`);return s}(e)}var X="1",Y="senpi-desktop/1",Q=["audit","stopPath.changed","engine.log"],ee=["PermissionDenied","CaptureFailed","InputFailed","BackgroundUnavailable","WindowNotFound","InvalidTarget","InvalidKey","InvalidCoordinateFrame","StaleRef","AxUnsupported","AxFailed","Timeout","Closed","Internal","StopPathUnavailable","Suspended","ScreenLocked","Cancelled","CursorRestoreFailed","FocusRestoreFailed","TransactionFailed","InputBusy","ControlRequired","CaptureUnavailable"];class te extends Error{code="abi-mismatch";enginePath;expected;actual;constructor(e,t){let n={abi:Y,protocolVersion:X};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 ne}from"node:child_process";import{createHash as re}from"node:crypto";import{accessSync as ie,constants as oe,existsSync as se,readFileSync as ae,realpathSync as le}from"node:fs";import{dirname as ue,join as ce,sep as de}from"node:path";import{fileURLToPath as pe}from"node:url";var he="senpi-desktop-engine-checksums.txt",fe=["darwin-arm64","darwin-x64","linux-x64","linux-arm64","win32-x64","win32-arm64"];function me(e){switch(e){case"darwin-arm64":case"darwin-x64":case"linux-x64":case"linux-arm64":return`senpi-desktop-engine-${e}`;case"win32-x64":case"win32-arm64":return`senpi-desktop-engine-${e}.exe`;default:return null}}function ge(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||!fe.some(e=>me(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 ye,ve="senpi-desktop-engine",be="com.apple.quarantine",we=ce(ue(pe(import.meta.url)),"..");function _e(e=process.platform,t=process.arch,n=("linux"===e&&e===process.platform?function(){return ye??=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(),ke),ye}():void 0)){return"linux"===e&&"musl"===n?`${e}-${t}-musl`:`${e}-${t}`}function ke(){try{return ae("/proc/self/maps","utf8")}catch(e){if(e instanceof Error&&"code"in e)return;throw e}}function xe(e=process.platform){return"win32"===e?`${ve}.exe`:ve}function Oe(e={}){let t=_e(e.platform,e.arch,e.libc),n=xe(e.platform),r=e.packageDir??we,i=e.execDir??ue(process.execPath),o=e.repoRoot??ce(r,"..",".."),s=ce("native","prebuilds",t,n),a=e.runtimeDir??process.env.OMO_PACKAGE_DIR;return[...a?[ce(a,s)]:[],ce(i,s),ce(r,s),ce(o,"target","release",n)]}function $e(e={}){let t=e.platform??process.platform,n=_e(t,e.arch,e.libc),r=Oe(e),i=e.execDir??ue(process.execPath),o=e.runtimeDir??process.env.OMO_PACKAGE_DIR?1:0,s=e.isQuarantined??(e=>Se(e,t)),a=[],l=[];for(let[e,t]of r.entries())if(se(t)){if(s(t)){if(e!==o||!Ee(t,i,n)){l.push(t),a.push(`${t}: blocked because ${be} 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(Pe(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===me(n)?"no-release-asset":void 0;return{path:null,diagnostic:{code:u,host:n,attemptedPaths:r,message:"quarantined"===u?`The ${ve} 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 ${ve} binary is available for ${n}.`,cause:a.join("; "),...void 0===c?{}:{reason:c}}}}function Ee(e,t,n){try{let r=`${ce(le(t),"native","prebuilds")}${de}`;if(!le(e).startsWith(r))return!1;let i=me(n);if(null===i)return!1;let o=ge(ae(ce(t,"native","prebuilds",he),"utf8"));if(null!==o.error)return!1;let s=o.checksums.get(i);return void 0!==s&&re("sha256").update(ae(e)).digest("hex")===s.toLowerCase()}catch(e){if(e instanceof Error&&"code"in e)return!1;throw e}}function Se(e,t=process.platform){if("darwin"!==t)return!1;let n=ne("/usr/bin/xattr",["-p",be,e],{stdio:["ignore","ignore","ignore"],timeout:2e3});return void 0===n.error&&0===n.status}function Pe(e){try{return ie(e,oe.X_OK),!0}catch(e){if(e instanceof Error&&"code"in e)return!1;throw e}}import{createHash as ze,randomUUID as Ie}from"node:crypto";import{accessSync as Te,chmodSync as Ae,constants as Ce,existsSync as Re,mkdirSync as Ne,mkdtempSync as je,readFileSync as Me,readdirSync as Ue,renameSync as Le,rmSync as De,writeFileSync as Ze}from"node:fs";import{homedir as Fe}from"node:os";import{join as Je}from"node:path";import{spawnSync as qe}from"node:child_process";function Ve(e){let t=qe("/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 We="-musl";function He(e,t){let{host:n,version:r}=e,i=me(n),o=[];if(null===i)return{path:null,attemptedPaths:o};let s=n.slice(0,n.indexOf("-")),a=e.cacheDir??Je(Fe(),".omo","cache","senpi-desktop-engine"),l=Je(a,r,n);if(Re(l))for(let e of Ue(l)){let n=/^([0-9a-f]{64})-[0-9a-f-]{36}$/.exec(e);if(null===n)continue;let r=Je(l,e,i);if(o=[...o,r],t?.(r),Re(r)&&ze("sha256").update(Me(r)).digest("hex")===n[1]&&!Se(r,s))try{return Te(r,Ce.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 Ke(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(We)?"musl":"glibc",u="musl"===l?a.slice(0,-5):a,c=$e({...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&&Je(r,"native","prebuilds",t,xe(s));if("darwin"===s&&c.path===o&&r&&(e.isReleaseEngine??Ve)(c.path)){let e=JSON.parse(Me(Je(r,"package.json"),"utf8"));return"object"==typeof e&&null!==e&&"omo"===Reflect.get(e,"name")&&Reflect.get(e,"version")===n?{path:c.path,sha256:ze("sha256").update(Me(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=me(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??Je(Fe(),".omo","cache","senpi-desktop-engine"),h=Je(p,n,t),f=He(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,Je(h,d)];let[y,v]=await Promise.all([m(`${g}/${d}`,{signal:AbortSignal.timeout(3e4)}),m(`${g}/${he}`,{signal:AbortSignal.timeout(3e4)})]);if(!y.ok)return i(`${d}: HTTP ${y.status}`);if(!v.ok)return i(`${he}: HTTP ${v.status}`);let b=ge(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=ze("sha256").update(_).digest("hex");if(k.toLowerCase()!==w.toLowerCase())return i(`SHA-256 mismatch for ${d}`);Ne(h,{recursive:!0});let x=je(Je(h,".download-")),O=Je(h,`${k}-${Ie()}`);try{let e=Je(x,d);Ze(e,_),Ae(e,493),Le(x,O)}finally{De(x,{recursive:!0,force:!0})}return{path:Je(O,d),sha256:k}}catch(e){return i(e instanceof Error?e.message:String(e))}}async function Be(e,p,h=Ke){let f=await h(e);if(null===f.path)return f;let m=e.isReleaseEngine??Ve;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:Je(e.installDir??Je(Fe(),".omo","engines","senpi-desktop-engine"),e.host)},t=>Se(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 Ge extends Error{reason;constructor(e,t){super(t),this.name="ComputerRunError",this.reason=e}}class Xe{#v=[];text(e){this.#v.push({type:"text",text:e})}image(e,t){this.#v.push({type:"image",data:e,mimeType:t})}finish(){return[...this.#v]}}function Ye(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 Ge("readOnly",`read-only run: '${n}' requires read_only: false`);e.signal.throwIfAborted()}(e.context,t,n),r(e))))}import{randomUUID as Qe}from"node:crypto";var et=new Set(["engine.hello","session.open","session.close","control.grant","control.revoke","control.state","capabilities","displays","windows","capture","captureRegion","observe","click","moveMouse","drag","scroll","typeText","keyChord","holdKeys","holdMouse","raiseWindow","menus.items","menus.select","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"]),tt=new Set(ee),nt=new Set(["global","host-relay","none"]),rt=["unknown","hostOnly","testOnly"],it={suspended:"boolean",globalLive:"boolean",hostRelayLive:"boolean",heartbeatFresh:"boolean",stopPath:"string",reason:"string?"},ot={backend:"string",displayServer:"string?",capture:"boolean",input:"boolean",ax:"boolean",backgroundWindowInput:"boolean",cursorOverlay:"boolean?",capturePermission:"string",inputPermission:"string",axPermission:"string",displayCount:"number",focusGuard:"boolean",stopPath:"string",stopReason:"string?",integrityLevel:"string?",screenLocked:"boolean"},st={action:"string",target:"string",delivery:"string",frameId:"string?",code:"string?",durationMs:"number",focusRestored:"boolean?",textLength:"number?",textDelivered:"number?",textSha256:"string?"};function at(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function lt(e,t){return!!at(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 ut(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function ct(e,t){return"string"==typeof e&&t.has(e)}function dt(e){return lt(e,it)&&ct(e.stopPath,nt)}function pt(e){return lt(e,ot)&&ut(e.deliveryModes)&&(void 0===e.cursorOverlay||"boolean"==typeof e.cursorOverlay)}function ht(e){if(!at(e))return null;let t=ee.find(t=>t===e.code);if(void 0!==t){let n=function(e){if(!at(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=rt.find(t=>t===e.reason);return void 0===n?null:{reason:n}}import{spawn as ft}from"node:child_process";import{createInterface as mt}from"node:readline";class gt extends Error{diagnostic;constructor(e){super(`${e.message} ${e.cause}`),this.name="DesktopEngineUnavailableError",this.diagnostic=e}}function yt(e){return()=>vt(e??function(){let e=$e();if(null===e.path)throw new gt(e.diagnostic);return e.path}())}function vt(e){return ft(e,["--stdio"],{stdio:"pipe",windowsHide:!0})}class bt{path;exited;#b;#w="";#_="";#k=!0;#x=new Z;constructor(e,t){this.#b=e,this.path=e.spawnfile,e.stderr.setEncoding("utf8"),e.stderr.on("data",e=>{this.#x.push(e),this.#w=(this.#w+e).slice(-4096)}),e.stdin.on("error",e=>this.#O(`stdin: ${e.message}`)),e.on("error",e=>{this.#x.disable(),this.#O(`spawn: ${e.message}`)}),mt({input:e.stdout}).on("line",t.onLine),this.exited=new Promise(n=>{e.on("close",(e,r)=>{this.#k=!1;let i=this.#$(e,r);t.onExit(i,this.#x.finish(e,r,i)),n()})})}get alive(){return this.#k}finishStartup(){this.#x.disable()}write(e){this.#k&&!this.#b.stdin.writableEnded&&this.#b.stdin.write(`${JSON.stringify({jsonrpc:"2.0",...e})}\n`)}end(){this.#b.stdin.end()}kill(){this.#x.disable(),this.#k&&(this.#k=!1,this.#b.kill())}#O(e){this.#_=""===this.#_?e:`${this.#_}; ${e}`}#$(e,t){return`desktop engine exited (code ${e??"null"}, signal ${t??"null"})${""===this.#_?"":`; ${this.#_}`}; stderr: ${this.#w.trim()||"<empty>"}`}}class wt extends Error{code;engineRestarted;constructor(e,t,n=!1){super(t),this.name="DesktopServiceError",this.code=e,this.engineRestarted=n}}class _t extends Error{method;rpcCode;data;constructor(e,t){super(t.message),this.name="DesktopEngineRpcError",this.method=e,this.rpcCode=t.code,this.data=ht(t.data)}}class kt{#E;#S;#P=new Map;#z=1;#$;constructor(e,t){this.#S=t,this.#E=new bt(e,{onLine:e=>this.#I(e),onExit:(e,t)=>this.#T(e,t)})}get enginePath(){return this.#E.path}get alive(){return void 0===this.#$&&this.#E.alive}get exited(){return this.#E.exited}request(e,t,n={}){if(!this.alive)return Promise.reject(new wt("Closed",this.#$??"desktop engine was killed"));if(n.signal?.aborted)return Promise.reject(new wt("Cancelled",`${e} was cancelled before it was sent`));let r=this.#z++,{promise:i,resolve:o,reject:s}=Promise.withResolvers(),a={method:e,resolve:o,reject:s,release:()=>{},cancelled:void 0};this.#P.set(r,a);let{signal:l,timeoutMs:u}=n,c=()=>this.#A(r,new wt("Cancelled",`${e} was cancelled`)),d=void 0===u?void 0:setTimeout(()=>this.#A(r,new wt("Timeout",`${e} timed out after ${u} ms`)),u);return l?.addEventListener("abort",c,{once:!0}),a.release=()=>{clearTimeout(d),l?.removeEventListener("abort",c)},this.#E.write({id:r,method:e,params:t}),i}cancelHolds(){for(let[e,t]of this.#P)xt(t.method)&&this.#A(e,new wt("Cancelled","desktop session is closing"))}end(){this.#E.end()}kill(){this.#E.kill()}#A(e,t){let n=this.#P.get(e);if(void 0===n||void 0!==n.cancelled)return;n.release(),n.cancelled=t,this.#E.finishStartup();let r=setTimeout(()=>{this.#C(e),n.reject(new wt(t.code,`${t.message}; desktop engine restarted; captures and ax refs were reset`,!0)),this.#E.kill()},xt(n.method)?2500:750);n.release=()=>clearTimeout(r),this.#E.write({method:"$/cancel",params:{id:e}})}#C(e){let t=this.#P.get(e);return this.#P.delete(e),t?.release(),t}#I(e){let t=function(e){try{return JSON.parse(e)}catch(e){if(e instanceof SyntaxError)return;throw e}}(e);if(!at(t))return this.#E.kill(),void(this.#$=`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.#S.onNotification(t.method,t.params);let n="number"==typeof t.id?this.#C(t.id):void 0;if(void 0===n)return;if("engine.hello"===n.method&&this.#E.finishStartup(),void 0!==n.cancelled){let e=function(e,t){if(!xt(e)||!at(t)||"number"!=typeof t.code||"string"!=typeof t.message)return;if("Cancelled"===(at(t.data)?t.data.code:void 0)&&!t.message.includes(Ot))return;return new _t(e,{code:t.code,message:t.message,data:t.data})}(n.method,t.error);return void n.reject(e??n.cancelled)}if("result"in t)return void n.resolve(t.result);let{error:r}=t;at(r)&&"number"==typeof r.code&&"string"==typeof r.message?n.reject(new _t(n.method,{code:r.code,message:r.message,data:r.data})):n.reject(new wt("Internal",`desktop engine sent a malformed reply to ${n.method}`))}#T(e,t){let n=void 0===this.#$?t:void 0;this.#$??=e;let r=n??new wt("Closed",this.#$);for(let e of[...this.#P.keys()]){let t=this.#C(e);void 0!==t?.cancelled&&(t.cancelled.cause=r),t?.reject(t.cancelled??r)}this.#S.onExit()}}var xt=e=>"holdKeys"===e||"holdMouse"===e;var Ot="input release also failed";var $t={id:"string",name:"string",x:"number",y:"number",width:"number",height:"number",scale:"number",pixelX:"number",pixelY:"number",pixelWidth:"number",pixelHeight:"number",isPrimary:"boolean"},Et={id:"string",title:"string",app:"string",pid:"number?",x:"number",y:"number",width:"number",height:"number",focused:"boolean",elevated:"boolean?"},St={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"},Pt={title:"string",enabled:"boolean",checked:"boolean",hasSubmenu:"boolean",shortcut:"string?"},zt={mode:"string",data:"string?",mimeType:"string?",artifactPath:"string?",width:"number",height:"number",sourceWidth:"number",sourceHeight:"number",coordinateWidth:"number?",coordinateHeight:"number?",scale:"number",target:"string",frameId:"string",note:"string?"},It=e=>lt(e,$t),Tt=e=>lt(e,Et),At=e=>lt(e,St)&&(void 0===e.actions||null===e.actions||ut(e.actions)),Ct=e=>lt(e,Pt)&&ut(e.path),Rt=e=>lt(e,zt)&&(null==e.region||lt(e.region,{x:"number",y:"number",width:"number",height:"number"})),Nt=e=>Rt(e)&&"number"==typeof e.coordinateWidth&&"number"==typeof e.coordinateHeight&&null!=e.region,jt=e=>Rt(e)&&"number"==typeof e.coordinateWidth&&"number"==typeof e.coordinateHeight&&lt(e,{ax:"string",nodeCount:"number",truncated:"boolean"}),Mt=e=>at(e)&&"string"==typeof e.text,Ut=e=>Array.isArray(e)&&e.every(e=>ut(e)&&2===e.length);function Lt(e){return t=>Array.isArray(t)&&t.every(e)}function Dt(e){return t=>null===t||e(t)}function Zt(e,t,n){if(!n(t))throw new wt("Internal",`desktop engine sent a malformed ${e} result`);return t}async function Ft(e,t,n){try{await e.call(t,n)}catch(e){if(e instanceof _t&&-32601===e.rpcCode)throw new Ge("unavailable",`${t} is unavailable in this desktop engine; update the engine for bounded holds`);throw e}}async function Jt(e,t,n={},r){let{snapshot:i}=e.context,o={maxWidth:i.captureMaxWidth,maxHeight:i.captureMaxHeight,maxBytes:i.captureMaxBytes},s=void 0===r?"capture":"captureRegion",a=void 0===r?{target:t,caps:o}:{target:t,caps:o,region:r,frameId:n.frameId},l=Zt(s,await e.call(s,a),void 0===r?Rt:Nt);return qt(e,l,n)}function qt(e,t,n={}){let{output:r,screenshots:i}=e.context,o=t.artifactPath??void 0;void 0!==o&&i.push({path:o,width:t.width,height:t.height,sourceWidth:t.sourceWidth,sourceHeight:t.sourceHeight,target:t.target}),!0!==n.silent&&(r.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}`:"",i=null==e.region?"":` zoom; input coordinates remain ${e.coordinateWidth??e.width}x${e.coordinateHeight??e.height}`;return`screenshot ${e.target} ${t}${n}${r}${i}`}(t)),"artifact-only"!==t.mode&&t.data&&t.mimeType?r.image(t.data,t.mimeType):r.text(t.note??"screenshot is available only as the artifact above"));let{width:s,height:a,sourceWidth:l,sourceHeight:u,scale:c,frameId:d}=t,p=t.coordinateWidth??s,h=t.coordinateHeight??a;return{target:t.target,frameId:d,width:s,height:a,sourceWidth:l,sourceHeight:u,coordinateWidth:p,coordinateHeight:h,...null==t.region?{}:{region:t.region},scale:c,...void 0===o?{}:{path:o}}}function Vt(e){if(!Number.isFinite(e)||e<0||e>100)throw new Ge("assertion","hold duration must be finite seconds in 0..=100")}function Wt(e={}){let{button:t,count:n,modifiers:r,delivery:i}=e;return{button:t,count:n,modifiers:r,deliveryMode:i}}function Ht(e){return"string"!=typeof e?e:e.split("+").map(e=>e.trim()).filter(e=>e.length>0)}function Kt(e,t,n,r){return e(t,async({call:e})=>{await e(n,r)})}class Bt{#R;#N;constructor(e,t,n){this.#R=t,this.#N=Ye(e,n)}screenshot(e){return this.#N("screenshot",t=>Jt(t,this.#R,e))}zoom(e,t){return this.#N("zoom",n=>Jt(n,this.#R,t,e))}click(e,t,n){return Kt(this.#N,"click","click",{target:this.#R,x:e,y:t,opts:Wt(n)})}doubleClick(e,t,n){let r=Wt({...n,count:2});return Kt(this.#N,"doubleClick","click",{target:this.#R,x:e,y:t,opts:r})}move(e,t){return Kt(this.#N,"move","moveMouse",{target:this.#R,x:e,y:t})}drag(e,t){let n=e.map(([e,t])=>({x:e,y:t}));return Kt(this.#N,"drag","drag",{target:this.#R,path:n,opts:Wt(t)})}scroll(e,t,n={}){let{dx:r=0,dy:i=0}=n,o={target:this.#R,x:e,y:t,dx:r,dy:i,opts:Wt(n)};return Kt(this.#N,"scroll","scroll",o)}type(e,t){return Kt(this.#N,"type","typeText",{target:this.#R,text:e,opts:Wt(t)})}press(e,t){let n={target:this.#R,keys:Ht(e),opts:Wt(t)};return Kt(this.#N,"press","keyChord",n)}holdKeys(e,t){return this.#N("holdKeys",async n=>{if(Vt(t?.duration),!Array.isArray(e)||0===e.length)throw new Ge("assertion","held keys must not be empty");await Ft(n,"holdKeys",{target:this.#R,keys:e,duration:t.duration,opts:Wt(t)})})}holdMouse(e,t,n){return this.#N("holdMouse",async r=>{Vt(n?.duration),await Ft(r,"holdMouse",{target:this.#R,x:e,y:t,duration:n.duration,button:n.button,keys:n.keys,frameId:n.frameId,opts:Wt(n)})})}}class Gt extends Bt{id;app;title;pid;bounds;focused;#N;constructor(e,t){super(e,t.id,q),this.#N=Ye(e,q),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 Kt(this.#N,"raise","raiseWindow",{windowId:this.id})}menu={items:e=>this.#N("menu.items",async({call:t})=>Zt("menus.items",await t("menus.items",{windowId:this.id,path:[...e??[]]}),Lt(Ct))),select:(e,t)=>Kt(this.#N,"menu.select","menus.select",{windowId:this.id,path:[...e],...void 0===t?.delivery?{}:{deliveryMode:t.delivery}})};ax(e){return this.#N("ax",async({call:t})=>Zt("ax.snapshot",await t("ax.snapshot",{target:this.id,opts:e}),Mt).text)}observe(e){return this.#N("observe",t=>async function(e,t,n={}){let r,{snapshot:i,output:o}=e.context,s={maxWidth:i.captureMaxWidth,maxHeight:i.captureMaxHeight,maxBytes:i.captureMaxBytes},{all:a,maxDepth:l,maxNodes:u}=n;try{r=await e.call("observe",{target:t,caps:s,ax:{all:a,maxDepth:l,maxNodes:u}})}catch(e){if(e instanceof _t&&-32601===e.rpcCode)throw new Ge("unavailable","observe is unavailable in this desktop engine; update the engine to use atomic observation");throw e}let c=Zt("observe",r,jt),d=qt(e,c,n);return!0!==n.silent&&o.text(c.ax),{...d,ax:c.ax,nodeCount:c.nodeCount,truncated:c.truncated}}(t,this.id,e))}find(e){return this.#N("find",async t=>Zt("ax.query",await t.call("ax.query",{target:this.id,query:e}),Lt(At)).map(e=>new Yt(t,e)))}ref(e){return this.#N("ref",t=>Xt(t,e))}}async function Xt(e,t){return new Yt(e,Zt("ax.node",await e.call("ax.node",{ref:t}),At))}class Yt{ref;role;nativeRole;title;description;enabled;focused;childCount;#N;constructor(e,t){this.#N=Ye(e,V),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}#j(e,t,n){return this.#N(e,async({call:e})=>{await e(t,{ref:this.ref,...n})})}#M(e,t){return this.#N(e,async({call:e})=>t(Zt("ax.node",await e("ax.node",{ref:this.ref}),At)))}value(){return this.#M("value",e=>e.value??void 0)}setValue(e){return this.#j("setValue","ax.setValue",{value:e})}bounds(){return this.#M("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.#N("attributes",async({call:e})=>Object.fromEntries(Zt("ax.attributes",await e("ax.attributes",{ref:this.ref}),Ut)))}actions(){return this.#M("actions",e=>e.actions??[])}perform(e){return this.#j("perform","ax.perform",{action:e})}press(){return this.#j("press","ax.perform",{action:"press"})}click(e){return this.#j("click","ax.click",{opts:Wt(e)})}focus(){return this.#j("focus","ax.focus",{})}parent(){return this.#N("parent",async e=>{let t=Zt("ax.parent",await e.call("ax.parent",{ref:this.ref}),Dt(At));return null===t?null:new Yt(e,t)})}children(){return this.#N("children",async e=>Zt("ax.children",await e.call("ax.children",{ref:this.ref}),Lt(At)).map(t=>new Yt(e,t)))}}function Qt(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 en(e){let t=Ye(e,F),n=async({call:e})=>Zt("windows",await e("windows",{}),Lt(Tt)),r=async(t,n)=>{let r=Zt(t,await e.call(t,n),Dt(At));return null===r?null:new Yt(e,r)},i=new Bt(e,"desktop",F);return{capabilities:()=>t("capabilities",async({call:e})=>{let t=Zt("capabilities",await e("capabilities",{}),pt);return{...t,cursorOverlay:t.cursorOverlay??!1}}),displays:()=>t("displays",async({call:e})=>Zt("displays",await e("displays",{}),Lt(It))),display:n=>t("display",async()=>{if("string"!=typeof n||0===n.length)throw new Ge("assertion","display requires an id, 'active', or 'all'");return Object.assign(new Bt(e,`display:${n}`,J),{id:n})}),windows:e=>t("windows",async t=>(await n(t)).filter(t=>Qt(t,e))),window:r=>t("window",async t=>{let i=(await n(t)).filter(e=>"string"==typeof r?e.id===r:Qt(e,r)),[o,...s]=i;if(void 0===o)throw new Ge("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 Ge("window",`multiple windows match ${JSON.stringify(r)}:\n${e.join("\n")}`)}return new Gt(e,o)}),focusedWindow:()=>t("focusedWindow",async t=>{let r=(await n(t)).find(e=>e.focused);return void 0===r?null:new Gt(e,r)}),screenshot:i.screenshot.bind(i),zoom:i.zoom.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),holdKeys:i.holdKeys.bind(i),holdMouse:i.holdMouse.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=>Xt(t,e)),clipboard:{read:()=>t("clipboard.read",async({call:e})=>Zt("clipboard.read",await e("clipboard.read",{}),Mt).text),write:e=>t("clipboard.write",async({call:t})=>{await t("clipboard.write",{text:e})})},control:on(e,t)}}var tn=5e3,nn=3e3;function rn(e){return at(e)&&"boolean"==typeof e.active}function on(e,t){return{acquire:n=>t("control.acquire",async({context:t,call:r})=>{let i="string"==typeof n?.reason?n.reason.trim():"";if(0===i.length)throw new Ge("assertion","control.acquire requires a non-empty reason");let o=Zt("control.state",await r("control.state",{}),rn);if(o.active)return o;let s=e.confirmControl;if(void 0===s)return{active:!1};let a=Math.max(0,t.deadline-Date.now()-tn);if(a<nn)throw new Ge("assertion","control.acquire needs at least 8 s of run time left (time for the human to answer, then to act); call it earlier or give the run a longer timeout");let l=await s(i,t.signal,a);return t.signal.throwIfAborted(),!0!==l?{active:!1}:Zt("control.grant",await r("control.grant",{reason:i,confirmationId:Qe()}),rn)}),release:()=>t("control.release",async({call:e})=>{await e("control.revoke",{})}),state:()=>t("control.state",async({call:e})=>Zt("control.state",await e("control.state",{}),rn))}}import{randomUUID as sn}from"node:crypto";import{format as an}from"node:util";import ln from"node:vm";function un(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 cn(e,t){return async(n,r={})=>{if("number"==typeof n)return un(n,e);if("function"!=typeof n)throw new Ge("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 Ge("wait",`wait(predicate) timed out after ${n} ms; the predicate never returned truthy`);await un(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 dn="computer-run.js";function pn(e){return at(e)&&"ERR_SCRIPT_EXECUTION_TIMEOUT"===e.code}function hn(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 fn(e,t){let{code:n,snapshot:r,timeoutMs:i}=e,o=sn(),s=new AbortController,{signal:a}=s,l=Date.now()+i,u=e=>s.abort(e),c=()=>new Ge("timeout",`computer run timed out after ${i} ms`),d=setTimeout(()=>u(c()),i),p=()=>u(new Ge("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 Xe,screenshots:[],deadline:l},g=new ln.Script(""),y=()=>{if(!a.aborted)try{g.runInContext(_,{timeout:Math.max(1,l-Date.now())})}catch(e){u(pn(e)?c():e)}},v=e=>{let t=()=>setImmediate(y);return e.then(t,t),e},b=cn(a,i),w=(...e)=>m.output.text(an(...e)),_=ln.createContext({desktop:en({context:m,call:(e,n)=>t.service.call(e,n,{signal:a}),resume:v,...void 0===t.confirmControl?{}:{confirmControl:t.confirmControl}}),wait:(e,t)=>v(b(e,t)),assert:(e,t)=>{if(!e)throw new Ge("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:dn,microtaskMode:"afterEvaluate"});try{a.throwIfAborted();let e=new ln.Script(`((run) => (run.catch(() => undefined), run))((async () => {\n${n}\n})())`,{filename:dn,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:hn(t),screenshots:[...m.screenshots],audit:[...h]}}catch(e){let n=pn(e)?c():e;throw t.service.revokeControl().catch(e=>t.service.reportError(e)),n}finally{clearTimeout(d),e.signal?.removeEventListener("abort",p),f(),a.aborted||s.abort(new Ge("ended","computer run has ended"))}}class mn extends Error{method;constructor(e,t){super(`desktop engine notification ${JSON.stringify(e)} ${t}`),this.name="DesktopNotificationError",this.method=e}}function gn(e,t){return e.add(t),()=>{e.delete(t)}}class yn{#U=new Set;#L=new Set;#D=new Set;onAudit(e){return gn(this.#U,e)}onStopPathChange(e){return gn(this.#L,e)}onError(e){return gn(this.#D,e)}emitError(e){for(let t of this.#D)t(e)}dispatch(e,t){let n=Q.find(t=>t===e);void 0!==n?this.#Z(n,t):this.emitError(new mn(e,"is not part of the engine protocol"))}#Z(e,t){switch(e){case"audit":if(lt(n=t,st)&&ct(n.action,et)&&(void 0===n.code||null===n.code||ct(n.code,tt))&&(void 0===n.keys||null===n.keys||ut(n.keys)))for(let e of this.#U)e(t);else this.emitError(new mn(e,"is malformed"));return;case"stopPath.changed":if(dt(t))for(let e of this.#L)e(t);else this.emitError(new mn(e,"is malformed"));return;case"engine.log":return;default:!function(e){throw Error(`unhandled engine notification ${JSON.stringify(e)}`)}(e)}var n}}class vn{#F=0;#J=0;#q=0;#V=!1;get possiblyLive(){return this.#J>this.#q}get automaticLive(){return this.possiblyLive&&this.#V}async grant(e,t,n=!1){if(t)return e();this.#F+=1;let r=this.#F,i={possiblyLive:this.#J,automatic:this.#V};this.#J=r,this.#V=n;try{return await e()}catch(e){throw e instanceof _t&&this.#J===r&&(this.#J=i.possiblyLive,this.#V=i.automatic),e}}async revoke(e){let t=this.#F,n=await e();return this.#q=Math.max(this.#q,t),n}}function bn(e,t,n){return new Promise((r,i)=>{let o=setTimeout(()=>i(new wt("Timeout",n)),t);e.then(e=>{clearTimeout(o),r(e)},e=>{clearTimeout(o),i(e)})})}import{randomUUID as wn}from"node:crypto";var _n=new Set(["click","moveMouse","drag","scroll","typeText","keyChord","holdKeys","holdMouse"]);function kn(e){return e instanceof _t&&null!==e.data&&"code"in e.data&&"ControlRequired"===e.data.code}function xn(e,t){if(!0===t.signal?.aborted)throw new wt("Cancelled",`${e} was cancelled`)}class On{#W;#H;constructor(e,t){this.#W=e,this.#H=t}async fence(e){this.#W.automaticLive&&!this.#H()&&await this.#K(e)}async send(e,t,n,r){let i=!1;for(;;){xn(t,r);let o=this.#H();if(o||!this.#W.automaticLive)if(!o||this.#W.possiblyLive){try{return await e.rpc.request(t,n,r)}catch(e){if(!o||i||!kn(e)||!0===r.signal?.aborted)throw e}i=!0,await this.#B(e,r)}else await this.#B(e,r);else await this.#K(e)}}#K(e){return this.#W.revoke(()=>e.rpc.request("control.revoke",{},{timeoutMs:2e3}))}async#B(e,t){let n={reason:"full access: the session's permission preset consents to desktop input",confirmationId:wn()},r=t.signal;await this.#W.grant(()=>e.rpc.request("control.grant",n,void 0===r?{}:{signal:r}),!1,!0)}}class $n{#G;#X=new yn;#Y=Promise.resolve();#Q;#ee;#W=new vn;#te;#ne=!1;constructor(e={}){this.#G=e.createChild??yt(),this.#te=new On(this.#W,e.fullAccess??(()=>!1)),this.#X.onStopPathChange(e=>{e.suspended&&(this.#ne=!0)})}onAudit(e){return this.#X.onAudit(e)}onStopPathChange(e){return this.#X.onStopPathChange(e)}onError(e){return this.#X.onError(e)}open(e){return this.#re(async()=>{let t={...e,showCursor:e.showCursor??!0};this.#ee={params:t,chord:this.#ee?.chord};let n=this.#Q;return!0===n?.rpc.alive?this.#ie(n,t):(void 0!==n&&this.#oe(n),(await this.#se(this.#ee)).capabilities)})}ensureStopPath(e){return this.#re(async()=>{let t=await this.#ae();if(t.armedChord===e)return this.#L(t,"stopPath.status",{});let n=await this.#L(t,"stopPath.start",{chord:e});return t.armedChord=e,void 0!==this.#ee&&(this.#ee.chord=e),n})}async call(e,t,n={}){let r=await this.#le();await this.#te.fence(r);let i=()=>r.rpc.request(e,t,n);return"control.grant"===e?this.#W.grant(i,!0===n.signal?.aborted):"control.revoke"===e?this.#W.revoke(i):function(e,t){if(!_n.has(e)||"object"!=typeof t||null===t)return!1;let n=Reflect.get(t,"target");return"string"==typeof n&&function(e){return"desktop"===e.replace(/[A-Z]/g,e=>e.toLowerCase())||e.startsWith("display:")}(n)}(e,t)?this.#te.send(r,e,t,n):i()}reportError(e){this.#X.emitError(e instanceof Error?e:Error(String(e)))}revokeControl(){let e=this.#Q;return void 0!==e&&e.rpc.alive&&this.#W.possiblyLive?this.#W.revoke(()=>e.rpc.request("control.revoke",{},{timeoutMs:2e3})).then(()=>{},e=>{if(!(e instanceof wt||e instanceof _t))throw e;this.#X.emitError(e)}):Promise.resolve()}async capabilities(){let e=await this.call("capabilities",{},{timeoutMs:1e4});if(!pt(e))throw En("capabilities");return{...e,cursorOverlay:e.cursorOverlay??!1}}async stopPathStatus(){return this.#L(await this.#le(),"stopPath.status",{})}async stop(){return this.#L(await this.#le(),"stopPath.stop",{source:"host-relay"})}async resume(){let e=await this.#le(),t=await this.#L(e,"stopPath.resume",{token:e.resumeToken});return t.suspended||(this.#ne=!1),t}close(){return this.#re(async()=>{this.#ee=void 0;let e=this.#Q;if(void 0===e)return;if(this.#oe(e),!e.rpc.alive)return;try{await bn((async()=>{e.rpc.cancelHolds(),await e.rpc.request("session.close",{}),e.rpc.end(),await e.rpc.exited})(),3e3,"Timed out closing desktop engine")}finally{e.rpc.kill()}})}#re(e){let t=this.#Y.then(e);return this.#Y=t.then(()=>{},()=>{}),t}#le(){let e=this.#Q;return!0===e?.rpc.alive?Promise.resolve(e):this.#re(()=>this.#ae())}async#ae(){let e=this.#Q;if(!0===e?.rpc.alive)return e;if(void 0!==e&&this.#oe(e),void 0===this.#ee)throw new wt("Closed","desktop session is not open");return(await this.#se(this.#ee)).connection}async#se(e){let t=new kt(await this.#G(),{onNotification:(e,t)=>this.#X.dispatch(e,t),onExit:()=>{this.#Q?.rpc===t&&this.#oe(this.#Q)}}),n={rpc:t,resumeToken:"",armedChord:void 0,heartbeat:void 0};try{let t=await bn(this.#ue(n,e),1e4,"Timed out starting desktop engine");return this.#Q=n,n.heartbeat=setInterval(()=>this.#ce(n),500),{connection:n,capabilities:t}}catch(e){throw t.kill(),e}}async#ue(e,t){let n=function(e){if(at(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 En("engine.hello");if(n.abi!==Y||n.protocolVersion!==X)throw new te(e.rpc.enginePath,n);let r=await this.#ie(e,t.params);return void 0!==t.chord&&(await this.#L(e,"stopPath.start",{chord:t.chord}),e.armedChord=t.chord),this.#ne&&await this.#L(e,"stopPath.stop",{source:"host-relay"}),r}async#ie(e,t){let n=function(e){if(at(e)&&"string"==typeof e.resumeToken&&pt(e.capabilities))return{capabilities:{...e.capabilities,cursorOverlay:e.capabilities.cursorOverlay??!1},resumeToken:e.resumeToken}}(await e.rpc.request("session.open",t,{timeoutMs:1e4}));if(void 0===n)throw En("session.open");return e.resumeToken=n.resumeToken,n.capabilities}async#L(e,t,n){let r=await e.rpc.request(t,n);if(!dt(r))throw En(t);return r.suspended&&(this.#ne=!0),r}#ce(e){e.rpc.request("stopPath.heartbeat",{}).catch(e=>{if(!(e instanceof wt&&"Closed"===e.code)){if(!(e instanceof wt||e instanceof _t))throw e;this.#X.emitError(e)}})}#oe(e){clearInterval(e.heartbeat),this.#Q===e&&(this.#Q=void 0)}}function En(e){return new wt("Internal",`desktop engine sent a malformed ${e} result`)}var Sn={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:R,executionMode:"sequential"},Pn={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",ControlRequired:"COMPUTER_CONTROL_REQUIRED",InputBusy:"COMPUTER_INPUT_BUSY",Cancelled:"COMPUTER_CANCELLED",Timeout:"COMPUTER_CANCELLED",timeout:"COMPUTER_CANCELLED",aborted:"COMPUTER_CANCELLED"};function zn(e){return{code:"COMPUTER_LAUNCH_CONTEXT_REQUIRED",message:e.message,reason:e.reason}}function In(e,t,n,r){let i=e.startsWith("COMPUTER_")?e:Pn[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.";case"COMPUTER_CONTROL_REQUIRED":return"Call desktop.control.acquire({ reason }) in computer run code (computer.control.acquire in an eval kernel) and let the human confirm before acting in the foreground; do not retry this action until that returns { active: true }.";case"COMPUTER_INPUT_BUSY":return"Another session holds the foreground control grant; it is never stolen, so continue in the background or retry once that session releases it.";default:return}}(i,n);return{code:i,message:`${i}: ${t}${void 0===o?"":` ${o}`}`,...r??{}}}import{Type as Tn}from"typebox";var An=Tn.Object({method:Tn.String({description:"desktop helper name, e.g. screenshot, window, click, clipboard.read"}),args:Tn.Optional(Tn.Array(Tn.Unknown(),{description:"positional helper arguments"}))},{additionalProperties:!1}),Cn=Tn.Number({minimum:1,maximum:600,description:"run: budget in seconds (default 60)"}),Rn=[Tn.Object({action:Tn.Literal("call"),chain:Tn.Array(An,{description:"one desktop helper call, optionally followed by one call on the window/element it returns"})},{additionalProperties:!1}),Tn.Object({action:Tn.Literal("run"),code:Tn.String({description:"JavaScript async function body; `desktop`, `wait`, `assert`, `tool` in scope; `return` sets the value"}),read_only:Tn.Optional(Tn.Boolean({description:"true = inspection only: screenshots and AX reads, input/mutation blocked"})),timeout:Tn.Optional(Cn)},{additionalProperties:!1}),Tn.Object({action:Tn.Literal("capabilities")},{additionalProperties:!1}),Tn.Object({action:Tn.Literal("close")},{additionalProperties:!1})],Nn=Tn.Union([...Rn]),jn=Tn.Object({action:Tn.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:Tn.Optional(Tn.Array(An,{description:"call (required): one desktop helper call, optionally followed by one call on the window/element it returns"})),code:Tn.Optional(Tn.String({description:"run (required): JavaScript async function body; `desktop`, `wait`, `assert`, `tool` in scope; `return` sets the value"})),read_only:Tn.Optional(Tn.Boolean({description:"run: true = inspection only: screenshots and AX reads, input/mutation blocked"})),timeout:Tn.Optional(Cn)},{additionalProperties:!1});import{Check as Mn}from"typebox/value";import{readFileSync as Un}from"node:fs";import{dirname as Ln,join as Dn}from"node:path";import{fileURLToPath as Zn}from"node:url";var Fn,Jn=["COMPUTER_PRELUDE_JAVASCRIPT","COMPUTER_PRELUDE_PYTHON","COMPUTER_DECLARATIONS","COMPUTER_DOCUMENTATION","COMPUTER_SAFETY"],qn=Dn(Ln(Zn(import.meta.url)),"assets.generated.json");function Vn(){if(void 0===Fn){let e=JSON.parse(Un(qn,"utf8"));Fn=function(e){let t=e&&"object"==typeof e?e:void 0,n=Jn.filter(e=>"string"!=typeof t?.[e]);if(n.length>0)throw Error(`senpi-desktop-prelude asset JSON is malformed at ${qn}: missing ${n.join(", ")}`);return e}(e)}return Fn}var Wn={get javascript(){return Vn().COMPUTER_PRELUDE_JAVASCRIPT},get python(){return Vn().COMPUTER_PRELUDE_PYTHON},get declarations(){return Vn().COMPUTER_DECLARATIONS},get documentation(){return Vn().COMPUTER_DOCUMENTATION},get safety(){return Vn().COMPUTER_SAFETY},exports:["computer"],methodAllowlist:["actions","attributes","ax","bounds","capabilities","children","click","clipboard.read","clipboard.write","control.acquire","control.release","control.state","display","displays","doubleClick","drag","elementAt","find","focus","focusedElement","focusedWindow","holdKeys","holdMouse","move","observe","menu.items","menu.select","parent","perform","press","raise","ref","screenshot","scroll","setValue","type","value","window","windows","zoom"]},Hn={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:Wn.safety.split("\n").filter(e=>e.startsWith("- ")).map(e=>e.slice(2)),kernelPrelude:Wn,parameters:jn,executionMode:"sequential"},Kn=w(Rn);function Bn(e,t){return"string"==typeof e?e:JSON.stringify(e,(e,n)=>"ax"===e&&"string"==typeof n&&t.has(n)?"[shown above]":n,2)??String(e)}function Gn(e){return"string"==typeof e?e:JSON.stringify(e,null,2)??String(e)}function Xn(e,t){return{content:[{type:"text",text:void 0===e?t:Gn(e)}],details:{value:e}}}async function Yn(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=e.confirmControl,u=await fn({code:n.code,snapshot:s,timeoutMs:a,...void 0===r?{}:{signal:r}},{service:i.service,executeTool:o,...void 0===l?{}:{confirmControl:(e,n,r)=>l({context:t,reason:e,signal:n,budgetMs:r})}}),c=[...u.displays],d=new Set(c.flatMap(e=>"text"===e.type&&""!==e.text?[e.text]:[]));return void 0!==u.returnValue&&c.push({type:"text",text:Bn(u.returnValue,d)}),0===c.length&&c.push({type:"text",text:"Done."}),{content:c,details:{value:u.returnValue,readOnly:n.readOnly,screenshots:u.screenshots,audit:u.audit}}}function Qn(e){let{handle:t}=e,n=(t,n,r)=>Yn(e,t,n,r);return{...Hn,async execute(e,r,i,o,s){let a=function(e){if(Mn(Nn,e))return e;throw _(Kn,e,"computer")}(r);switch(a.action){case"call":{let e=G(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 er(n(s,{code:r,readOnly:e,timeoutSeconds:60},i),t)}case"run":{let e=a.timeout??60;return er(n(s,{code:a.code,readOnly:!0===a.read_only,timeoutSeconds:e},i),t)}case"capabilities":return er((async()=>(await t.activate(s),Xn(await t.service.capabilities(),"capabilities unavailable")))(),t);case"close":return await t.close(),Xn(void 0,"Closed the desktop session.");default:return function(e){throw TypeError(`unhandled computer action ${JSON.stringify(e)}`)}(a)}}}}async function er(e,t){try{return await e}catch(e){if(e instanceof D){let t=zn(e);return{content:[{type:"text",text:e.message}],details:{value:t,isError:!0},isError:!0}}if(!(e instanceof _t)||null===e.data||!("code"in e.data)||"PermissionDenied"!==e.data.code&&"ControlRequired"!==e.data.code&&"InputBusy"!==e.data.code&&"Suspended"!==e.data.code)throw e;let n=In(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},isError:!0}}}function tr(e){let t=null;return{...Sn,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(z,e));if(e>=0)throw _(N,t[e],`computer_actions actions[${e}]`)}throw _(j,e,"computer_actions")}(r)}catch(e){if(!(e instanceof b))throw e;let t=In(e.code,e.reason,l);return{content:[{type:"text",text:t.message}],details:{value:t,isError:!0},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 Yn(e,s,{code:p,readOnly:d,timeoutSeconds:c},i)}catch(e){if(!(e instanceof Error))throw e;if(e instanceof D){let t=zn(e);return{content:[{type:"text",text:t.message}],details:{value:t,isError:!0},isError:!0}}let t=e instanceof _t&&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=In(String(n),e.message,l,t?.permission);return{content:[{type:"text",text:r.message}],details:{value:r,isError:!0},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=In(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},isError:!0}}}}import{Type as nr}from"typebox";import{Check as rr,Errors as ir}from"typebox/value";nr.Object({enabled:nr.Optional(nr.Boolean({description:"Register the computer tool (experimental; default: host supported)"})),showCursor:nr.Optional(nr.Boolean({default:!0,description:"Show the display-only virtual cursor on macOS"})),display:nr.Optional(nr.String({description:"`active` (default) follows the focused monitor; `all` composites every display; otherwise a display id"})),maxWidth:nr.Optional(nr.Integer({minimum:1,default:3840})),maxHeight:nr.Optional(nr.Integer({minimum:1,default:2400})),screenshotMaxBytes:nr.Optional(nr.Integer({minimum:1,default:5e6})),stopHotkey:nr.Optional(nr.String({minLength:1,description:"Stop chord, e.g. ctrl+alt+shift+escape"})),allowHostRelayOnlyStop:nr.Optional(nr.Boolean({default:!1})),macosCanary:nr.Optional(nr.Union([nr.Literal("session"),nr.Literal("off")],{default:"session"})),auditLog:nr.Optional(nr.Object({enabled:nr.Optional(nr.Boolean({default:!0}))},{additionalProperties:!1})),screenshotGc:nr.Optional(nr.Object({enabled:nr.Optional(nr.Boolean({default:!0})),staleMs:nr.Optional(nr.Integer({minimum:0,default:432e5})),scanIntervalMs:nr.Optional(nr.Integer({minimum:0,default:18e5}))},{additionalProperties:!1})),enginePath:nr.Optional(nr.String({minLength:1,description:"Override the located engine binary"})),cuaAdapter:nr.Optional(nr.Boolean({default:!1,description:"Also register computer_actions (OpenAI computer-use actions)"}))},{additionalProperties:!1});var or=(e,t)=>{let n=setTimeout(e,t);return()=>clearTimeout(n)};import{readFileSync as sr}from"node:fs";import{dirname as ar,join as lr}from"node:path";import{accessSync as ur,constants as cr,existsSync as dr}from"node:fs";import{homedir as pr}from"node:os";import{join as hr}from"node:path";function fr(e,t,n,r=e=>Se(e,n)){let i={host:t,attemptedPaths:[e]};if(!dr(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:mr(i,t,`${e}: not executable (expected a .exe file)`);try{return void ur(e,cr.X_OK)}catch(n){if(!(n instanceof Error&&"code"in n))throw n;return mr(i,t,`${e}: not executable (chmod +x)`)}}function mr(e,t,n){return{...e,code:"native-unavailable",message:`No senpi-desktop-engine binary is available for ${t}.`,cause:n}}function gr(e,t,n,r={}){let i=r.platform??process.platform,o=_e(i,r.arch,r.libc);if(void 0!==e){let t=fr(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=$e(s);if(null!==a.path){let e=Oe(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=He({host:o,version:n,cacheDir:hr(t.HOME??pr(),".omo","cache","senpi-desktop-engine")});if(null!==e.path)return{path:e.path,source:"cache"}}return null===me(o)?{diagnostic:a.diagnostic}:{notInstalled:a.diagnostic}}function yr(e,t){let n;try{n=JSON.parse(sr(lr(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 vr(e){let t=e.OMO_PACKAGE_DIR?.trim();if(t){let e=yr(t,["omo"]);if(void 0!==e)return e}let n=e.OMO_BIN?.trim();return n?yr(ar(ar(n)),["omo-ai"]):void 0}function br(e=process.env,t){return n=>{if(void 0!==n)return function(e){let t=_e(),n=fr(e,t,process.platform);return void 0!==n?()=>{throw new gt(n)}:yt(e)}(n);let r=vr(e);return void 0!==r?function(e){let t=e.acquire??Ke,n=e.spawnEngine??vt;return async()=>{let r=await Be({version:e.version,host:e.host??_e()},n,t);if(null===r.path)throw new gt(r.diagnostic);return r.value}}({version:r}):void 0===t?yt():()=>{let e=$e(t);if(null===e.path)throw new gt(e.diagnostic);return yt(e.path)()}}}function wr(e,t,n={}){let r=vr(t),i=gr(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=me(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 _r extends Error{diagnostic;constructor(e,t){super(`Desktop engine unavailable (${e}): ${t.message}`,{cause:t}),this.name="ComputerEngineUnavailableError",this.diagnostic=e}}function kr(e){return e instanceof gt?e.diagnostic.code:e instanceof te?"abi-mismatch":e instanceof D?e.code:void 0}class xr extends $n{#de="not started";#pe;#he;constructor(e={}){super(e),this.#pe=e.onError,this.#he=e.onPermissionRequired,this.onError(e=>this.#fe(e))}get engineState(){return this.#de}async open(e){try{let t=await super.open(e);return this.#de="ready",t}catch(e){if(!(e instanceof Error))throw e;if(this.#fe(e),e instanceof D)throw e;let t=kr(e);if(void 0===t)throw e;throw this.#de=t,new _r(t,e)}}async call(e,t,n={}){return this.#me(super.call(e,t,n))}ensureStopPath(e){return this.#me(super.ensureStopPath(e))}stopPathStatus(){return this.#me(super.stopPathStatus())}stop(){return this.#me(super.stop())}resume(){return this.#me(super.resume())}async#me(e){try{let t=await e;return"not started"!==this.#de&&"launch-context-unavailable"!==this.#de||(this.#de="ready"),t}catch(e){if(!(e instanceof Error))throw e;throw this.#fe(e),e}}#fe(e){let t=kr(e);void 0!==t&&(this.#de=t),e instanceof _t&&null!==e.data&&"code"in e.data&&"PermissionDenied"===e.data.code&&null!=e.data.permission&&this.#he?.(e.data.permission),this.#pe?.(e)}}import{spawn as Or}from"node:child_process";import{createInterface as $r}from"node:readline";function Er(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 Sr(e,t="|"){return e.map(e=>Br(e)).join(t)}function Pr(e,t){return"bigint"==typeof t?t.toString():t}class zr{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 Ir(e){return new zr(e)}function Tr(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Ar(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Cr(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Rr(e){return Cr(e._zod.def)??e._zod.def.shape}function Nr(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return Ar(this,t,e),e},enumerable:!0,configurable:!0})}function jr(e,t,n){t in e?Ar(e,t,n):e[t]=n}function Mr(e,t,n,r){let i=Rr(t);for(let o of n){let n=Object.getOwnPropertyDescriptor(i,o);n.enumerable&&(n.get?Nr(e,o,()=>{let e=t._zod.def.shape[o];return r?r(e,o):e}):jr(e,o,r?r(n.value,o):n.value))}}function Ur(...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 Dr="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Zr(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Fr=Ir(()=>{if(Si.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Jr(e){if(!1===Zr(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!==Zr(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function qr(e){return Jr(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var Vr=new Set(["string","number","symbol"]);function Wr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hr(e,t,n){let r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function Kr(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 Br(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}var Gr={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]},Xr={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Yr(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 Qr(e,t){let n={};return Mr(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?Nr(e,n,()=>t[n]):jr(e,n,r.value))}}(n,t),n}function ei(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(Yr(t,n)):void 0,s={};return Mr(s,t,Reflect.ownKeys(Rr(t)),e&&((t,n)=>o&&!o.has(n)?t:new e({type:"optional",innerType:t}))),Hr(t,Ur(t._zod.def,{shape:s,checks:[]}))}function ti(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 ni(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 ri(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function ii(e){return"string"==typeof e?e:e?.message}function oi(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function si(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:ii(e.inst?._zod.def?.error?.(e))??ii(o?.(e))??ii(t?.error?.(e))??ii(n.customError?.(e))??ii(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 ai=/[\uD800-\uDBFF]/;function li(e){let t=e.length;if(!ai.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 ui(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function ci(...e){let[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}function di(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function pi(e,t,n){return di(e,t,n,!1)}function hi(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return di(this,n,r(this))},set(e){di(this,n,e)}})}return t}function fi(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return null==this?n:di(this,t,n.bind(this))},set(e){di(this,t,e)}})}var mi,gi=!1,yi={configurable:!0,get(){gi=!0}};function vi(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&mi!==e._zod?mi=void 0:(mi=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,yi);let e=gi;gi=!1;try{let r=n(this);return gi?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),gi=gi||e,r}catch(n){throw delete this[t],gi=gi||e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function bi(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 wi;function _i(e){let t=()=>e;return t["~constantCatch"]=!0,t}var ki={value:void 0,enumerable:!1},xi="captureStackTrace"in Error?Error:null;function Oi(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{ki.value=new i(r);try{Object.defineProperty(n,"_zod",ki)}finally{ki.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}):fi(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=xi;if(t){let n=t.stackTraceLimit;if("number"==typeof n){try{t.stackTraceLimit=0}catch{return xi=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 $i extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Ei extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(wi=globalThis).__zod_globalConfig??(wi.__zod_globalConfig={});var Si=globalThis.__zod_globalConfig;function Pi(e){return e&&Object.assign(Si,e),Si}var zi={get:function(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Pr,2)),e.message},set:function(e){this._zod.message=e},enumerable:!0,configurable:!0},Ii={value:void 0,enumerable:!1},Ti=new WeakSet([Object.prototype,Error.prototype]),Ai=(e,t)=>{e.name="$ZodError",Ii.value=t,Object.defineProperty(e,"issues",Ii),Ii.value=void 0,Object.defineProperty(e,"message",zi);let n=Object.getPrototypeOf(e);Ti.has(n)||(Ti.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})}}))},Ci=Oi("$ZodError",Ai);Oi("$ZodError",Ai,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 Ni(e,t){return{callee:t?.callee??e,Err:t?.Err}}var ji=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 $i;if(a.issues.length){let n=new(o?.Err??e)(a.issues.map(e=>si(e,s,Pi())));throw Dr(n,o?.callee??t),n}return a.value};return t},Mi=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=>si(e,s,Pi())));throw Dr(n,o?.callee??t),n}return a.value};return t},Ui=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 $i;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=>si(e,n,Pi()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}var Di=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}},Zi=Symbol.for("zod.compile.invalid"),Fi=Symbol.for("zod.compile.fallback"),Ji=(e,t,n)=>{let r=e._zod.bag.validator;if(void 0!==r){if(r(t)!==Zi)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[Fi]=!0,r=o({value:t,issues:[]},i)):r=e._zod.run({value:t,issues:[]},i);if(r instanceof Promise)throw new $i;return 0===r.issues.length}(e,t,n)};var qi=/^[cC][0-9a-z]{6,}$/,Vi=/^[0-9a-z]+$/,Wi=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Hi=/^[0-9a-vA-V]{20}$/,Ki=/^[A-Za-z0-9]{27}$/,Bi=/^[a-zA-Z0-9_-]{21}$/;var Gi=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Xi=/^([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})$/,Yi=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)$/,Qi=/^(?:[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 eo=/^(?:(?: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])$/,to=/^(([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}|:))$/,no=/^((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])$/,ro=/^(([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])$/,io=/^https?$/,oo=/^\+[1-9]\d{6,14}$/,so="(?:(?:\\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 ao=new RegExp(`^${so}$`);function lo(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 uo=/^[\s\S]{0,}$/,co=/^-?\d+(?:\.\d+)?$/,po=/^(?:true|false)$/i,ho=/^[^A-Z]*$/,fo=/^[^a-z]*$/,mo=Oi("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),go=e=>{let t=e.value;return!(n=t,null==n||void 0===t.length);var n},yo={number:"number",bigint:"bigint",object:"date"},vo=Oi("$ZodCheckLessThan",(e,t)=>{mo.init(e,t);let n=yo[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:yo[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})}}),bo=Oi("$ZodCheckGreaterThan",(e,t)=>{mo.init(e,t);let n=yo[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:yo[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})}}),wo=Oi("$ZodCheckMultipleOf",(e,t)=>{mo.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})}}),_o=Oi("$ZodCheckNumberFormat",(e,t)=>{mo.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[i,o]=Gr[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})}}),ko=Oi("$ZodCheckMaxLength",(e,t)=>{var n;mo.init(e,t),(n=e._zod.def).when??(n.when=go),e._zod.check=n=>{let r=n.value,i=r.length;if(("string"==typeof r&&i>t.maximum?li(r):i)<=t.maximum)return;let o=ui(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),xo=Oi("$ZodCheckMinLength",(e,t)=>{var n;mo.init(e,t),(n=e._zod.def).when??(n.when=go),e._zod.check=n=>{let r=n.value,i=r.length;if(("string"==typeof r&&i>=t.minimum&&i<2*t.minimum?li(r):i)>=t.minimum)return;let o=ui(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Oo=Oi("$ZodCheckLengthEquals",(e,t)=>{var n;mo.init(e,t),(n=e._zod.def).when??(n.when=go),e._zod.check=n=>{let r=n.value,i=r.length,o="string"==typeof r&&i>=t.length&&i<=2*t.length?li(r):i;if(o===t.length)return;let s=ui(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})}}),$o=Oi("$ZodCheckStringFormat",(e,t)=>{var n,r;mo.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=()=>{})}),Eo=Oi("$ZodCheckRegex",(e,t)=>{$o.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})}}),So=Oi("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=ho),$o.init(e,t)}),Po=Oi("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=fo),$o.init(e,t)}),zo=Oi("$ZodCheckIncludes",(e,t)=>{mo.init(e,t);let n=Wr(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})}}),Io=Oi("$ZodCheckStartsWith",(e,t)=>{mo.init(e,t);let n=new RegExp(`^${Wr(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})}}),To=Oi("$ZodCheckEndsWith",(e,t)=>{mo.init(e,t);let n=new RegExp(`.*${Wr(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})}}),Ao=Oi("$ZodCheckOverwrite",(e,t)=>{mo.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Co{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 Ro={major:4,minor:6,patch:5},No=Oi("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ro;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=ti(t);for(let s of n){if(s._zod.def.when){if(ni(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 $i;if(i||a instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await a,t.issues.length!==n&&(oi(t.issues,n,e),o||(o=ti(t,n)))});else{if(t.issues.length===n)continue;oi(t.issues,n,e),o||(o=ti(t,n))}}return i?i.then(()=>t):t},n=(n,r,o)=>{if(ti(n))return n.aborted=!0,n;let s=t(r,i,o);if(s instanceof Promise){if(!1===o.async)throw new $i;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 $i;return s.then(e=>t(e,i,o))}return t(s,i,o)}}},{get"~standard"(){return pi(this,"~standard",Mo(this))},set"~standard"(e){di(this,"~standard",e)}}),jo=(e,t)=>e.issues.length?{issues:e.issues.map(e=>si(e,t,Pi()))}:{value:e.value};function Mo(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return jo(r,n)}catch(e){}return async function(e,t){let n={async:!0};return jo(await e._zod.run({value:t,issues:[]},n),n)}(e,t)},vendor:"zod",version:1}}var Uo=Oi("$ZodString",(e,t)=>{No.init(e,t),e._zod.pattern=t.pattern??uo,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}}),Lo=Oi("$ZodStringFormat",(e,t)=>{$o.init(e,t),Uo.init(e,t)}),Do=Oi("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Xi),Lo.init(e,t)}),Zo=Oi("$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=Yi(e))}else t.pattern??(t.pattern=Yi());Lo.init(e,t)}),Fo=Oi("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Qi),Lo.init(e,t)});function Jo(e){try{return typeof URL<"u"&&"function"==typeof URL.canParse?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function qo(e,t){return"normalize"in t||"hostname"in t||"protocol"in t?function(e,t){if(!t.normalize&&t.protocol?.source===io.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):Jo(e)||2}var Vo=/[\t\n\r]/g;function Wo(e){return e.replace(Vo,"")}var Ho=Oi("$ZodURL",(e,t)=>{Lo.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=qo(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=Wo(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:Wo(r)))}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Ko=Oi("$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")),Lo.init(e,t)}),Bo=Oi("$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?Bi:(n=t.length,new RegExp(`^[a-zA-Z0-9_-]{${n}}$`))),Lo.init(e,t)}),Go=Oi("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=qi),Lo.init(e,t)}),Xo=Oi("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Vi),Lo.init(e,t)}),Yo=Oi("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Wi),Lo.init(e,t)}),Qo=Oi("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Hi),Lo.init(e,t)}),es=Oi("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ki),Lo.init(e,t)}),ts=Oi("$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=`${lo({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${lo({precision:e.precision})}`:n;return new RegExp(`^${so}T(?:${r})$`)}(t)),Lo.init(e,t)}),ns=Oi("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ao),Lo.init(e,t)}),rs=Oi("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${lo(t)}$`)),Lo.init(e,t)}),is=Oi("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Gi),Lo.init(e,t)}),os=Oi("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=eo),Lo.init(e,t)}),ss=/^[0-9a-fA-F:.]+$/;function as(e){return!!ss.test(e)&&Jo(`http://[${e}]`)}var ls=Oi("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=to),Lo.init(e,t),e._zod.check=n=>{as(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),us=Oi("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=no),Lo.init(e,t)});var cs=Oi("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ro),Lo.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)&&as(n)})(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function ds(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 ps=/^[0-9a-zA-Z+/]*={0,2}$/,hs=Oi("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ps),Lo.init(e,t),e._zod.check=n=>{ds(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),fs=/^[A-Za-z0-9_-]*$/;var ms=Oi("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=fs),Lo.init(e,t),e._zod.check=n=>{(function(e){if(!fs.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return ds(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})}}),gs=Oi("$ZodE164",(e,t)=>{t.pattern??(t.pattern=oo),Lo.init(e,t)});var ys=Oi("$ZodJWT",(e,t)=>{Lo.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})}}),vs=Oi("$ZodNumber",(e,t)=>{No.init(e,t),e._zod.pattern=co,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}}),bs=Oi("$ZodNumberFormat",(e,t)=>{_o.init(e,t),vs.init(e,t)}),ws=Oi("$ZodBoolean",(e,t)=>{No.init(e,t),e._zod.pattern=po,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}}),_s=Oi("$ZodUnknown",(e,t)=>{No.init(e,t),e._zod.parse=e=>e}),ks=Oi("$ZodNever",(e,t)=>{No.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function xs(e,t,n){e.issues.length&&t.issues.push(...ri(n,e.issues)),t.value[n]=e.value}var Os=Oi("$ZodArray",(e,t)=>{No.init(e,t);let n=Si.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=>xs(t,r,e)));else if(xs(l,r,e),a&&0!==l.issues.length&&ti(l))break}return s.length?Promise.all(s).then(()=>r):r}});function $s(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(...ri(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 Es=[];function Ss(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Es,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 Ps(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(ti(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=>$s(e,n,i,t,d,p))):$s(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 zs=Oi("$ZodObject",(e,t)=>{No.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=Ir(()=>Ss(t));vi(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)||Ar(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=Zr,a=t.catchall,l=Si.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(ti(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=>$s(n,t,e,r,o,s))):$s(a,t,e,r,o,s)}return a?Ps(u,r,t,n,i.value,e,!0===d):u.length?Promise.all(u).then(()=>t):t}}),Is=Oi("$ZodObjectJIT",(e,t)=>{zs.init(e,t);let n,r,i=e._zod.parse,o=Ir(()=>Ss(t)),s=Si.memoizer,a=Zr,l=!Si.jitless,u=l&&Fr.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 Co(["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?Ps([],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 Ts(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=>!ti(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=>si(e,r,Pi())))}),t)}var As=Oi("$ZodUnion",(e,t)=>{No.init(e,t),vi(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),vi(e,"optout",e=>e.def.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),vi(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)))}),vi(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=>Tr(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=>Ts(t,r,e,i)):Ts(s,r,e,i)}}),Cs=Oi("$ZodIntersection",(e,t)=>{No.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])=>Ns(e,t,n)):Ns(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(Jr(e)&&Jr(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 Ns(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(ti(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(l.mergeErrorPath)}`)}return e.value=l.data,e}var js=Oi("$ZodEnum",(e,t)=>{No.init(e,t);let n=Er(t.entries),r=new Set(n);e._zod.values=r,vi(e,"pattern",e=>{let t=Er(e.def.entries).filter(e=>Vr.has(typeof e));return new RegExp(t.length?`^(${t.map(e=>Wr(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}}),Ms=Oi("$ZodLiteral",(e,t)=>{No.init(e,t);let n=new Set(t.values);e._zod.values=n,vi(e,"pattern",e=>{let t=e.def.values;return new RegExp(t.length?`^(${t.map(e=>"string"==typeof e?Wr(e):e?Wr(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}}),Us=Oi("$ZodTransform",(e,t)=>{No.init(e,t),e._zod.optin="optional",Si.memoizer?.guard(e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new Ei(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 $i;return n.value=i,n}});function Ls(e,t){return e.value=t.issues.length?void 0:t.value,e}var Ds=Oi("$ZodOptional",(e,t)=>{No.init(e,t),vi(e,"optin",e=>"defaulted"===e.def.innerType._zod.optin?"defaulted":"optional"),e._zod.optout="optional",vi(e,"values",e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),vi(e,"pattern",e=>{let t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${Tr(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)}}),Zs=Oi("$ZodExactOptional",(e,t)=>{Ds.init(e,t),vi(e,"values",e=>e.def.innerType._zod.values),vi(e,"pattern",e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Fs=Oi("$ZodNullable",(e,t)=>{No.init(e,t),vi(e,"optin",e=>e.def.innerType._zod.optin),vi(e,"optout",e=>e.def.innerType._zod.optout),vi(e,"pattern",e=>{let t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${Tr(t.source)}|null)$`):void 0}),vi(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)}),Js=Oi("$ZodDefault",(e,t)=>{No.init(e,t),e._zod.optin="defaulted",vi(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=>qs(e,t)):qs(r,t)}});function qs(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var Vs=Oi("$ZodPrefault",(e,t)=>{No.init(e,t),e._zod.optin="defaulted",vi(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))}),Ws=Oi("$ZodNonOptional",(e,t)=>{No.init(e,t),vi(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=>Hs(t,e)):Hs(i,e)}});function Hs(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 Ks(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>si(e,r,Pi()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var Bs=Oi("$ZodCatch",(e,t)=>{No.init(e,t),vi(e,"optin",e=>"defaulted"===e.def.innerType._zod.optin?"defaulted":"optional"),vi(e,"optout",e=>e.def.innerType._zod.optout),vi(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=>Ks(e,r,t,n)):Ks(e,r,t,n)}}),Gs=Oi("$ZodPipe",(e,t)=>{No.init(e,t),vi(e,"values",e=>e.def.in._zod.values),vi(e,"optin",e=>e.def.in._zod.optin),vi(e,"optout",e=>e.def.out._zod.optout),vi(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=>Xs(e,t.in,n)):Xs(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Xs(e,t.out,n)):Xs(r,t.out,n)}});function Xs(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 Ys=Oi("$ZodReadonly",(e,t)=>{No.init(e,t),vi(e,"propValues",e=>e.def.innerType._zod.propValues),vi(e,"values",e=>e.def.innerType._zod.values),vi(e,"optin",e=>e.def.innerType?._zod?.optin),vi(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(Qs):Qs(r)}});function Qs(e){return e.memo||(e.value=Object.freeze(e.value)),e}var ea=Oi("$ZodCustom",(e,t)=>{mo.init(e,t),No.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=>ta(t,n,r,e));ta(i,n,r,e)}});function ta(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(ci(e))}}class na extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}var ra="~memo",ia=[];function oa(e){return null!==e&&"object"==typeof e}function sa(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var aa=new WeakMap;function la(e,t,n){let r=aa.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=la(e,t,n);r>i&&(i=r)}},s=e=>{e>i&&(i=e)},a=e._zod.def;switch(a.type){case"object":{let e=Cr(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?la(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?la(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&&aa.set(e,2===t);return t}(e,i)}var ua,ca=[],da={alloc(e,t,n){let r=ua;if(!r)return n;ua=void 0;let i={value:n,issues:null};return r.set(t.value,i),ca.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[ra]?.backEdges;return void 0!==n&&oa(t)&&n.has(t)}(n,e.value))throw new na;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=la(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(!oa(u))return t(a,l);let c,d=l[ra];d||(d={buckets:new WeakMap,backEdges:void 0},l[ra]=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(...sa(p.issues)):(a.memo=!0,d.backEdges??(d.backEdges=new WeakSet),d.backEdges.add(p.value)),a;ua=c;let h=ca.length,f=t(a,l);ua=void 0;let m=ca.length>h?ca.pop():void 0;return f instanceof Promise?f.then(e=>(m&&(m.issues=e.issues.length?sa(e.issues):ia),e)):(m&&(m.issues=f.issues.length?sa(f.issues):ia),f)};e._zod.parse=s,e._zod.run===t&&(e._zod.run=s)})}};var pa,ha=()=>{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 ${Br(e.values[0])}`:`Invalid option: expected one of ${Sr(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":""}: ${Sr(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 fa{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)}}(pa=globalThis).__zod_globalRegistry??(pa.__zod_globalRegistry=new fa);var ma=globalThis.__zod_globalRegistry;function ga(e){return e.checks&&(e.checks=[...e.checks]),e}function ya(e,t){return new vo({check:"less_than",...Kr(t),value:e,inclusive:!1})}function va(e,t){return new vo({check:"less_than",...Kr(t),value:e,inclusive:!0})}function ba(e,t){return new bo({check:"greater_than",...Kr(t),value:e,inclusive:!1})}function wa(e,t){return new bo({check:"greater_than",...Kr(t),value:e,inclusive:!0})}function _a(e,t){return new wo({check:"multiple_of",...Kr(t),value:e})}function ka(e,t){return new ko({check:"max_length",...Kr(t),maximum:e})}function xa(e,t){return new xo({check:"min_length",...Kr(t),minimum:e})}function Oa(e,t){return new Oo({check:"length_equals",...Kr(t),length:e})}function $a(e){return new Ao({check:"overwrite",tx:e})}function Ea(e,t){let n=function(e,t){let n=new mo({check:"custom",...Kr(t)});return n._zod.check=e,n}(t=>(t.addIssue=e=>{if("string"==typeof e)t.issues.push(ci(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(ci(r))}},e(t.value,t)),t);return n}function Sa(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Ar(e,t,n[t]);return e}function Pa(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??ma,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 za(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 Ia(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),Ia(o,t,r),t.seen.get(o).isParent=!0)}let l=t.metadataRegistry.get(e);return l&&Sa(s.schema,l),"input"===t.io&&Da(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 Ta(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Aa(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}/${Ta(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+Ta(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 Ca(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;Ca(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"]),Na=["oneOf","anyOf"];function ja(e){let t=e.additionalProperties;return void 0===t||!1===t||"object"!=typeof t||null===t?null:Object.keys(t).length?t:null}function Ma(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]??ja(n);null!=t&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Ar(n,r,1===e.length?e[0]:Ma(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=ja(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 Ua(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=>Na.some(t=>Array.isArray(e[t]))),r=null;if(n.length){let e=n[0],i=Na.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=>Ma([...o,e]));if(s.some(e=>!e))return;r={[i]:s}}else r=Ma(t);r&&(delete e.allOf,Sa(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?Sa(i,a):(i.allOf=i.allOf??[],i.allOf.push(a)),Sa(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())Ca(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)??[])Ua(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)}Sa(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,Ar(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:Za(t,"input",e.processors),output:Za(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw Error("Error converting schema to JSON.")}}function Da(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 Da(r.element,n);if("set"===r.type)return Da(r.valueType,n);if("lazy"===r.type)return Da(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 Da(r.innerType,n);if("intersection"===r.type)return Da(r.left,n)||Da(r.right,n);if("record"===r.type||"map"===r.type)return Da(r.keyType,n)||Da(r.valueType,n);if("pipe"===r.type)return!!e._zod.traits.has("$ZodCodec")||(Da(r.in,n)||Da(r.out,n));if("object"===r.type){for(let e in r.shape)if(Da(r.shape[e],n))return!0;return!1}if("union"===r.type){for(let e of r.options)if(Da(e,n))return!0;return!1}if("tuple"===r.type){for(let e of r.items)if(Da(e,n))return!0;return!(!r.rest||!Da(r.rest,n))}return!1}var Za=(e,t,n={})=>r=>{let{libraryOptions:i,target:o}=r??{},s=Pa({...i??{},target:o,io:t,processors:n});return Ia(e,s),Aa(s,e),La(s,e)},Fa=(e,t,n)=>{(void 0===e[t]||n>e[t])&&(e[t]=n)},Ja=(e,t,n)=>{(void 0===e[t]||n<e[t])&&(e[t]=n)},qa=(e,t)=>{Fa(e,"minimum",t),Ja(e,"maximum",t)},Va=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},Wa=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Ha=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},Ka=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Ba=(e,t)=>Fa(e,"minimum",t.minimum),Ga=(e,t)=>Ja(e,"maximum",t.maximum),Xa=e=>(t,n)=>{Ka(t,n.format);let[r,i]=e[n.format];Fa(t,"minimum",r),Ja(t,"maximum",i)},Ya={greater_than:(e,t)=>Fa(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Ja(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Va(e,t.value),number_format:Xa(Gr),bigint_format:Xa(Xr),min_length:Ba,max_length:Ga,length_equals:(e,t)=>qa(e,t.length),min_size:Ba,max_size:Ga,size_equals:(e,t)=>qa(e,t.size),string_format:(e,t)=>{Ka(e,t.format),t.pattern&&Wa(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)=>Ha(e,t.mime)};function Qa(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let e of r)Ya[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;void 0!==i.minimum&&Fa(t,"minimum",i.minimum),void 0!==i.exclusiveMinimum&&Fa(t,"exclusiveMinimum",i.exclusiveMinimum),void 0!==i.maximum&&Ja(t,"maximum",i.maximum),void 0!==i.exclusiveMaximum&&Ja(t,"exclusiveMaximum",i.exclusiveMaximum),void 0!==i.multipleOf&&Va(t,i.multipleOf),void 0!==i.format&&(t.format??(t.format=i.format),i.format.includes("int")&&(t.isInt=!0)),i.mime&&Ha(t,i.mime);for(let e of i.patterns??[])Wa(t,e);return t}var el={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},tl=new Map([[ps,/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/],[fs,/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/]]),nl=e=>tl.get(e)??e;function rl(e){let t=e._zod.def;return"pipe"===t.type&&t.in._zod.traits.has("$ZodTransform")?rl(t.out):"catch"===t.type?rl(t.innerType):e._zod.optin}var il=Symbol();function ol(e,t,n,r,i){let o=!1,s=JSON.stringify(e,(e,t)=>"bigint"!=typeof t?t:(o=!0,null));return o?(za(t,n,r,i,"BigInt defaults cannot be represented in JSON Schema"),il):JSON.parse(s)}var sl=(e,t,n,r)=>{let i=e._zod.def;Ia(i.innerType,t,r),t.seen.get(e).ref=i.innerType},al=new WeakSet([Object.prototype,Error.prototype]);function ll(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 ul,cl=Oi("ZodError",(e,t)=>{Ci.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);al.has(n)||(al.add(n),ll(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)),ll(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)),ll(n,"addIssue",e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Pr,2)}),ll(n,"addIssues",e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Pr,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return 0===this.issues.length}}))},void 0,{Parent:Error}),dl=ji(cl),pl=Mi(cl),hl=Ui(cl),fl=Di(cl),ml=(e=>{let t=ji(e),n=(e,r,i,o)=>{let s=i?{...i,direction:"backward"}:{direction:"backward"};return t(e,r,s,Ni(n,o))};return n})(cl),gl=(e=>{let t=ji(e),n=(e,r,i,o)=>t(e,r,i,Ni(n,o));return n})(cl),yl=(e=>{let t=Mi(e),n=async(e,r,i,o)=>{let s=i?{...i,direction:"backward"}:{direction:"backward"};return await t(e,r,s,Ni(n,o))};return n})(cl),vl=(e=>{let t=Mi(e),n=async(e,r,i,o)=>await t(e,r,i,Ni(n,o));return n})(cl),bl=(ul=cl,(e,t,n)=>{let r=n?{...n,direction:"backward"}:{direction:"backward"};return Ui(ul)(e,t,r)}),wl=(e=>(t,n,r)=>Ui(e)(t,n,r))(cl),_l=(e=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return Di(e)(t,n,i)})(cl),kl=(e=>async(t,n,r)=>Di(e)(t,n,r))(cl);function xl(){Si.localeError||Pi({localeError:ha()})}function Ol(){Si.memoizer||Pi({memoizer:da})}var $l=Oi("ZodType",(e,t)=>(xl(),No.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Ur(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 Hr(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,...Kr(n)})}(Tu,e,t)}(e,t))},superRefine(e,t){return this.check(function(e,t){return Ea(e,t)}(e,t))},overwrite(e){return this.check($a(e))},optional(){return wu(this)},exactOptional(){return new _u({type:"optional",innerType:this})},nullable(){return xu(this)},nullish(){return wu(xu(this))},nonoptional(e){return function(e,t){return new Eu({type:"nonoptional",innerType:e,...Kr(t)})}(this,e)},array(){return uu(this)},or(e){return hu([this,e])},and(e){return new fu({type:"intersection",left:this,right:e})},transform(e){return zu(this,new vu({type:"transform",transform:e}))},default(e){return t=e,new Ou({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():qr(t)}});var t},prefault(e){return t=e,new $u({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():qr(t)}});var t},catch(e){return new Su({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:_i(t)});var t},pipe(e){return zu(this,e)},readonly(){return new Iu({type:"readonly",innerType:this})},describe(e){let t=this.clone();return ma.add(t,{description:e}),t},meta(...e){if(0===e.length)return ma.get(this);let t=this.clone();return ma.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 pi(this,"~standard",{...Mo(this),jsonSchema:{input:Za(this,"input"),output:Za(this,"output")}})},set"~standard"(e){di(this,"~standard",e)},parse:function e(t,n){return dl(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await pl(this,t,n,{callee:e})},safeParse(e,t){return hl(this,e,t)},async safeParseAsync(e,t){return fl(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){di(this,"spa",e)},validate(e,t){return Ji(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 ml(this,t,n,{callee:e})},decode:function e(t,n){return gl(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await yl(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await vl(this,t,n,{callee:e})},safeEncode(e,t){return bl(this,e,t)},safeDecode(e,t){return wl(this,e,t)},async safeEncodeAsync(e,t){return _l(this,e,t)},async safeDecodeAsync(e,t){return kl(this,e,t)},toJSONSchema(e){return((e,t={})=>n=>{let r=Pa({...n,processors:t});return Ia(e,r),Aa(r,e),La(r,e)})(this,{})(e)},get description(){return ma.get(this)?.description},get _def(){return this._zod.def}}),El=Oi("_ZodString",(e,t)=>{Uo.init(e,t),$l.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}=Qa(e);if("number"==typeof i&&(r.minLength=i),"number"==typeof o&&(r.maxLength=o),s&&(r.format=el[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(nl);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)},hi({format:e=>Qa(e).format??null,minLength:e=>Qa(e).minimum??null,maxLength:e=>Qa(e).maximum??null},{regex(...e){return this.check(function(e,t){return new Eo({check:"string_format",format:"regex",...Kr(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new zo({check:"string_format",format:"includes",...Kr(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new Io({check:"string_format",format:"starts_with",...Kr(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new To({check:"string_format",format:"ends_with",...Kr(t),suffix:e})}(...e))},min(...e){return this.check(xa(...e))},max(...e){return this.check(ka(...e))},length(...e){return this.check(Oa(...e))},nonempty(...e){return this.check(xa(1,...e))},lowercase(e){return this.check(function(e){return new So({check:"string_format",format:"lowercase",...Kr(e)})}(e))},uppercase(e){return this.check(function(e){return new Po({check:"string_format",format:"uppercase",...Kr(e)})}(e))},trim(){return this.check($a(e=>e.trim()))},normalize(...e){return this.check(function(e){return $a(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check($a(e=>e.toLowerCase()))},toUpperCase(){return this.check($a(e=>e.toUpperCase()))},slugify(){return this.check($a(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}})),Sl=Oi("ZodString",(e,t)=>{Uo.init(e,t),El.init(e,t)},{email(e){return this.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Kr(t)})}(Rl,e))},url(e){return this.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Kr(t)})}(Ml,e))},jwt(e){return this.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Kr(t)})}(Yl,e))},emoji(e){return this.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Kr(t)})}(Ul,e))},guid(e){return this.check(function(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Kr(t)})}(Nl,e))},uuid(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Kr(t)})}(jl,e))},uuidv4(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Kr(t)})}(jl,e))},uuidv6(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Kr(t)})}(jl,e))},uuidv7(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Kr(t)})}(jl,e))},nanoid(e){return this.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Kr(t)})}(Ll,e))},cuid(e){return this.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Kr(t)})}(Dl,e))},cuid2(e){return this.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Kr(t)})}(Zl,e))},ulid(e){return this.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Kr(t)})}(Fl,e))},base64(e){return this.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Kr(t)})}(Bl,e))},base64url(e){return this.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Kr(t)})}(Gl,e))},xid(e){return this.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Kr(t)})}(Jl,e))},ksuid(e){return this.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Kr(t)})}(ql,e))},ipv4(e){return this.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Kr(t)})}(Vl,e))},ipv6(e){return this.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Kr(t)})}(Wl,e))},cidrv4(e){return this.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Kr(t)})}(Hl,e))},cidrv6(e){return this.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Kr(t)})}(Kl,e))},e164(e){return this.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Kr(t)})}(Xl,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,...Kr(t)})}(Il,e))},date(e){return this.check(function(e,t){return new e({type:"string",format:"date",check:"string_format",...Kr(t)})}(Tl,e))},time(e){return this.check(function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Kr(t)})}(Al,e))},duration(e){return this.check(function(e,t){return new e({type:"string",format:"duration",check:"string_format",...Kr(t)})}(Cl,e))}});function Pl(e){return function(e,t){return new e(ga({type:"string",...Kr(t)}))}(Sl,e)}var zl=Oi("ZodStringFormat",(e,t)=>{Lo.init(e,t),El.init(e,t)}),Il=Oi("ZodISODateTime",(e,t)=>{ts.init(e,t),zl.init(e,t)}),Tl=Oi("ZodISODate",(e,t)=>{ns.init(e,t),zl.init(e,t)}),Al=Oi("ZodISOTime",(e,t)=>{rs.init(e,t),zl.init(e,t)}),Cl=Oi("ZodISODuration",(e,t)=>{is.init(e,t),zl.init(e,t)}),Rl=Oi("ZodEmail",(e,t)=>{Fo.init(e,t),zl.init(e,t)}),Nl=Oi("ZodGUID",(e,t)=>{Do.init(e,t),zl.init(e,t)}),jl=Oi("ZodUUID",(e,t)=>{Zo.init(e,t),zl.init(e,t)}),Ml=Oi("ZodURL",(e,t)=>{Ho.init(e,t),zl.init(e,t)}),Ul=Oi("ZodEmoji",(e,t)=>{Ko.init(e,t),zl.init(e,t)}),Ll=Oi("ZodNanoID",(e,t)=>{Bo.init(e,t),zl.init(e,t)}),Dl=Oi("ZodCUID",(e,t)=>{Go.init(e,t),zl.init(e,t)}),Zl=Oi("ZodCUID2",(e,t)=>{Xo.init(e,t),zl.init(e,t)}),Fl=Oi("ZodULID",(e,t)=>{Yo.init(e,t),zl.init(e,t)}),Jl=Oi("ZodXID",(e,t)=>{Qo.init(e,t),zl.init(e,t)}),ql=Oi("ZodKSUID",(e,t)=>{es.init(e,t),zl.init(e,t)}),Vl=Oi("ZodIPv4",(e,t)=>{os.init(e,t),zl.init(e,t)}),Wl=Oi("ZodIPv6",(e,t)=>{ls.init(e,t),zl.init(e,t)}),Hl=Oi("ZodCIDRv4",(e,t)=>{us.init(e,t),zl.init(e,t)}),Kl=Oi("ZodCIDRv6",(e,t)=>{cs.init(e,t),zl.init(e,t)}),Bl=Oi("ZodBase64",(e,t)=>{hs.init(e,t),zl.init(e,t)}),Gl=Oi("ZodBase64URL",(e,t)=>{ms.init(e,t),zl.init(e,t)}),Xl=Oi("ZodE164",(e,t)=>{gs.init(e,t),zl.init(e,t)}),Yl=Oi("ZodJWT",(e,t)=>{ys.init(e,t),zl.init(e,t)}),Ql=Oi("ZodNumber",(e,t)=>{vs.init(e,t),$l.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}=Qa(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)):za(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},hi({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=Qa(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=Qa(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:n}=Qa(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>Qa(e).format??null},{gt(e,t){return this.check(ba(e,t))},gte(e,t){return this.check(wa(e,t))},min(e,t){return this.check(wa(e,t))},lt(e,t){return this.check(ya(e,t))},lte(e,t){return this.check(va(e,t))},max(e,t){return this.check(va(e,t))},int(e){return this.check(tu(e))},safe(e){return this.check(tu(e))},positive(e){return this.check(ba(0,e))},nonnegative(e){return this.check(wa(0,e))},negative(e){return this.check(ya(0,e))},nonpositive(e){return this.check(va(0,e))},multipleOf(e,t){return this.check(_a(e,t))},step(e,t){return this.check(_a(e,t))},finite(){return this}}));var eu=Oi("ZodNumberFormat",(e,t)=>{bs.init(e,t),Ql.init(e,t)});function tu(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Kr(t)})}(eu,e)}var nu=Oi("ZodBoolean",(e,t)=>{ws.init(e,t),$l.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function ru(e){return function(e,t){return new e({type:"boolean",...Kr(t)})}(nu,e)}var iu=Oi("ZodUnknown",(e,t)=>{_s.init(e,t),$l.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function ou(){return new iu({type:"unknown"})}var su=Oi("ZodNever",(e,t)=>{ks.init(e,t),$l.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function au(e){return function(e,t){return new e({type:"never",...Kr(t)})}(su,e)}var lu=Oi("ZodArray",(e,t)=>{Ol(),Os.init(e,t),$l.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=n,o=e._zod.def,{minimum:s,maximum:a}=Qa(e);"number"==typeof s&&(i.minItems=s),"number"==typeof a&&(i.maxItems=a),i.type="array",i.items=Ia(o.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element},{min(e,t){return this.check(xa(e,t))},nonempty(e){return this.check(xa(1,e))},max(e,t){return this.check(ka(e,t))},length(e,t){return this.check(Oa(e,t))},unwrap(){return this.element}});function uu(e,t){return function(e,t,n){return new e({type:"array",element:t,...Kr(n)})}(lu,e,t)}var cu=Oi("ZodObject",(e,t)=>{Ol(),Is.init(e,t),$l.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&&za(e,t,i,r,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(let e in s)Ar(i.properties,e,Ia(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===rl(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=Ia(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(i.additionalProperties=!1)})(e,t,n,r),bi(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 mu({type:"enum",entries:n,...Kr(t)})}(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(Ur(this._zod.def,{catchall:e}))},passthrough(){return this.clone(Ur(this._zod.def,{catchall:ou()}))},loose(){return this.clone(Ur(this._zod.def,{catchall:ou()}))},strict(){return this.clone(Ur(this._zod.def,{catchall:au()}))},strip(){return this.clone(Ur(this._zod.def,{catchall:void 0}))},extend(e){return function(e,t){if(!Jr(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 Hr(e,Ur(e._zod.def,{shape:Qr(e,t)}))}(this,e)},safeExtend(e){return function(e,t){if(!Jr(t))throw Error("Invalid input to safeExtend: expected a plain object");return Hr(e,Ur(e._zod.def,{shape:Qr(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 Mr(n,e,Reflect.ownKeys(Rr(e))),Mr(n,t,Reflect.ownKeys(Rr(t))),Hr(e,Ur(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 Mr(i,e,Yr(e,t)),Hr(e,Ur(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(Yr(e,t)),o={};return Mr(o,e,Reflect.ownKeys(Rr(e)).filter(e=>!i.has(e))),Hr(e,Ur(n,{shape:o,checks:[]}))}(this,e)},partial(...e){return ei(bu,this,e[0])},exactPartial(...e){return ei(_u,this,e[0],"exactPartial")},required(...e){return function(e,t,n){let r=n?new Set(Yr(t,n)):void 0,i={};return Mr(i,t,Reflect.ownKeys(Rr(t)),(t,n)=>r&&!r.has(n)?t:new e({type:"nonoptional",innerType:t})),Hr(t,Ur(t._zod.def,{shape:i}))}(Eu,this,e[0])}});function du(e,t){let n={type:"object",shape:e??{},...Kr(t)};return new cu(n)}var pu=Oi("ZodUnion",(e,t)=>{As.init(e,t),$l.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)=>Ia(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 hu(e,t){return new pu({type:"union",options:e,...Kr(t)})}var fu=Oi("ZodIntersection",(e,t)=>{Cs.init(e,t),$l.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def,o=Ia(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=Ia(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 mu=Oi("ZodEnum",(e,t)=>{js.init(e,t),$l.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{let r=Er(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 mu({...t,checks:[],...Kr(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 mu({...t,checks:[],...Kr(r),entries:i})}});var gu=Oi("ZodLiteral",(e,t)=>{Ms.init(e,t),$l.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(za(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if("bigint"==typeof s){if(za(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 yu(e,t){return new gu({type:"literal",values:Array.isArray(e)?e:[e],...Kr(t)})}var vu=Oi("ZodTransform",(e,t)=>{Ol(),Us.init(e,t),$l.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{za(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 Ei(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(ci(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(ci(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});var bu=Oi("ZodOptional",(e,t)=>{Ds.init(e,t),$l.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sl(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function wu(e){return new bu({type:"optional",innerType:e})}var _u=Oi("ZodExactOptional",(e,t)=>{Zs.init(e,t),$l.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sl(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var ku=Oi("ZodNullable",(e,t)=>{Fs.init(e,t),$l.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def,o=Ia(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 xu(e){return new ku({type:"nullable",innerType:e})}var Ou=Oi("ZodDefault",(e,t)=>{Js.init(e,t),$l.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;Ia(i.innerType,t,r),t.seen.get(e).ref=i.innerType;let o=ol(i.defaultValue,e,t,n,r);o!==il&&(n.default=o)})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});var $u=Oi("ZodPrefault",(e,t)=>{Vs.init(e,t),$l.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;if(Ia(i.innerType,t,r),t.seen.get(e).ref=i.innerType,"input"!==t.io)return;let o=ol(i.defaultValue,e,t,n,r);o!==il&&(n._prefault=o)})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var Eu=Oi("ZodNonOptional",(e,t)=>{Ws.init(e,t),$l.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;Ia(i.innerType,t,r),t.seen.get(e).ref=i.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var Su=Oi("ZodCatch",(e,t)=>{Bs.init(e,t),$l.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i,o=e._zod.def;Ia(o.innerType,t,r),t.seen.get(e).ref=o.innerType;try{i=o.catchValue(void 0)}catch{return void za(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 Pu=Oi("ZodPipe",(e,t)=>{Gs.init(e,t),$l.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;Ia(s,t,r),t.seen.get(e).ref=s})(e,t,0,r),e.in=t.in,e.out=t.out});function zu(e,t){return new Pu({type:"pipe",in:e,out:t})}var Iu=Oi("ZodReadonly",(e,t)=>{Ys.init(e,t),$l.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;Ia(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 Tu=Oi("ZodCustom",(e,t)=>{ea.init(e,t),$l.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{za(e,t,n,r,"Custom types cannot be represented in JSON Schema")})(e,t,n,r)});var Au,Cu=du({protocolVersion:Pl(),engineVersion:Pl(),buildSha:Pl(),abi:Pl()}),Ru=du({backend:Pl(),displayServer:Pl().nullable().optional(),capture:ru(),input:ru(),ax:ru(),backgroundWindowInput:ru(),cursorOverlay:ru().default(!1),deliveryModes:uu(Pl()),capturePermission:Pl(),inputPermission:Pl(),axPermission:Pl(),displayCount:function(e,t){return new e(ga({type:"number",checks:[],...Kr(t)}))}(Ql,Au).int().nonnegative(),focusGuard:ru(),stopPath:Pl(),stopReason:Pl().nullable().optional(),integrityLevel:Pl().nullable().optional(),screenLocked:ru()}),Nu=du({id:hu([yu(1),yu(2)]),result:ou().optional(),error:ou().optional()});var ju=(e,t,n)=>Or(e,[...t],{stdio:"pipe",windowsHide:!0,detached:!0,env:n});function Mu(e,t,n,r=ju){let i=r(e,["--stdio"],{...process.env,...t});return new Promise(t=>{let r,o=new Map,s="",a=new Z,l=e=>{void 0===r&&(r=e,i.stdin.end())},u=setTimeout(()=>{a.disable();let s=r??{ok:!1,code:"timeout",message:`desktop engine probe timed out after ${n} ms at ${e} (phase: ${o.has(1)&&!o.has(2)?"engine.hello answered, awaiting capabilities":o.has(2)&&!o.has(1)?"capabilities answered, awaiting engine.hello":"requests sent, awaiting engine.hello and capabilities"})`};if(l(s),t(s),c.close(),i.stdin.destroy(),i.stdout.destroy(),i.stderr.destroy(),i.unref(),void 0!==i.pid)if("win32"===process.platform){let e=Or("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&&"EPERM"!==e.code)throw e}},n);i.stderr.setEncoding("utf8"),i.stderr.on("data",e=>{a.push(e),s=(s+e).slice(-4096)}),i.stdin.on("error",t=>{l({ok:!1,code:"handshake-failed",message:`desktop engine stdin failed at ${e}: ${t.message}`})}),i.on("error",t=>{a.disable(),l({ok:!1,code:"handshake-failed",message:`desktop engine spawn failed at ${e}: ${t.message}`})});let c=$r({input:i.stdout}).on("line",t=>{let n;try{n=JSON.parse(t)}catch(t){if(!(t instanceof SyntaxError))throw t;return a.disable(),void l({ok:!1,code:"handshake-failed",message:`desktop engine emitted non-JSON output at ${e}`})}let r=Nu.safeParse(n);r.success&&(1!==r.data.id&&void 0===r.data.error||a.disable(),void 0===r.data.error?(o.set(r.data.id,r.data.result),o.has(1)&&o.has(2)&&l(function(e,t,n){let r=Cu.safeParse(e);if(!r.success)return{ok:!1,code:"handshake-failed",message:`malformed engine.hello result at ${n}`};if(r.data.abi!==Y||r.data.protocolVersion!==X)return{ok:!1,code:"abi-mismatch",message:`desktop engine ABI mismatch at ${n}: expected abi ${Y} protocol ${X}, 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))):l({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(u);let o=a.finish(n,i,s);t(void 0===o?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>"}`}:{ok:!1,code:o.code,reason:o.reason,message:o.message,diagnostic:o.diagnostic})}),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 Uu(e,t,n={}){let r=gr(e,t,vr(t),n);if(!("path"in r))return"OS permissions: unknown until first use (no usable installed engine)";let i=await Mu(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??br(),n=new xr({createChild:t(e.settings.enginePath),onError:t=>e.onEngineError(function(e){return e instanceof gt?e.diagnostic.code:e instanceof te?"abi-mismatch":e instanceof _t?null!==e.data&&"code"in e.data?e.data.code:"other":e instanceof wt?e.code:"other"}(t)),onPermissionRequired:e.onPermissionRequired,...void 0===e.fullAccess?{}:{fullAccess:e.fullAccess}}),r=new y({service:n,settings:()=>e.settings}),i={handle:r,executeTool:e.executeTool,confirmControl:t=>async function(e,t={}){if(!1===e.context.hasUI||e.signal.aborted)return!1;let n=e.context.ui?.notify;if(!0===t.fullAccess?.()&&!0===e.context.hasUI&&void 0!==n)return n(`Computer use is taking foreground control (full access, no confirm needed): ${e.reason}`,"info"),!0;let r=e.context.ui?.confirm;if(void 0===r)return!1;let i=Math.min(t.timeoutMs??45e3,e.budgetMs??Number.POSITIVE_INFINITY),o=t.scheduleTimeout??or;return await new Promise(t=>{let n=!1,s=r=>{n||(n=!0,l(),e.signal.removeEventListener("abort",a),t(r))},a=()=>s(!1),l=o(()=>s(!1),i);var u;e.signal.addEventListener("abort",a,{once:!0}),Promise.resolve(r("Allow foreground computer control?",(u=e.reason,`${u}\n\nFor this task only. Interrupt the task or press the computer stop chord to stop and revoke control. This does not authorize external side effects.`),{signal:e.signal,timeout:i})).then(e=>s(!0===e),()=>s(!1))})}(t,{fullAccess:e.fullAccess})};return{handle:r,service:n,computerTool:Qn(i),computerActionsTool:tr(i),describeEngineSource:wr,describeEnginePermissions:Uu}}export{Lu as createComputerUseRuntime};