omo-ai 5.1.71 → 5.1.72
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/darwin/omo-keychain +0 -0
- package/bin/lib/daemon.js +38 -1
- package/bin/lib/provider-map.json +1 -1
- package/bin/lib/service-auth.generated.js +58 -20
- package/package.json +2 -2
- package/plugin/CHANGELOG.md +49 -0
- package/plugin/extensions/gateway-store-worker.mjs +1 -1
- package/plugin/extensions/memory-run-supervisor.mjs +1 -1
- package/plugin/extensions/omo-claim-receipt.js +1 -1
- package/plugin/extensions/omo-computer-run-worker.mjs +1 -1
- package/plugin/extensions/omo-computer-use.js +1 -1
- package/plugin/extensions/omo-desktop-toolkit.js +1 -1
- package/plugin/extensions/omo-device-account.js +6 -6
- package/plugin/extensions/omo-device-service.js +5 -5
- package/plugin/extensions/omo-feedback.js +2 -2
- package/plugin/extensions/omo-init-deep-advisor.js +1 -1
- package/plugin/extensions/omo-member.js +1 -1
- package/plugin/extensions/omo-memory-commands.js +1 -1
- package/plugin/extensions/omo-memory-doctor.js +1 -1
- package/plugin/extensions/omo-memory-memfs.js +1 -1
- package/plugin/extensions/omo-memory-palace.js +1 -1
- package/plugin/extensions/omo-memory-sync.js +1 -1
- package/plugin/extensions/omo-onboarding-scan.js +2 -2
- package/plugin/extensions/omo-recall-store.js +1 -1
- package/plugin/extensions/omo-session-history.js +1 -1
- package/plugin/extensions/omo-side-panel.js +1 -1
- package/plugin/extensions/omo-task.js +2 -2
- package/plugin/extensions/omo-telemetry-otlp.js +1 -1
- package/plugin/extensions/omo-telemetry-posthog.js +1 -1
- package/plugin/extensions/omo-telemetry-recovery.js +1 -1
- package/plugin/extensions/omo-thread-client.js +3 -3
- package/plugin/extensions/omo-wake.js +57 -0
- package/plugin/extensions/omo.js +3 -3
- package/plugin/package.json +2 -1
- package/plugin/runtime/agent-toolkit-sdk/sdk.js +2 -2
- package/plugin/runtime/ast-grep-mcp/manifest.json +1 -1
- package/plugin/runtime/bunshin-ts/sdk.js +2 -2
- package/plugin/runtime/rollback-migrate.js +1 -1
- package/plugin/runtime/thread-sdk/sdk.js +3 -3
- package/plugin/scripts/install.mjs +1 -0
- package/plugin/skills/browser/runtime/omowright/manifest.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
// omo:
|
|
1
|
+
// omo:Qwz161UO0YAFGHGZlx9DLMU3VnNNT49C0TIVqiVm3pg:LXqGOoe3lpE7Kp9lQS0d_IXRVEGUUB9mjgpAXlphzGY
|
|
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 h}from"node:os";import{join as p}from"node:path";var f=".computer-audit.jsonl",m=Number.MAX_SAFE_INTEGER;function g(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 v 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 v;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,i=t.executionScope;if(void 0!==i){let{capture:t}=i;return{display:e.display,macosCanary:e.macosCanary,showCursor:e.showCursor,allowHostRelayOnlyStop:e.allowHostRelayOnlyStop,auditPath:n.enabled?p(i.auditDir,f):null,artifactDir:h(),screenshotGc:{staleMs:t.screenshotGc.staleMs,scanIntervalMs:t.screenshotGc.scanIntervalMs},captureCaps:{maxWidth:t.maxWidth,maxHeight:t.maxHeight,coordinateSafe:t.coordinateSafe,maxBytes:t.maxBytes}}}return{display:e.display,macosCanary:e.macosCanary,showCursor:e.showCursor,allowHostRelayOnlyStop:e.allowHostRelayOnlyStop,auditPath:n.enabled?p(t.sessionManager.getSessionDir(),f):null,artifactDir:h(),screenshotGc:{staleMs:r.enabled?r.staleMs:m,scanIntervalMs:r.scanIntervalMs},captureCaps:{maxWidth:e.maxWidth,maxHeight:e.maxHeight,coordinateSafe:g(t.model),maxBytes:e.screenshotMaxBytes},intervention:e.intervention,macosKeyPriming:e.macosKeyPriming,trace:e.trace}}(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 b}from"typebox/value";class w extends Error{code="COMPUTER_INVALID_ARGUMENTS";reason;constructor(e){super(`COMPUTER_INVALID_ARGUMENTS: ${e}`),this.name="ComputerArgumentsError",this.reason=e}}function _(e){return new Map(e.map(e=>[String(Reflect.get(e.properties.action??{},"const")),e]))}function k(e,t,n){let r=[...e.keys()].join(", ");if("object"!=typeof t||null===t)return new w(`${n} must be an object`);let i=Reflect.get(t,"action");if("string"!=typeof i)return new w(`${n}: "action" must be one of ${r}`);let o=e.get(i);if(void 0===o)return new w(`${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 w(`${n}: action "${i}" does not take ${s.join(", ")}`);let[a]=b(o,t),l=void 0===a||""===a.instancePath?"":` at ${a.instancePath}`;return new w(`${n}: action "${i}"${l}: ${a?.message??"invalid arguments"}`)}import{Type as x}from"typebox";import{Check as O}from"typebox/value";var S=x.Union([x.Literal("left"),x.Literal("right"),x.Literal("middle")]),E={timeout:x.Optional(x.Number({exclusiveMinimum:0,description:"Maximum time in seconds for this action."})),include_screenshot:x.Optional(x.Boolean({description:"Capture a screenshot after the action."}))},$={x:x.Number(),y:x.Number()},P={additionalProperties:!1},I=[x.Object({action:x.Literal("screenshot"),...E},P),x.Object({action:x.Literal("click"),...$,button:x.Optional(S),...E},P),x.Object({action:x.Literal("double_click"),...$,button:x.Optional(S),...E},P),x.Object({action:x.Literal("move"),...$,button:x.Optional(S),...E},P),x.Object({action:x.Literal("drag"),...$,to_x:x.Number(),to_y:x.Number(),button:x.Optional(S),...E},P),x.Object({action:x.Literal("scroll"),...$,scroll_x:x.Number(),scroll_y:x.Number(),...E},P),x.Object({action:x.Literal("type"),text:x.String(),...E},P),x.Object({action:x.Literal("keypress"),keys:x.Array(x.String(),{minItems:1}),...E},P),x.Object({action:x.Literal("wait"),ms:x.Integer({minimum:0}),...E},P)],T=x.Union([...I]),C=x.Object({action:x.Literal("batch"),actions:x.Array(T,{minItems:1}),...E},P),z=x.Union([T,C]),R=["screenshot","click","double_click","move","drag","scroll","type","keypress","wait"],A={x:x.Optional(x.Number({description:"click, double_click, move, drag (start), scroll (required): x pixel"})),y:x.Optional(x.Number({description:"click, double_click, move, drag (start), scroll (required): y pixel"})),button:x.Optional(x.Enum(["left","right","middle"],{type:"string",description:"click, double_click, move, drag: mouse button (default left)"})),to_x:x.Optional(x.Number({description:"drag (required): end x pixel"})),to_y:x.Optional(x.Number({description:"drag (required): end y pixel"})),scroll_x:x.Optional(x.Number({description:"scroll (required): horizontal scroll distance in pixels on every OS (one wheel notch is about 40 px); positive scrolls right"})),scroll_y:x.Optional(x.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:x.Optional(x.String({description:"type (required): text to type"})),keys:x.Optional(x.Array(x.String(),{minItems:1,description:"keypress (required): keys pressed together"})),ms:x.Optional(x.Integer({minimum:0,description:"wait (required): milliseconds"})),...E},N=x.Object({action:x.Enum([...R,"batch"],{type:"string",description:"The action to perform, or batch to run `actions` in order"}),actions:x.Optional(x.Array(x.Object({action:x.Enum([...R],{type:"string",description:"The action to perform"}),...A},P),{minItems:1,description:"batch (required): actions to execute in order"})),...A},P),j=_(I),M=_([...I,C]);var U=new Set(["screenshot","wait"]);var L=/^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$/,D=/^senpi-desktop-engine: refusing to run: the responsible process of engine pid [1-9]\d* cannot be resolved$/;class Z extends Error{code="launch-context-unavailable";reason;diagnostic;userFacing;constructor(e,t){let n={code:"COMPUTER_LAUNCH_CONTEXT_REQUIRED",message:"Computer use cannot start safely from this host's current macOS launch context."+("unresolved"===e?" macOS responsibility could not be resolved.":""),action:"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."};super(`${n.code}: ${n.message} ${n.action}`),this.name="DesktopLaunchContextError",this.reason=e,this.diagnostic=t,this.userFacing=n}}class F{#u="";#c=!1;#d=!1;#h=!1;#p=!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.#v(),this.#u="",this.#c=!1,t=n+1}}finish(e,t,n){if(this.#u.startsWith("SENPI_DESKTOP_LAUNCH_REFUSED")&&(this.#p=!0),this.#d||this.#p||1!==e||null!==t)return;let r=this.#h?this.#f:this.#m;return void 0===r?void 0:new Z(r,`${this.#g}\n${n}`)}#v(){if(this.#u.startsWith("SENPI_DESKTOP_LAUNCH_REFUSED")){this.#h&&(this.#p=!0),this.#h=!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.#p=!0:(this.#f=e,this.#g=this.#u))}if(this.#c)return;let e=L.test(this.#u)?"self-responsible":D.test(this.#u)?"unresolved":void 0;void 0!==e&&(void 0!==this.#m&&this.#m!==e&&(this.#p=!0),this.#m=e)}}var J={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"},q={screenshot:"read",zoom:"read",click:"exec",doubleClick:"exec",move:"exec",drag:"exec",scroll:"exec",type:"exec",press:"exec",holdKeys:"exec",holdMouse:"exec"},W={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",type:"exec",focus:"exec",parent:"read",children:"read"},B={display:{label:"display",methods:q},window:{label:"window",methods:W},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 G(e){return Object.keys(e).join(", ")}function Y(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(J,t.method);if(void 0===i)throw new H("unknownMethod",`Unknown desktop method "${t.method}". Desktop helpers support: ${G(J)}.`);if(void 0===n)return i;let o=Object.hasOwn(B,t.method)?B[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: ${G(o.methods)}.`);return s}(e)}var X="1",Q="senpi-desktop/1",ee=["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","ax.typeText","stopPath.start","stopPath.status","stopPath.heartbeat","stopPath.stop","stopPath.resume","$/cancel","$/test.advanceClock"],te=["audit","stopPath.changed","engine.log","epoch.changed"],ne=["PermissionDenied","CaptureFailed","InputFailed","BackgroundUnavailable","WindowNotFound","InvalidTarget","InvalidKey","InvalidCoordinateFrame","StaleRef","AxUnsupported","AxFailed","Timeout","Closed","Internal","StopPathUnavailable","Suspended","ScreenLocked","Cancelled","CursorRestoreFailed","FocusRestoreFailed","TransactionFailed","InputBusy","ControlRequired","CaptureUnavailable","UserIntervened","AxUnconfirmed","SpaceUnsupported","SpaceMoveDenied","AmbiguousTarget","CaptureConsentRequired","ProtectedProcess"],re=-32601,ie="unknown";class oe extends Error{code="abi-mismatch";enginePath;expected;actual;constructor(e,t){let n={abi:Q,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 se}from"node:child_process";import{createHash as ae}from"node:crypto";import{accessSync as le,constants as ue,existsSync as ce,readFileSync as de,realpathSync as he}from"node:fs";import{dirname as pe,join as fe,sep as me}from"node:path";import{fileURLToPath as ge}from"node:url";var ve="senpi-desktop-engine-checksums.txt",ye=["darwin-arm64","darwin-x64","linux-x64","linux-arm64","win32-x64","win32-arm64"];function be(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 we(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||!ye.some(e=>be(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 _e,ke="senpi-desktop-engine",xe="com.apple.quarantine",Oe=fe(pe(ge(import.meta.url)),"..");function Se(e=process.platform,t=process.arch,n=("linux"===e&&e===process.platform?function(){return _e??=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(),Ee),_e}():void 0)){return"linux"===e&&"musl"===n?`${e}-${t}-musl`:`${e}-${t}`}function Ee(){try{return de("/proc/self/maps","utf8")}catch(e){if(e instanceof Error&&"code"in e)return;throw e}}function $e(e=process.platform){return"win32"===e?`${ke}.exe`:ke}function Pe(e={}){let t=Se(e.platform,e.arch,e.libc),n=$e(e.platform),r=e.packageDir??Oe,i=e.execDir??pe(process.execPath),o=e.repoRoot??fe(r,"..",".."),s=fe("native","prebuilds",t,n),a=e.runtimeDir??process.env.OMO_PACKAGE_DIR;return[...a?[fe(a,s)]:[],fe(i,s),fe(r,s),fe(o,"target","release",n)]}function Ie(e={}){let t=e.platform??process.platform,n=Se(t,e.arch,e.libc),r=Pe(e),i=e.execDir??pe(process.execPath),o=e.runtimeDir??process.env.OMO_PACKAGE_DIR?1:0,s=e.isQuarantined??(e=>Ce(e,t)),a=[],l=[];for(let[e,t]of r.entries())if(ce(t)){if(s(t)){if(e!==o||!Te(t,i,n)){l.push(t),a.push(`${t}: blocked because ${xe} 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(ze(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===be(n)?"no-release-asset":void 0;return{path:null,diagnostic:{code:u,host:n,attemptedPaths:r,message:"quarantined"===u?`The ${ke} 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 ${ke} binary is available for ${n}.`,cause:a.join("; "),...void 0===c?{}:{reason:c}}}}function Te(e,t,n){try{let r=`${fe(he(t),"native","prebuilds")}${me}`;if(!he(e).startsWith(r))return!1;let i=be(n);if(null===i)return!1;let o=we(de(fe(t,"native","prebuilds",ve),"utf8"));if(null!==o.error)return!1;let s=o.checksums.get(i);return void 0!==s&&ae("sha256").update(de(e)).digest("hex")===s.toLowerCase()}catch(e){if(e instanceof Error&&"code"in e)return!1;throw e}}function Ce(e,t=process.platform){if("darwin"!==t)return!1;let n=se("/usr/bin/xattr",["-p",xe,e],{stdio:["ignore","ignore","ignore"],timeout:2e3});return void 0===n.error&&0===n.status}function ze(e){try{return le(e,ue.X_OK),!0}catch(e){if(e instanceof Error&&"code"in e)return!1;throw e}}import{createHash as Re,randomUUID as Ae}from"node:crypto";import{accessSync as Ne,chmodSync as je,constants as Me,existsSync as Ue,mkdirSync as Le,mkdtempSync as De,readFileSync as Ze,readdirSync as Fe,renameSync as Je,rmSync as qe,writeFileSync as We}from"node:fs";import{homedir as Ve}from"node:os";import{join as Be}from"node:path";import{spawnSync as He}from"node:child_process";function Ke(e){let t=He("/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 Ge="-musl";function Ye(e,t){let{host:n,version:r}=e,i=be(n),o=[];if(null===i)return{path:null,attemptedPaths:o};let s=n.slice(0,n.indexOf("-")),a=e.cacheDir??Be(Ve(),".omo","cache","senpi-desktop-engine"),l=Be(a,r,n);if(Ue(l))for(let e of Fe(l)){let n=/^([0-9a-f]{64})-[0-9a-f-]{36}$/.exec(e);if(null===n)continue;let r=Be(l,e,i);if(o=[...o,r],t?.(r),Ue(r)&&Re("sha256").update(Ze(r)).digest("hex")===n[1]&&!Ce(r,s))try{return Ne(r,Me.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 Xe(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(Ge)?"musl":"glibc",u="musl"===l?a.slice(0,-5):a,c=Ie({...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&&Be(r,"native","prebuilds",t,$e(s));if("darwin"===s&&c.path===o&&r&&(e.isReleaseEngine??Ke)(c.path)){let e=JSON.parse(Ze(Be(r,"package.json"),"utf8"));return"object"==typeof e&&null!==e&&"omo"===Reflect.get(e,"name")&&Reflect.get(e,"version")===n?{path:c.path,sha256:Re("sha256").update(Ze(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=be(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 h=e.cacheDir??Be(Ve(),".omo","cache","senpi-desktop-engine"),p=Be(h,n,t),f=Ye(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,Be(p,d)];let[v,y]=await Promise.all([m(`${g}/${d}`,{signal:AbortSignal.timeout(3e4)}),m(`${g}/${ve}`,{signal:AbortSignal.timeout(3e4)})]);if(!v.ok)return i(`${d}: HTTP ${v.status}`);if(!y.ok)return i(`${ve}: HTTP ${y.status}`);let b=we(await y.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 v.arrayBuffer()),k=Re("sha256").update(_).digest("hex");if(k.toLowerCase()!==w.toLowerCase())return i(`SHA-256 mismatch for ${d}`);Le(p,{recursive:!0});let x=De(Be(p,".download-")),O=Be(p,`${k}-${Ae()}`);try{let e=Be(x,d);We(e,_),je(e,493),Je(x,O)}finally{qe(x,{recursive:!0,force:!0})}return{path:Be(O,d),sha256:k}}catch(e){return i(e instanceof Error?e.message:String(e))}}async function Qe(e,h,p=Xe){let f=await p(e);if(null===f.path)return f;let m=e.isReleaseEngine??Ke;return e.host.startsWith("darwin-")&&void 0!==f.sha256&&m(f.path)?(await Promise.resolve().then(()=>{}),function(e,h,p){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(!p(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:h(f)}}finally{m.close()}}({path:f.path,sha256:f.sha256,version:e.version,directory:Be(e.installDir??Be(Ve(),".omo","engines","senpi-desktop-engine"),e.host)},t=>Ce(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:h(t)},m).value):{path:f.path,value:h(f.path)}}function et(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var tt=e=>"string"==typeof e,nt=e=>"number"==typeof e&&Number.isFinite(e),rt=e=>"boolean"==typeof e,it=e=>null==e,ot=e=>Array.isArray(e)&&e.every(tt);function st(e,t){return it(e)?null:!!t(e)&&e}function at(e,t){if(!Array.isArray(e))return;let n=[];for(let r of e){let e=t(r);if(void 0===e)return;n.push(e)}return n}function lt(e){let{x:t,y:n,width:r,height:i}=e;return nt(t)&&nt(n)&&nt(r)&&nt(i)?{x:t,y:n,width:r,height:i}:void 0}function ut(e){if(it(e))return null;if(!et(e)||!tt(e.windowNumber)||!nt(e.pid))return;let t=st(e.processStart,nt);return!1!==t?{windowNumber:e.windowNumber,pid:e.pid,processStart:t}:void 0}function ct(e){if(!(et(e)&&tt(e.id)&&tt(e.app)&&tt(e.title)))return;let t=lt(e),n=st(e.pid,nt),r=ut(e.identity);return void 0!==t&&!1!==n&&void 0!==r&&rt(e.focused)?{id:e.id,app:e.app,title:e.title,pid:n,bounds:t,focused:e.focused,identity:r}:void 0}function dt(e){if(!(et(e)&&tt(e.id)&&tt(e.name)&&nt(e.scale)))return;let t=lt(e),{pixelX:n,pixelY:r,pixelWidth:i,pixelHeight:o}=e;return void 0!==t&&rt(e.isPrimary)&&nt(n)&&nt(r)&&nt(i)&&nt(o)?{id:e.id,name:e.name,bounds:t,scale:e.scale,pixelBounds:{x:n,y:r,width:i,height:o},isPrimary:e.isPrimary}:void 0}var ht=new Set(["known","absent","unknown"]),pt=["title","value","description","enabled","focused","bounds"];function ft(e){if(!(et(e)&&tt(e.ref)&&tt(e.role)&&tt(e.nativeRole)))return;if(!rt(e.enabled)||!rt(e.focused)||!nt(e.childCount))return;let t=st(e.title,tt),n=st(e.value,tt),r=st(e.description,tt),i=st(e.actions,ot),o=function(e){return it(e)?null:et(e)&&pt.every(t=>ht.has(e[t]))?e:void 0}(e.evidence),{x:s,y:a,width:l,height:u}=e,c=[s,a,l,u],d=c.every(nt)?lt(e):null;if(void 0===d||null===d&&!c.every(e=>it(e)||nt(e)))return;if(!1===t||!1===n||!1===r||!1===i||void 0===o)return;let h=st(e.subtreeTruncated,rt),p=st(e.secure,rt);return!1!==h&&!1!==p?{ref:e.ref,role:e.role,nativeRole:e.nativeRole,title:t,value:n,description:r,enabled:e.enabled,focused:e.focused,bounds:d,actions:i??[],childCount:e.childCount,evidence:o,subtreeTruncated:h??!1,secure:p??!1}:void 0}function mt(e){return et(e)&&tt(e.ref)&&nt(e.childCount)?{ref:e.ref,childCount:e.childCount}:void 0}function gt(e,t="text"){if(!et(e))return;let n=e[t];if(!tt(n)||!nt(e.nodeCount)||!rt(e.truncated))return;let r=st(e.generation,nt),i=st(e.parent,nt),o=st(e.complete,rt),s=st(e.nodesObserved,nt),a=it(e.cuts)?[]:at(e.cuts,mt);return!1!==r&&!1!==i&&!1!==o&&!1!==s&&void 0!==a?{text:n,nodeCount:e.nodeCount,truncated:e.truncated,generation:r,parent:i,complete:o,nodesObserved:s,cuts:a}:void 0}function vt(e){if(!et(e)||!tt(e.title)||!ot(e.path))return;if(!rt(e.enabled)||!rt(e.checked)||!rt(e.hasSubmenu))return;let t=st(e.shortcut,tt);return!1!==t?{title:e.title,path:e.path,enabled:e.enabled,checked:e.checked,hasSubmenu:e.hasSubmenu,shortcut:t}:void 0}var yt=new Set(["not_delivered/safe","not_delivered/after_user","delivery_uncertain/unsafe","delivery_uncertain/unknown","delivered_unverified/unsafe","delivered_verified/unsafe","unknown/unknown"]);function bt(e){if(et(e)&&tt(e.delivery)&&tt(e.retry)&&yt.has(`${e.delivery}/${e.retry}`))return{delivery:e.delivery,retry:e.retry}}var wt=new Set(["confirmed","unverifiable","no_change"]),_t=new Set(["ax","background_window","background_pid","foreground_hid"]),kt=new Set(["not_needed","restored","user_moved_on","not_confirmed"]);function xt(e){if(!et(e)||!tt(e.kind))return;let t=st(e.title,tt),n=st(e.windowId,tt),r=st(e.ref,tt);return!1!==t&&!1!==n&&!1!==r?{kind:e.kind,title:t,windowId:n,ref:r}:void 0}function Ot(e){if(et(e)&&tt(e.backend)&&rt(e.capture)&&rt(e.input)&&rt(e.ax)&&ot(e.deliveryModes)&&tt(e.stopPath))return e}function St(e){if(et(e)&&rt(e.suspended)&&rt(e.globalLive)&&rt(e.hostRelayLive)&&rt(e.heartbeatFresh)&&tt(e.stopPath))return e}var Et=new Set(["display","lock","sleep","space","engine_restarted","idle_flush"]);function $t(e){if(!et(e)||!rt(e.active))return;let t=st(e.reason,tt),n=st(e.grantedAt,tt);return!1!==t&&!1!==n?{active:e.active,reason:t,grantedAt:n}:void 0}function Pt(e){let t=at(e,e=>ot(e)&&2===e.length?e:void 0);return void 0===t?void 0:Object.fromEntries(t.map(([e,t])=>[e,t]))}var It={delivery:"not_delivered",retry:"safe"},Tt={delivery:"unknown",retry:"unknown"};class Ct extends Error{code;disposition;data;nothingSent;constructor(e,t,n={}){super(t,void 0===n.cause?void 0:{cause:n.cause}),this.name="ComputerError",this.code=e,this.disposition=n.disposition??Tt,this.nothingSent="not_delivered"===this.disposition.delivery,this.data={reason:n.reason??null,hint:n.hint??null,...void 0===n.candidates?{}:{candidates:n.candidates},...void 0===n.engine?{}:{engine:n.engine}}}}var zt=new Set(ne),Rt=e=>zt.has(e),At=e=>"string"==typeof e?e:null;function Nt(e,t,n,r={}){return new Ct(e,t,{...r,reason:n,disposition:r.disposition??It})}function jt(e,t,n){let r=JSON.stringify(n)?.slice(0,200)??String(n);return new Ct("Internal",`desktop engine sent a malformed ${e} result: ${r}`,{reason:"malformed_result",disposition:"read"===t?It:Tt})}function Mt(e,t,n){if(n instanceof Ct)return n;let r=et(n)?n:{},i=At(r.message)??`${e} failed: ${String(n)}`,o="read"===t||!0===r.nothingSent?It:Tt,s=et(r.data)?r.data:void 0;if(void 0!==s&&Rt(s.code))return new Ct(s.code,i,{disposition:bt(s.disposition)??o,reason:At(s.reason),hint:At(s.hint),engine:s,cause:n});if(r.rpcCode===re){let e=void 0===s?"unknown":At(s.reason)??"unknown";return new Ct("Internal",i,{disposition:It,reason:`method_${e}`,...void 0===s?{}:{engine:s},cause:n})}let a=Rt(r.code)?r.code:"Internal";return new Ct(a,i,{disposition:o,cause:n})}function Ut(e){return{disposition:e.disposition,delivered:null,effect:e.nothingSent?"refused":"unverifiable",route:null,hit:null,focusRestoration:"not_confirmed",openedSurfaces:[],nextCall:null,note:e.message,warning:null,auditIds:[],timings:null,legacy:!1}}var Lt={delivery:"not_delivered",retry:"after_user"};class Dt{active;reason;grantedAt;#y;constructor(e,t){this.#y=e,this.active=t.active,this.reason=t.reason,this.grantedAt=t.grantedAt}release(){return this.#y.release()}}class Zt{#b;#w;constructor(e,t){this.#b=e,this.#w=t}async acquire(e){let t="string"==typeof e?e.trim():"";if(0===t.length)throw Nt("InvalidTarget","control.acquire requires a non-empty reason","empty_reason");let n=await this.state();if(n.active)return new Dt(this,n);if(void 0===this.#w)throw Nt("ControlRequired","no confirm channel can ask the human for foreground control","no_confirm_channel",{disposition:Lt});if(!0!==await this.#w(t))throw Nt("ControlRequired","the human declined foreground control","declined",{disposition:Lt});let r=await this.#b.read("control.grant",{reason:t,confirmationId:crypto.randomUUID()},$t);return new Dt(this,r)}state(){return this.#b.read("control.state",{},$t)}async release(){await this.#b.read("control.revoke",{},e=>null===e?null:void 0)}}var Ft=(e,t)=>void 0===t||e.toLocaleLowerCase().includes(t.toLocaleLowerCase());function Jt(e,t){return void 0===t||("string"==typeof t?e.id===t:(void 0===t.id||e.id===t.id)&&Ft(e.app,t.app)&&Ft(e.title,t.title))}var qt=new Set(["inline-png","inline-jpeg","artifact-only"]),Wt=e=>"number"==typeof e&&Number.isFinite(e),Vt=e=>null==e||"string"==typeof e;function Bt(e){if(!et(e)||"string"!=typeof e.frameId||"string"!=typeof e.target)return;if(!qt.has(e.mode)||!Wt(e.width)||!Wt(e.height))return;let{data:t,mimeType:n,artifactPath:r}=e;if(!Vt(t)||!Vt(n)||!Vt(r))return;let i=e.coordinateWidth??e.width,o=e.coordinateHeight??e.height,s=function(e){if(null==e)return null;if(!et(e))return;let{x:t,y:n,width:r,height:i}=e;return Wt(t)&&Wt(n)&&Wt(r)&&Wt(i)?{x:t,y:n,width:r,height:i}:void 0}(e.region),a=ut(e.identity);return Wt(i)&&Wt(o)&&void 0!==s&&void 0!==a&&("artifact-only"===e.mode||"string"==typeof t)?{frameId:e.frameId,target:e.target,identity:a,width:e.width,height:e.height,coordinateWidth:i,coordinateHeight:o,region:s,data:t??null,mimeType:n??("inline-jpeg"===e.mode?"image/jpeg":"image/png"),artifactPath:r??null}:void 0}function Ht(e){if(void 0===e)return;let{maxDimension:t,maxBytes:n,coordinateSafe:r}=e,i={...void 0===t?{}:{maxWidth:t,maxHeight:t},...void 0===n?{}:{maxBytes:n},...void 0===r?{}:{coordinateSafe:r}};return 0===Object.keys(i).length?void 0:i}class Kt{id;target;identity;width;height;coordinateWidth;coordinateHeight;region;image;mimeType;artifactPath;#b;constructor(e,t){this.#b=e,this.id=t.frameId,this.target=t.target,this.identity=t.identity,this.width=t.width,this.height=t.height,this.coordinateWidth=t.coordinateWidth,this.coordinateHeight=t.coordinateHeight,this.region=t.region,this.image=null===t.data?null:function(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}(t.data),this.mimeType=t.mimeType,this.artifactPath=t.artifactPath}async zoom(e){let t={target:this.target,region:e,frameId:this.id};return new Kt(this.#b,await this.#b.read("captureRegion",t,Bt))}}function Gt(e={}){let{button:t,count:n,modifiers:r,delivery:i,consume:o}=e;return Object.fromEntries(Object.entries({button:t,count:n,modifiers:r,deliveryMode:i,consume:o}).filter(([,e])=>void 0!==e))}function Yt(e){if("number"!=typeof e||!Number.isFinite(e)||e<0||e>100)throw Nt("InvalidTarget","hold durationSeconds must be finite seconds in 0..=100","invalid_duration");return e}function Xt(e,t){let{frame:n,x:r,y:i}=t;if(n.target!==e)throw Nt("InvalidCoordinateFrame",`a frame of ${n.target} cannot aim input at ${e}`,"other_target");if(null!==n.region)throw Nt("InvalidCoordinateFrame","a zoom frame cannot aim input; use the full frame","zoom_frame");if(!Number.isFinite(r)||!Number.isFinite(i))throw Nt("InvalidCoordinateFrame","frame point coordinates must be finite","invalid_point");return{x:r,y:i,frameId:n.id}}class Qt{#b;#_;constructor(e,t){this.#b=e,this.#_=t}async click(e,t){let n=Xt(this.#_,e);return this.#b.act("click",{target:this.#_,...n,opts:Gt(t)},t?.verify)}async move(e,t){let n=Xt(this.#_,e);return this.#b.act("moveMouse",{target:this.#_,...n,opts:Gt(t)},t?.verify)}async drag(e,t,n){let r=Xt(this.#_,e),i=Xt(this.#_,t);if(r.frameId!==i.frameId)throw Nt("InvalidCoordinateFrame","both drag points must come from the same frame","mixed_frames");let o=[{x:r.x,y:r.y},{x:i.x,y:i.y}],s={target:this.#_,path:o,frameId:r.frameId,opts:Gt(n)};return this.#b.act("drag",s,n?.verify)}async scroll(e,t,n){let r=Xt(this.#_,e);if(!Number.isFinite(t.dx)||!Number.isFinite(t.dy))throw Nt("InvalidTarget","scroll delta must be finite","invalid_delta");let i={target:this.#_,...r,dx:t.dx,dy:t.dy,opts:Gt(n)};return this.#b.act("scroll",i,n?.verify)}async hold(e,t){let n=Yt(t?.durationSeconds),r=Xt(this.#_,e),{button:i,...o}=t,s={target:this.#_,...r,duration:n,...void 0===i?{}:{button:i},opts:Gt(o)};return this.#b.act("holdMouse",s,t.verify)}}class en{#b;#_;constructor(e,t){this.#b=e,this.#_=t}async type(e,t){return this.#b.act("typeText",{target:this.#_,text:e,opts:Gt(t)},t?.verify)}async chord(e,t){let n=e.split("+").map(e=>e.trim()).filter(e=>e.length>0);if(0===n.length)throw Nt("InvalidKey","chord needs at least one key","empty_chord");let r={target:this.#_,keys:n,opts:Gt(t),...void 0===t?.force?{}:{force:t.force}};return this.#b.act("keyChord",r,t?.verify)}async hold(e,t){let n=Yt(t?.durationSeconds);if(0===e.length)throw Nt("InvalidKey","held keys must not be empty","empty_chord");let r={target:this.#_,keys:[...e],duration:n,opts:Gt(t)};return this.#b.act("holdKeys",r,t.verify)}}class tn{kind;target;pointer;keyboard;link;constructor(e,t,n){this.link=e,this.kind=t,this.target=n,this.pointer=new Qt(e,n),this.keyboard=new en(e,n)}async screenshot(e){let t=Ht(e),n={target:this.target,...void 0===t?{}:{caps:t}};return new Kt(this.link,await this.link.read("capture",n,Bt))}async observe(e){let t=Ht(e),n={target:this.target,...void 0===t?{}:{caps:t},...void 0===e?.ax?{}:{ax:e.ax}},{frame:r,ax:i}=await this.link.read("observe",n,e=>{let t=Bt(e),n=gt(e,"ax");return void 0===t||void 0===n?void 0:{frame:t,ax:n}});return{frame:new Kt(this.link,r),ax:i}}ax(e){let t={target:this.target,...void 0===e?{}:{opts:e}};return this.link.read("ax.snapshot",t,e=>gt(e))}}var nn=new Set(["1","true","yes"]);async function rn(e,t){return(await e.read("windows",{},e=>at(e,ct))).filter(e=>Jt(e,t))}async function on(e,t){switch(t.kind){case"elementExists":try{return await e.read("ax.node",{ref:t.ref},ft),t.exists??!0}catch(e){if(e instanceof Ct&&"StaleRef"===e.code)return!(t.exists??!0);throw e}case"elementValue":return(await e.read("ax.node",{ref:t.ref},ft)).value===t.value;case"elementEnabled":return(await e.read("ax.node",{ref:t.ref},ft)).enabled===(t.enabled??!0);case"elementSelected":{let n=await e.read("ax.attributes",{ref:t.ref},Pt);return nn.has((n.AXSelected??"").toLowerCase())===(t.selected??!0)}case"windowExists":return(await rn(e,t.window)).length>0;case"windowGone":return 0===(await rn(e,t.window)).length;case"windowBounds":{let o=await rn(e,t.window);if(o.length>1)throw Nt("InvalidTarget","verify windowBounds matches more than one window","ambiguous",{candidates:o});let[s]=o;return void 0!==s&&(n=s.bounds,r=t.bounds,i=t.tolerance??0,["x","y","width","height"].every(e=>{let t=r[e];return void 0===t||Math.abs(n[e]-t)<=i}))}}var n,r,i}function sn(e,t){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}async function an(e,t,n={}){let r=n.timeoutMs??2e3;if(!Number.isFinite(r)||r<0)throw Nt("InvalidTarget","verify timeoutMs must be a finite, non-negative number","invalid_timeout");let i=Math.max(n.intervalMs??100,10),{signal:o}=n,s=Date.now(),a=s+r,l=0;for(;;){if(o?.aborted)throw Nt("Cancelled","verify was cancelled","aborted");let n;try{l+=1,n=await on(e,t)}catch(e){return{status:"unknown",reads:l,elapsedMs:Date.now()-s,cause:e}}let r=Date.now();if(n)return{status:"satisfied",reads:l,elapsedMs:r-s};if(r>=a)return{status:"unsatisfied",reads:l,elapsedMs:r-s};try{await sn(Math.min(i,a-r),o)}catch(e){throw Nt("Cancelled","verify was cancelled","aborted",{cause:e})}}}var ln=e=>void 0===e?.delivery?{}:{opts:{deliveryMode:e.delivery}};class un{ref;node;#b;#k;constructor(e,t,n,r){this.#b=e,this.#k=t,this.ref=n,this.node=r}read(){return this.#b.read("ax.node",{ref:this.ref},ft)}press(e){return this.#b.act("ax.perform",{ref:this.ref,action:"press"},e?.verify)}click(e){return this.#b.act("ax.click",{ref:this.ref,...ln(e)},e?.verify)}setValue(e,t){return this.#b.act("ax.setValue",{ref:this.ref,value:e},t?.verify)}async type(e,t){let n=await this.#b.exec("ax.typeText",{ref:this.ref,text:e,...ln(t)});if(!et(n)||"inserted"!==n.method&&"keys"!==n.method)throw jt("ax.typeText","exec",n);let r={...this.#b.report("ax.typeText",n.report),input:n.method};return this.#b.verifyAfter(r,t?.verify)}focus(e){return this.#b.act("ax.focus",{ref:this.ref},e?.verify)}perform(e,t){return this.#b.act("ax.perform",{ref:this.ref,action:e},t?.verify)}attributes(){return this.#b.read("ax.attributes",{ref:this.ref},Pt)}drill(e){let t={target:this.#k,opts:{...e,root:this.ref}};return this.#b.read("ax.snapshot",t,e=>gt(e))}}class cn{#b;#x;constructor(e,t){this.#b=e,this.#x=t}items(e=[]){return this.#b.read("menus.items",{windowId:this.#x,path:[...e]},e=>at(e,vt))}select(e,t){let n={windowId:this.#x,path:[...e],...void 0===t?.delivery?{}:{deliveryMode:t.delivery}};return this.#b.act("menus.select",n,t?.verify)}}class dn extends tn{id;identity;app;title;pid;bounds;focused;menu;constructor(e,t){super(e,"window",t.id),this.id=t.id,this.identity=t.identity,this.app=t.app,this.title=t.title,this.pid=t.pid,this.bounds=t.bounds,this.focused=t.focused,this.menu=new cn(e,t.id)}raise(e){return this.link.act("raiseWindow",{windowId:this.id},e?.verify)}element(e){return new un(this.link,this.id,e,null)}async find(e){return(await this.link.read("ax.query",{target:this.id,query:e},e=>at(e,ft))).map(e=>new un(this.link,this.id,e.ref,e))}}class hn{desktop;control;stop;audit;epoch;#b;constructor(e,t){this.#b=e,this.desktop=new tn(e,"desktop","desktop"),this.control=new Zt(e,t),this.stop=function(e){return{status:()=>e.read("stopPath.status",{},St),on:t=>e.on("stopPath.changed",t)}}(e),this.audit=function(e){return{on:t=>e.on("audit",t)}}(e),this.epoch=function(e){return{on:t=>e.on("epoch.changed",t)}}(e)}capabilities(){return this.#b.read("capabilities",{},Ot)}displays(){return this.#b.read("displays",{},e=>at(e,dt))}async windows(e){return(await this.#O(e)).map(e=>new dn(this.#b,e))}async window(e){let t=await this.#O(e),[n]=t;if(void 0===n)throw Nt("WindowNotFound",`no window matches ${JSON.stringify(e)}`,"no_match");if(t.length>1)throw Nt("InvalidTarget",`${t.length} windows match ${JSON.stringify(e)}`,"ambiguous",{candidates:t});return new dn(this.#b,n)}verify(e,t){return an(this.#b,e,t)}batch(e,t){return async function(e,t,n={}){let r=[],i=null;for(let[o,s]of t.entries()){let t=s.label??null;if(null===i)try{n.signal?.throwIfAborted(),r.push({label:t,status:"ok",report:await s.run(e)})}catch(e){let s=e instanceof Ct?e:n.signal?.aborted?new Ct("Cancelled","batch was cancelled",{disposition:{delivery:"not_delivered",retry:"safe"},reason:"aborted",cause:e}):Mt("batch","exec",e);r.push({label:t,status:"failed",report:Ut(s),error:s}),i=o}else r.push({label:t,status:"skipped"})}return{completed:r.filter(e=>"ok"===e.status).length,of:t.length,stoppedAt:i,steps:r}}(this,e,t)}async close(){this.#b.close()}async#O(e){return(await this.#b.read("windows",{},e=>at(e,ct))).filter(t=>Jt(t,e))}}class pn{#S;#E;#n=new Map;#$;#P=!1;constructor(e,t){this.#S=e,this.#$=t,this.#E=e.notifications.subscribe(e=>this.#I(e))}async read(e,t,n){let r=await this.#T(e,t,"read"),i=n(r);if(void 0===i)throw jt(e,"read",r);return i}async act(e,t,n){return this.verifyAfter(this.report(e,await this.#T(e,t,"exec")),n)}report(e,t){if(null==t)return{disposition:{delivery:"delivered_unverified",retry:"unsafe"},delivered:null,effect:"unverifiable",route:null,hit:null,focusRestoration:"not_confirmed",openedSurfaces:[],nextCall:null,note:null,warning:null,auditIds:[],timings:null,legacy:!0};let n=function(e){if(!et(e))return;let t=bt(e.disposition);if(void 0===t||!wt.has(e.effect)||!kt.has(e.focusRestoration))return;if(!ot(e.auditIds))return;if(!it(e.route)&&!_t.has(e.route))return;let n=it(e.delivered)?null:et(e.delivered)&&nt(e.delivered.count)&&nt(e.delivered.of)?{count:e.delivered.count,of:e.delivered.of}:void 0,r=!!et(e.hit)&&st(e.hit.label,tt),i=it(e.hit)?null:et(e.hit)&&tt(e.hit.role)&&!1!==r?{role:e.hit.role,label:r}:void 0,o=it(e.openedSurfaces)?[]:at(e.openedSurfaces,xt),s=it(e.nextCall)?null:et(e.nextCall)&&tt(e.nextCall.method)&&et(e.nextCall.args)?{method:e.nextCall.method,args:e.nextCall.args}:void 0,a=st(e.note,tt),l=st(e.warning,tt);return void 0!==n&&void 0!==i&&void 0!==o&&void 0!==s&&!1!==a&&!1!==l?{disposition:t,delivered:n,effect:e.effect,route:e.route??null,hit:i,focusRestoration:e.focusRestoration,openedSurfaces:o,nextCall:s,note:a,warning:l,auditIds:e.auditIds,timings:null,legacy:!1}:void 0}(t);if(void 0===n)throw jt(e,"exec",t);return n}async verifyAfter(e,t){if(void 0===t)return e;return function(e,t){return"unknown"===t.status?e:{...e,effect:"satisfied"===t.status?"confirmed":"no_change"}}(e,await an(this,t.expectation,{timeoutMs:t.timeoutMs}))}exec(e,t){return this.#T(e,t,"exec")}on(e,t){let n=this.#n.get(e)??new Set;this.#n.set(e,n);let r=t;return n.add(r),()=>{n.delete(r)}}close(){this.#P||(this.#P=!0,this.#E(),this.#n.clear())}async#T(e,t,n){if(this.#P)throw new Ct("Closed",`${e}: this SDK connection is closed`,{disposition:{delivery:"not_delivered",retry:"safe"},reason:"sdk_closed"});try{return await this.#S.call(e,t)}catch(t){throw Mt(e,n,t)}}#I(e){let t=this.#n.get(e.method);if(void 0===t||0===t.size)return;let n=this.#$[e.method],r=void 0===n?e.params:n(e.params);if(void 0!==r)for(let e of[...t])try{e(r)}catch(e){queueMicrotask(()=>{throw e})}}}import fn from"node:fs";import mn from"node:net";import gn from"node:path";var vn={"session.open":"hostOnly","session.close":"hostOnly","control.grant":"hostOnly","control.revoke":"hostOnly","stopPath.start":"hostOnly","stopPath.heartbeat":"hostOnly","stopPath.resume":"hostOnly","$/test.advanceClock":"testOnly"},yn={env:process.env,platform:process.platform,euid:()=>process.geteuid?.()??-1,serverUid:e=>{let t=fn.lstatSync(e);if(!t.isSocket())throw Error(`${e} is not a socket`);return t.uid}},bn=(e,t)=>Nt("Closed",e,t);class wn extends Error{rpcCode;data;code;nothingSent;constructor(e){super(e.message),this.name="AttachPortFailure",this.rpcCode=e.rpcCode,this.data=e.data,this.code=e.code,this.nothingSent=e.nothingSent}}async function _n(e,t=yn){if("1"===t.env.SENPI_DESKTOP_HOST)throw Nt("ControlRequired","attach is not available inside a host session; use the host's computer tool","attach_inside_session");if("win32"===t.platform)throw Nt("InvalidTarget","attach over a Windows named pipe is not available","unsupported_transport");let n,r=function(e,t){let n,r=gn.dirname(e),i=gn.basename(e);try{n=fn.openSync(r,fn.constants.O_RDONLY|fn.constants.O_DIRECTORY|fn.constants.O_NOFOLLOW)}catch(e){throw bn(`${r}: cannot open the endpoint directory: ${String(e)}`,"endpoint_refused")}try{let e=t.euid(),o=fn.fstatSync(n);if(o.uid!==e)throw bn(`${r} is owned by uid ${o.uid}, not ${e}`,"endpoint_refused");if(63&o.mode){let e=(4095&o.mode).toString(8);throw bn(`${r} has mode ${e}; it must not be accessible to group or other`,"endpoint_refused")}let s="linux"===t.platform?`/proc/self/fd/${n}`:r,a=fn.statSync(gn.join(s,"..")),l=!!(512&a.mode);if(a.uid!==e&&0!==a.uid)throw bn(`${r}/.. is owned by uid ${a.uid}`,"endpoint_refused");if(18&a.mode&&!l)throw bn(`${r}/.. is writable by group or other and not sticky`,"endpoint_refused");return{fd:n,entry:gn.join(s,i)}}catch(e){throw fn.closeSync(n),e}}(e,t);try{n=await function(e){let{promise:t,resolve:n,reject:r}=Promise.withResolvers(),i=mn.createConnection({path:e});return i.once("connect",()=>{i.off("error",r),n(i)}),i.once("error",r),t}(r.entry);let i,o=t.euid();try{i=t.serverUid(r.entry)}catch(t){throw n.destroy(),bn(`${e}: the server's uid is unavailable: ${String(t)}`,"server_refused")}if(i!==o)throw n.destroy(),bn(`${e} is served by uid ${i}, not ${o}`,"server_refused")}catch(t){if(t instanceof Ct)throw t;throw bn(`${e}: cannot connect: ${String(t)}`,"unreachable")}finally{fn.closeSync(r.fd)}return new kn(n)}class kn{#C;#z=new Map;#n=new Set;#P;#R=1;#A="";#N=!1;constructor(e){this.#C=e,e.setEncoding("utf8"),e.on("data",e=>this.#j(e));let t="";e.on("error",e=>{t=`: ${e.message}`}),this.#P=new Promise(n=>{e.once("close",()=>{this.#N=!0;let e=new wn({message:`the desktop daemon connection closed${t}`,code:"Closed"});for(let t of this.#z.values())t.cleanup(),t.reject(e);this.#z.clear(),n()})})}notifications={subscribe:e=>(this.#n.add(e),()=>{this.#n.delete(e)})};call(e,t,n={}){let r=vn[e];if(void 0!==r)return Promise.reject(new wn({message:`${e} is not available over attach`,rpcCode:re,data:{reason:r},nothingSent:!0}));if(this.#N)return Promise.reject(new wn({message:`${e}: the connection is closed`,code:"Closed",nothingSent:!0}));let i=this.#R++,{promise:o,resolve:s,reject:a}=Promise.withResolvers(),l=()=>this.#M({jsonrpc:"2.0",method:"$/cancel",params:{id:i}}),u=void 0===n.timeoutMs?void 0:setTimeout(l,n.timeoutMs);n.signal?.addEventListener("abort",l,{once:!0});return this.#z.set(i,{resolve:s,reject:a,cleanup:()=>{clearTimeout(u),n.signal?.removeEventListener("abort",l)}}),this.#M({jsonrpc:"2.0",id:i,method:e,params:t}),o}async close(){this.#C.end(),await this.#P}#M(e){this.#C.write(`${JSON.stringify(e)}\n`)}#j(e){this.#A+=e;let t=this.#A.indexOf("\n");for(;t>=0;){let e=this.#A.slice(0,t).trim();this.#A=this.#A.slice(t+1),e.length>0&&this.#U(e),t=this.#A.indexOf("\n")}}#U(e){let t;try{t=JSON.parse(e)}catch{return void this.#C.destroy(Error(`the desktop daemon sent a line that is not JSON: ${e.slice(0,200)}`))}if("string"==typeof t.method&&void 0===t.id){for(let e of[...this.#n])e(t);return}if("number"!=typeof t.id)return;let n=this.#z.get(t.id);if(void 0===n)return;if(this.#z.delete(t.id),n.cleanup(),void 0===t.error)return void n.resolve(t.result);let{error:r}=t;n.reject(new wn({message:r.message,rpcCode:r.code,data:r.data??null}))}}var xn={audit:function(e){if(!(et(e)&&tt(e.target)&&tt(e.delivery)&&nt(e.durationMs)))return;let t=tt(e.action)?e.action:ie;return{...e,action:t}},"epoch.changed":function(e){return et(e)&&Et.has(e.reason)?e:void 0},"stopPath.changed":St};class On extends hn{#S;constructor(e,t){super(new pn(e,xn),t),this.#S=e}async close(){await super.close(),await this.#S.close()}}async function Sn(e,t={}){if("inProcess"===e?.kind)return new hn(new pn(e.port,xn),t.confirmControl);if("spawn"===e?.kind)return new On(await async function(e){if("1"===globalThis.process?.env?.SENPI_DESKTOP_HOST)throw Nt("ControlRequired","spawn is refused inside an omo session: use the session's own computer instead of starting a second engine","spawn_inside_session",{disposition:{delivery:"not_delivered",retry:"after_user"},hint:"use the host computer global"});if("function"!=typeof e.launch)throw Nt("InvalidTarget","a spawn transport needs a launch function","missing_launch");try{return await e.launch(e.settings)}catch(e){if(e instanceof Ct)throw e;let t=e instanceof Error?e.message:String(e);throw new Ct("Internal",`desktop engine launch failed: ${t}`,{disposition:{delivery:"not_delivered",retry:"safe"},reason:"launch_failed",cause:e})}}(e),t.confirmControl);if("attach"===e?.kind)return new On(await _n(e.endpoint),t.confirmControl);throw Nt("InvalidTarget",`transport kind ${String(e?.kind)} is not available in this SDK`,"unsupported_transport")}Object.freeze({focus:"never",cursor:"never",physical:"never"}),Object.freeze({focus:"never",cursor:"never",physical:"allowed"}),Object.freeze({focus:"activate",cursor:"move",physical:"allowed"});import{spawn as En}from"node:child_process";import{createInterface as $n}from"node:readline";import{spawn as Pn}from"node:child_process";import{createInterface as In}from"node:readline";var Tn=new Set(["global","host-relay","none"]),Cn=["unknown","hostOnly","testOnly"],zn={suspended:"boolean",globalLive:"boolean",hostRelayLive:"boolean",heartbeatFresh:"boolean",stopPath:"string",reason:"string?"},Rn={backend:"string",displayServer:"string?",capture:"boolean",input:"boolean",ax:"boolean",backgroundWindowInput:"boolean",cursorOverlay:"boolean?",interventionWatch:"string?",displayAsleep:"boolean?",capturePermission:"string",inputPermission:"string",axPermission:"string",displayCount:"number",focusGuard:"boolean",stopPath:"string",stopReason:"string?",integrityLevel:"string?",screenLocked:"boolean"},An={action:"string",target:"string",delivery:"string",frameId:"string?",code:"string?",durationMs:"number",focusRestored:"boolean?",textLength:"number?",textDelivered:"number?",textSha256:"string?"};function Nn(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function jn(e,t){return!!Nn(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 Mn(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function Un(e){return jn(e,zn)&&function(e,t){return"string"==typeof e&&t.has(e)}(e.stopPath,Tn)}function Ln(e){return jn(e,Rn)&&Mn(e.deliveryModes)&&(void 0===e.cursorOverlay||"boolean"==typeof e.cursorOverlay)}function Dn(e){if(!function(e){return jn(e,An)&&(void 0===e.keys||null===e.keys||Mn(e.keys))}(e))return;let t=ee.find(t=>t===e.action)??ie,{code:n}=e;return null==n?{...e,action:t,code:n}:{...e,action:t,code:ne.find(e=>e===n)??ie}}function Zn(e){if(!Nn(e)||"string"!=typeof e.abi||"string"!=typeof e.protocolVersion)return;let{features:t}=e;return null==t||Mn(t)?{abi:e.abi,protocolVersion:e.protocolVersion,features:t??[]}:void 0}function Fn(e){if(!Nn(e))return null;let t=ne.find(t=>t===e.code);if(void 0!==t){let n=function(e){if(!Nn(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},..."string"==typeof e.reason?{reason:e.reason}:{}}}let n=Cn.find(t=>t===e.reason);return void 0===n?null:{reason:n}}var Jn="denied";class qn{#L;#z=new Map;#D=!1;constructor(e){this.#L=e}sent(e){let{id:t,method:n}=e;"number"==typeof t&&("capabilities"===n&&this.#z.set(t,{opens:!1}),"session.open"===n&&this.#z.set(t,this.#D?{opens:!0,probe:this.#L()}:{opens:!0}))}received(e){if(0===this.#z.size)return e;let t=Wn(e);if(!Nn(t)||"number"!=typeof t.id||!this.#z.has(t.id))return e;let n=this.#z.get(t.id);this.#z.delete(t.id);let{result:r}=t,i=!0===n?.opens&&Nn(r)?r.capabilities:r;if(!Ln(i))return e;this.#D=function(e){return[e.capturePermission,e.inputPermission,e.axPermission].includes(Jn)}(i);let o=n?.probe;return void 0!==o&&Nn(r)?o.then(n=>{if(void 0===n)return e;let o=function(e,t){let n=e;e.capturePermission===Jn&&(n={...n,capturePermission:t.capturePermission,capture:t.capture,displayCount:t.displayCount});e.inputPermission!==Jn&&e.axPermission!==Jn||(n={...n,inputPermission:t.inputPermission,axPermission:t.axPermission,input:t.input,ax:t.ax,backgroundWindowInput:t.backgroundWindowInput});return n}(i,n);return JSON.stringify({...t,result:{...r,capabilities:o}})}):e}}function Wn(e){try{return JSON.parse(e)}catch(e){if(e instanceof SyntaxError)return;throw e}}class Vn extends Error{diagnostic;constructor(e){super(`${e.message} ${e.cause}`),this.name="DesktopEngineUnavailableError",this.diagnostic=e}}function Bn(e){return()=>Hn(e??function(){let e=Ie();if(null===e.path)throw new Vn(e.diagnostic);return e.path}())}function Hn(e){return En(e,["--stdio"],{stdio:"pipe",windowsHide:!0})}class Kn{path;exited;#Z;#F="";#J="";#q=!0;#W=new F;#V;#B;constructor(e,t){this.#Z=e,this.path=e.spawnfile,this.#V=new qn(function(e,t,n=5e3){return()=>new Promise(r=>{let i=Pn(e,[...t],{stdio:"pipe",windowsHide:!0}),o=new Map,s=!1,a=e=>{s||(s=!0,clearTimeout(l),r(e),i.stdin.end(),i.kill())},l=setTimeout(()=>a(void 0),n);i.on("error",()=>a(void 0)),i.stdin.on("error",()=>a(void 0)),i.on("close",()=>a(void 0)),i.stderr.resume(),In({input:i.stdout}).on("line",e=>{let t=Wn(e);if(!Nn(t)||void 0===t.id)return;if(!("result"in t))return a(void 0);if(o.set(t.id,t.result),!o.has(1)||!o.has(2))return;let n=Zn(o.get(1)),r=o.get(2),i=n?.abi===Q&&n.protocolVersion===X;a(i&&Ln(r)?r:void 0)});for(let[e,t]of[[1,"engine.hello"],[2,"capabilities"]])i.stdin.write(`${JSON.stringify({jsonrpc:"2.0",id:e,method:t,params:{}})}\n`)})}(e.spawnfile,e.spawnargs.slice(1))),e.stderr.setEncoding("utf8"),e.stderr.on("data",e=>{this.#W.push(e),this.#F=(this.#F+e).slice(-4096)}),e.stdin.on("error",e=>this.#H(`stdin: ${e.message}`)),e.on("error",e=>{this.#W.disable(),this.#H(`spawn: ${e.message}`)}),$n({input:e.stdout}).on("line",e=>this.#I(e,t.onLine)),this.exited=new Promise(n=>{e.on("close",(e,r)=>{this.#q=!1;let i=this.#K(e,r),o=this.#W.finish(e,r,i),s=()=>{t.onExit(i,o),n()};void 0===this.#B?s():this.#B.then(s)})})}get alive(){return this.#q}finishStartup(){this.#W.disable()}write(e){this.#q&&!this.#Z.stdin.writableEnded&&(this.#V.sent(e),this.#Z.stdin.write(`${JSON.stringify({jsonrpc:"2.0",...e})}\n`))}end(){this.#Z.stdin.end()}kill(){this.#W.disable(),this.#q&&(this.#q=!1,this.#Z.kill())}#I(e,t){let n=this.#V.received(e);if(void 0===this.#B&&"string"==typeof n)return void t(n);let r=(this.#B??Promise.resolve()).then(()=>n).then(t);this.#B=r,r.then(()=>{this.#B===r&&(this.#B=void 0)})}#H(e){this.#J=""===this.#J?e:`${this.#J}; ${e}`}#K(e,t){return`desktop engine exited (code ${e??"null"}, signal ${t??"null"})${""===this.#J?"":`; ${this.#J}`}; stderr: ${this.#F.trim()||"<empty>"}`}}class Gn extends Error{code;engineRestarted;constructor(e,t,n=!1){super(t),this.name="DesktopServiceError",this.code=e,this.engineRestarted=n}}class Yn extends Error{method;rpcCode;data;constructor(e,t){super(t.message),this.name="DesktopEngineRpcError",this.method=e,this.rpcCode=t.code,this.data=Fn(t.data)}}class Xn{#G;#Y;#z=new Map;#R=1;#K;constructor(e,t){this.#Y=t,this.#G=new Kn(e,{onLine:e=>this.#X(e),onExit:(e,t)=>this.#Q(e,t)})}get enginePath(){return this.#G.path}get alive(){return void 0===this.#K&&this.#G.alive}get exited(){return this.#G.exited}request(e,t,n={}){if(!this.alive)return Promise.reject(new Gn("Closed",this.#K??"desktop engine was killed"));if(n.signal?.aborted)return Promise.reject(new Gn("Cancelled",`${e} was cancelled before it was sent`));let r=this.#R++,{promise:i,resolve:o,reject:s}=Promise.withResolvers(),a={method:e,resolve:o,reject:s,release:()=>{},cancelled:void 0};this.#z.set(r,a);let{signal:l,timeoutMs:u}=n,c=()=>this.#ee(r,new Gn("Cancelled",`${e} was cancelled`)),d=void 0===u?void 0:setTimeout(()=>this.#ee(r,new Gn("Timeout",`${e} timed out after ${u} ms`)),u);return l?.addEventListener("abort",c,{once:!0}),a.release=()=>{clearTimeout(d),l?.removeEventListener("abort",c)},this.#G.write({id:r,method:e,params:t}),i}cancelHolds(){for(let[e,t]of this.#z)Qn(t.method)&&this.#ee(e,new Gn("Cancelled","desktop session is closing"))}end(){this.#G.end()}kill(){this.#G.kill()}#ee(e,t){let n=this.#z.get(e);if(void 0===n||void 0!==n.cancelled)return;n.release(),n.cancelled=t,this.#G.finishStartup();let r=setTimeout(()=>{this.#te(e),n.reject(new Gn(t.code,`${t.message}; desktop engine restarted; captures and ax refs were reset`,!0)),this.#G.kill()},Qn(n.method)?2500:750);n.release=()=>clearTimeout(r),this.#G.write({method:"$/cancel",params:{id:e}})}#te(e){let t=this.#z.get(e);return this.#z.delete(e),t?.release(),t}#X(e){let t=function(e){try{return JSON.parse(e)}catch(e){if(e instanceof SyntaxError)return;throw e}}(e);if(!Nn(t))return this.#G.kill(),void(this.#K=`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.#Y.onNotification(t.method,t.params);let n="number"==typeof t.id?this.#te(t.id):void 0;if(void 0===n)return;if("engine.hello"===n.method&&this.#G.finishStartup(),void 0!==n.cancelled){let e=function(e,t){if(!Qn(e)||!Nn(t)||"number"!=typeof t.code||"string"!=typeof t.message)return;if("Cancelled"===(Nn(t.data)?t.data.code:void 0)&&!t.message.includes(er))return;return new Yn(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;Nn(r)&&"number"==typeof r.code&&"string"==typeof r.message?n.reject(new Yn(n.method,{code:r.code,message:r.message,data:r.data})):n.reject(new Gn("Internal",`desktop engine sent a malformed reply to ${n.method}`))}#Q(e,t){let n=void 0===this.#K?t:void 0;this.#K??=e;let r=n??new Gn("Closed",this.#K);for(let e of[...this.#z.keys()]){let t=this.#te(e);void 0!==t?.cancelled&&(t.cancelled.cause=r),t?.reject(t.cancelled??r)}this.#Y.onExit()}}var Qn=e=>"holdKeys"===e||"holdMouse"===e;var er="input release also failed";class tr extends Error{reason;constructor(e,t){super(t),this.name="ComputerRunError",this.reason=e}}class nr{#ne=[];text(e){this.#ne.push({type:"text",text:e})}image(e,t){this.#ne.push({type:"image",data:e,mimeType:t})}finish(){return[...this.#ne]}}async function rr(e,t){let n=new Map;return{computer:await Sn({kind:"inProcess",port:{call:async(r,i)=>{let o=await e.call(r,i),s=t[r];if(void 0!==s&&!s(o))throw new Gn("Internal",`desktop engine sent a malformed ${r} result`);return n.set(r,o),o},notifications:{subscribe:()=>()=>{}},close:async()=>{}}}),reply:e=>n.get(e)}}async function ir(e,t){try{return await t()}catch(t){throw function(e,t){return e instanceof Ct?void 0!==e.cause?e.cause:"malformed_result"===e.data.reason?new Gn("Internal",`desktop engine sent a malformed ${t} result`):e:e}(t,e)}}function or(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 tr("readOnly",`read-only run: '${n}' requires read_only: false`);e.signal.throwIfAborted()}(e.context,t,n),r(e))))}import{randomUUID as sr}from"node:crypto";var ar={id:"string",name:"string",x:"number",y:"number",width:"number",height:"number",scale:"number",pixelX:"number",pixelY:"number",pixelWidth:"number",pixelHeight:"number",isPrimary:"boolean"},lr={id:"string",title:"string",app:"string",pid:"number?",x:"number",y:"number",width:"number",height:"number",focused:"boolean",elevated:"boolean?"},ur={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"},cr={title:"string",enabled:"boolean",checked:"boolean",hasSubmenu:"boolean",shortcut:"string?"},dr={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?"},hr=e=>jn(e,ur)&&(void 0===e.actions||null===e.actions||Mn(e.actions)),pr=e=>jn(e,dr)&&(null==e.region||jn(e.region,{x:"number",y:"number",width:"number",height:"number"})),fr=e=>pr(e)&&"number"==typeof e.coordinateWidth&&"number"==typeof e.coordinateHeight&&null!=e.region,mr=e=>pr(e)&&"number"==typeof e.coordinateWidth&&"number"==typeof e.coordinateHeight&&jn(e,{ax:"string",nodeCount:"number",truncated:"boolean"}),gr=e=>"object"==typeof e&&null!==e&&("inserted"===e.method||"keys"===e.method),vr=new Set(["not_delivered/safe","not_delivered/after_user","delivery_uncertain/unsafe","delivery_uncertain/unknown","delivered_unverified/unsafe","delivered_verified/unsafe","unknown/unknown"]);var yr=e=>jn(e,{effect:"string",focusRestoration:"string",route:"string?",note:"string?",warning:"string?"})&&function(e){return jn(e,{delivery:"string",retry:"string"})&&vr.has(`${e.delivery}/${e.retry}`)}(e.disposition)&&Mn(e.auditIds)&&(null==e.delivered||jn(e.delivered,{count:"number",of:"number"}))&&(null==e.hit||jn(e.hit,{role:"string",label:"string?"}))&&(void 0===e.openedSurfaces||Array.isArray(e.openedSurfaces)&&e.openedSurfaces.every(Nn))&&(null==e.nextCall||jn(e.nextCall,{method:"string"})&&Nn(e.nextCall.args)),br=e=>null===e||yr(e),wr=e=>Nn(e)&&"string"==typeof e.text,_r=e=>Array.isArray(e)&&e.every(e=>Mn(e)&&2===e.length);function kr(e){return t=>Array.isArray(t)&&t.every(e)}function xr(e){return t=>null===t||e(t)}function Or(e,t,n){if(!n(t))throw new Gn("Internal",`desktop engine sent a malformed ${e} result`);return t}async function Sr(e,t,n){try{Or(t,await e.call(t,n),br)}catch(e){if(e instanceof Yn&&-32601===e.rpcCode)throw new tr("unavailable",`${t} is unavailable in this desktop engine; update the engine for bounded holds`);throw e}}async function Er(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=Or(s,await e.call(s,a),void 0===r?pr:fr);return $r(e,l,n)}function $r(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,h=t.coordinateWidth??s,p=t.coordinateHeight??a;return{target:t.target,frameId:d,width:s,height:a,sourceWidth:l,sourceHeight:u,coordinateWidth:h,coordinateHeight:p,...null==t.region?{}:{region:t.region},scale:c,...void 0===o?{}:{path:o}}}function Pr(e){if(!Number.isFinite(e)||e<0||e>100)throw new tr("assertion","hold duration must be finite seconds in 0..=100")}function Ir(e={}){let{button:t,count:n,modifiers:r,delivery:i}=e;return{button:t,count:n,modifiers:r,deliveryMode:i}}function Tr(e){return"string"!=typeof e?e:e.split("+").map(e=>e.trim()).filter(e=>e.length>0)}function Cr(e,t,n,r){return e(t,async({call:e})=>{Or(n,await e(n,r),br)})}class zr{#_;#re;constructor(e,t,n){this.#_=t,this.#re=or(e,n)}screenshot(e){return this.#re("screenshot",t=>Er(t,this.#_,e))}zoom(e,t){return this.#re("zoom",n=>Er(n,this.#_,t,e))}click(e,t,n){return Cr(this.#re,"click","click",{target:this.#_,x:e,y:t,opts:Ir(n)})}doubleClick(e,t,n){let r=Ir({...n,count:2});return Cr(this.#re,"doubleClick","click",{target:this.#_,x:e,y:t,opts:r})}move(e,t){return Cr(this.#re,"move","moveMouse",{target:this.#_,x:e,y:t})}drag(e,t){let n=e.map(([e,t])=>({x:e,y:t}));return Cr(this.#re,"drag","drag",{target:this.#_,path:n,opts:Ir(t)})}scroll(e,t,n={}){let{dx:r=0,dy:i=0}=n,o={target:this.#_,x:e,y:t,dx:r,dy:i,opts:Ir(n)};return Cr(this.#re,"scroll","scroll",o)}type(e,t){return Cr(this.#re,"type","typeText",{target:this.#_,text:e,opts:Ir(t)})}press(e,t){let n={target:this.#_,keys:Tr(e),opts:Ir(t)};return Cr(this.#re,"press","keyChord",n)}holdKeys(e,t){return this.#re("holdKeys",async n=>{if(Pr(t?.duration),!Array.isArray(e)||0===e.length)throw new tr("assertion","held keys must not be empty");await Sr(n,"holdKeys",{target:this.#_,keys:e,duration:t.duration,opts:Ir(t)})})}holdMouse(e,t,n){return this.#re("holdMouse",async r=>{Pr(n?.duration),await Sr(r,"holdMouse",{target:this.#_,x:e,y:t,duration:n.duration,button:n.button,keys:n.keys,frameId:n.frameId,opts:Ir(n)})})}}var Rr={capabilities:Ln,displays:kr(e=>jn(e,ar)),windows:kr(e=>jn(e,lr)),raiseWindow:br,"menus.items":kr(e=>jn(e,cr)&&Mn(e.path)),"menus.select":br,"ax.query":kr(hr)};function Ar({title:e,path:t,enabled:n,checked:r,hasSubmenu:i,shortcut:o}){return{title:e,path:t,enabled:n,checked:r,hasSubmenu:i,shortcut:o}}function Nr(e){let{ref:t,role:n,nativeRole:r,title:i,value:o,description:s,enabled:a,focused:l,actions:u,childCount:c,bounds:d}=e;return{ref:t,role:n,nativeRole:r,title:i,value:o,description:s,enabled:a,focused:l,x:d?.x??null,y:d?.y??null,width:d?.width??null,height:d?.height??null,actions:u,childCount:c}}class jr extends zr{id;app;title;pid;bounds;focused;#re;#k;constructor(e,t,n){super(e,t.id,W),this.#re=or(e,W),this.#k=n,this.id=t.id,this.app=t.app,this.title=t.title,this.pid=t.pid??void 0,this.bounds={x:t.x,y:t.y,width:t.width,height:t.height},this.focused=t.focused}raise(){return this.#re("raise",()=>ir("raiseWindow",async()=>{await this.#k.raise()}))}menu={items:e=>this.#re("menu.items",()=>ir("menus.items",async()=>(await this.#k.menu.items(e??[])).map(Ar))),select:(e,t)=>this.#re("menu.select",()=>ir("menus.select",async()=>{let n=t?.delivery;await this.#k.menu.select(e,void 0===n?void 0:{delivery:n})}))};ax(e){return this.#re("ax",async({call:t})=>Or("ax.snapshot",await t("ax.snapshot",{target:this.id,opts:e}),wr).text)}observe(e){return this.#re("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 Yn&&-32601===e.rpcCode)throw new tr("unavailable","observe is unavailable in this desktop engine; update the engine to use atomic observation");throw e}let c=Or("observe",r,mr),d=$r(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.#re("find",t=>ir("ax.query",async()=>(await this.#k.find(e)).flatMap(e=>null===e.node?[]:[new Ur(t,Nr(e.node))])))}ref(e){return this.#re("ref",t=>Mr(t,e))}}async function Mr(e,t){return new Ur(e,Or("ax.node",await e.call("ax.node",{ref:t}),hr))}class Ur{ref;role;nativeRole;title;description;enabled;focused;childCount;#re;constructor(e,t){this.#re=or(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}#ie(e,t,n){return this.#re(e,async({call:e})=>{Or(t,await e(t,{ref:this.ref,...n}),br)})}#oe(e,t){return this.#re(e,async({call:e})=>t(Or("ax.node",await e("ax.node",{ref:this.ref}),hr)))}value(){return this.#oe("value",e=>e.value??void 0)}setValue(e){return this.#ie("setValue","ax.setValue",{value:e})}bounds(){return this.#oe("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.#re("attributes",async({call:e})=>Object.fromEntries(Or("ax.attributes",await e("ax.attributes",{ref:this.ref}),_r)))}actions(){return this.#oe("actions",e=>e.actions??[])}perform(e){return this.#ie("perform","ax.perform",{action:e})}press(){return this.#ie("press","ax.perform",{action:"press"})}click(e){return this.#ie("click","ax.click",{opts:Ir(e)})}type(e,t){return this.#re("type",async({call:n})=>Or("ax.typeText",await n("ax.typeText",{ref:this.ref,text:e,opts:Ir(t)}),gr))}focus(){return this.#ie("focus","ax.focus",{})}parent(){return this.#re("parent",async e=>{let t=Or("ax.parent",await e.call("ax.parent",{ref:this.ref}),xr(hr));return null===t?null:new Ur(e,t)})}children(){return this.#re("children",async e=>Or("ax.children",await e.call("ax.children",{ref:this.ref}),kr(hr)).map(t=>new Ur(e,t)))}}function Lr(e){let t=or(e,J),n=t=>ir("windows",async()=>{let n=await rr(e,Rr),r=await n.computer.windows("string"==typeof t?{id:t}:function(e={}){return{...e.app?{app:e.app}:{},...e.title?{title:e.title}:{}}}(t)),i=new Map(r.map(e=>[e.id,e]));return n.reply("windows").flatMap(e=>{let t=i.get(e.id);return void 0===t?[]:[{record:e,window:t}]})}),r=({record:t,window:n})=>new jr(e,t,n),i=async(t,n)=>{let r=Or(t,await e.call(t,n),xr(hr));return null===r?null:new Ur(e,r)},o=new zr(e,"desktop",J);return{capabilities:()=>t("capabilities",()=>ir("capabilities",async()=>{let t=await(await rr(e,Rr)).computer.capabilities();return{...t,cursorOverlay:t.cursorOverlay??!1}})),displays:()=>t("displays",()=>ir("displays",async()=>{let t=await rr(e,Rr);return await t.computer.displays(),t.reply("displays")})),display:n=>t("display",async()=>{if("string"!=typeof n||0===n.length)throw new tr("assertion","display requires an id, 'active', or 'all'");return Object.assign(new zr(e,`display:${n}`,q),{id:n})}),windows:e=>t("windows",async()=>(await n(e??{})).map(({record:e})=>e)),window:e=>t("window",async()=>{let t=await n(e),[i,...o]=t;if(void 0===i)throw new tr("window",`no window matches ${JSON.stringify(e)}`);if(o.length>0){let n=t.map(({record:e})=>`${e.id} ${e.app} ${JSON.stringify(e.title)}`);throw new tr("window",`multiple windows match ${JSON.stringify(e)}:\n${n.join("\n")}`)}return r(i)}),focusedWindow:()=>t("focusedWindow",async()=>{let e=(await n({})).find(({window:e})=>e.focused);return void 0===e?null:r(e)}),screenshot:o.screenshot.bind(o),zoom:o.zoom.bind(o),click:o.click.bind(o),doubleClick:o.doubleClick.bind(o),move:o.move.bind(o),drag:o.drag.bind(o),scroll:o.scroll.bind(o),type:o.type.bind(o),press:o.press.bind(o),holdKeys:o.holdKeys.bind(o),holdMouse:o.holdMouse.bind(o),elementAt:(e,n)=>t("elementAt",()=>i("ax.elementAt",{target:"desktop",x:e,y:n})),focusedElement:()=>t("focusedElement",()=>i("ax.focused",{})),ref:e=>t("ref",t=>Mr(t,e)),clipboard:{read:()=>t("clipboard.read",async({call:e})=>Or("clipboard.read",await e("clipboard.read",{}),wr).text),write:e=>t("clipboard.write",async({call:t})=>{Or("clipboard.write",await t("clipboard.write",{text:e}),br)})},control:Jr(e,t)}}var Dr=5e3,Zr=3e3;function Fr(e){return Nn(e)&&"boolean"==typeof e.active}function Jr(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 tr("assertion","control.acquire requires a non-empty reason");let o=Or("control.state",await r("control.state",{}),Fr);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()-Dr);if(a<Zr)throw new tr("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}:Or("control.grant",await r("control.grant",{reason:i,confirmationId:sr()}),Fr)}),release:()=>t("control.release",async({call:e})=>{await e("control.revoke",{})}),state:()=>t("control.state",async({call:e})=>Or("control.state",await e("control.state",{}),Fr))}}import{randomUUID as qr}from"node:crypto";import{format as Wr}from"node:util";import Vr from"node:vm";import{existsSync as Br}from"node:fs";import{createRequire as Hr}from"node:module";import{fileURLToPath as Kr}from"node:url";import{Worker as Gr}from"node:worker_threads";var Yr=67108864,Xr=1e3,Qr=1048576,ei=1048576,ti=1048576,ni=8388608;var ri=new Set(["assertion","payloadSize","stalled","readOnly","window","wait","unavailable"]),ii={EvalError:EvalError,RangeError:RangeError,ReferenceError:ReferenceError,SyntaxError:SyntaxError,TypeError:TypeError,URIError:URIError};function oi(e){if(e instanceof tr)return{name:e.name,message:e.message,reason:e.reason};throw e}var si=new Map;async function ai(e,t,n={}){let{timeoutMs:r}=e,i=new AbortController,{signal:o}=i,s=setTimeout(()=>i.abort(new tr("timeout",`computer run timed out after ${r} ms`)),r),a=()=>i.abort(new tr("aborted","computer run was aborted"));e.signal?.addEventListener("abort",a,{once:!0}),e.signal?.aborted&&a();let l=e.snapshot.sessionId,u=si.get(l)??Promise.resolve(),c=()=>{},d=new Promise(e=>{c=e}),h=u.then(()=>d);si.set(l,h);try{return await function(e,t){return new Promise((n,r)=>{let i=()=>r(t.reason);if(t.aborted)return i();t.addEventListener("abort",i,{once:!0}),e.then(()=>{t.removeEventListener("abort",i),n()})})}(u,o),await function(e,t,n){let r,i,o=n.bridge??{};try{let e=function(e){let t=Kr(new URL("./omo-computer-run-worker.mjs",e)),n=Kr(new URL("./quickjs.wasm",e));return Br(t)?{worker:t,wasm:n}:{worker:Kr(new URL("./worker.ts",e)),wasm:Hr(e).resolve("quickjs-wasi/quickjs.wasm")}}(import.meta.url);if(r=n.workerPath??e.worker,i=e.wasm,!Br(i))throw Error(`missing ${i}`)}catch(e){return Promise.reject(new tr("crashed",`the QuickJS run cell could not be loaded: ${e instanceof Error?e.message:String(e)}`))}let s=new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT),a={code:e,wasmPath:i,interrupt:s,bridge:Object.keys(o),limits:{memoryBytes:Yr,outputBytes:Qr,returnBytes:ei,argsBytes:ti}};return new Promise((e,n)=>{t.throwIfAborted();let i=new Gr(r,{workerData:a}),l=[],u=!1,c=0,d=Promise.resolve(),h=()=>{Atomics.store(new Int32Array(s),0,1),i.terminate()},p=e=>{u||(u=!0,t.removeEventListener("abort",m),h(),e())},f=e=>p(()=>n(e)),m=()=>f(t.reason);t.addEventListener("abort",m,{once:!0});let g=e=>{u||i.postMessage(e)},v=async(e,n,r)=>{let i;try{let e=JSON.parse(r),o=await n(Array.isArray(e)?e:[],t);i=void 0===o?void 0:JSON.stringify(o)}catch(t){return void g({type:"settle",id:e,ok:!1,payload:JSON.stringify(oi(t))})}let o=void 0===i?0:Buffer.byteLength(i);if(o>ni){let t={name:"ComputerRunError",reason:"payloadSize",message:`computer run: the result is ${o} bytes, over the 8388608-byte cap`};return void g({type:"settle",id:e,ok:!1,payload:JSON.stringify(t)})}g({type:"settle",id:e,ok:!0,...void 0===i?{}:{payload:i}})};i.on("message",t=>{if(!u)switch(t.type){case"output":return void l.push({type:"text",text:t.text});case"call":{if(c++,c>Xr)return void f(new tr("calls","computer run made more than 1000 host calls"));let e=Object.hasOwn(o,t.name)?o[t.name]:void 0;return void 0===e?void f(new tr("crashed",`the QuickJS run cell called an unknown host function '${t.name}'`)):void(d=d.then(()=>v(t.id,e,t.args)).catch(f))}case"done":if(t.ok){let n=void 0===t.value?void 0:JSON.parse(t.value);p(()=>e({displays:l,returnValue:n,screenshots:[],audit:[]}))}else f(function(e){if(void 0!==e.thrown)return JSON.parse(e.thrown);let{name:t,message:n}=e;if("ComputerRunError"===t&&void 0!==e.reason&&ri.has(e.reason))return new tr(e.reason,n);if("InternalError"===t&&"out of memory"===n)return new tr("memory","computer run exceeded its 67108864-byte heap");if("RangeError"===t&&"Maximum call stack size exceeded"===n)return new tr("stack","computer run exceeded its stack limit");let r=ii[t],i=void 0===r?Error(n):new r(n);return void 0===r&&(i.name=t),void 0!==e.stack&&(i.stack=e.stack),i}(t.error));return}}),i.on("error",e=>f(new tr("crashed",`the QuickJS run cell crashed: ${e instanceof Error?e.message:String(e)}`))),i.on("exit",e=>f(new tr("crashed",`the QuickJS run cell exited with code ${e} before the run settled`)))})}(e.code,o,n)}catch(e){throw t.service.revokeControl().catch(e=>t.service.reportError(e)),e}finally{clearTimeout(s),e.signal?.removeEventListener("abort",a),o.aborted||i.abort(new tr("ended","computer run has ended")),c(),si.get(l)===h&&si.delete(l)}}function li(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 ui(e,t){return async(n,r={})=>{if("number"==typeof n)return li(n,e);if("function"!=typeof n)throw new tr("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 tr("wait",`wait(predicate) timed out after ${n} ms; the predicate never returned truthy`);await li(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 ci="computer-run.js";function di(e){return Nn(e)&&"ERR_SCRIPT_EXECUTION_TIMEOUT"===e.code}function hi(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 pi(e,t){let{code:n,snapshot:r,timeoutMs:i}=e,o=qr(),s=new AbortController,{signal:a}=s,l=Date.now()+i,u=e=>s.abort(e),c=()=>new tr("timeout",`computer run timed out after ${i} ms`),d=setTimeout(()=>u(c()),i),h=()=>u(new tr("aborted","computer run was aborted"));e.signal?.addEventListener("abort",h,{once:!0}),e.signal?.aborted&&h();let p=[],f=t.service.onAudit(e=>p.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 nr,screenshots:[],deadline:l},g=new Vr.Script(""),v=()=>{if(!a.aborted)try{g.runInContext(_,{timeout:Math.max(1,l-Date.now())})}catch(e){u(di(e)?c():e)}},y=e=>{let t=()=>setImmediate(v);return e.then(t,t),e},b=ui(a,i),w=(...e)=>m.output.text(Wr(...e)),_=Vr.createContext({desktop:Lr({context:m,call:(e,n)=>t.service.call(e,n,{signal:a}),resume:y,...void 0===t.confirmControl?{}:{confirmControl:t.confirmControl}}),wait:(e,t)=>y(b(e,t)),assert:(e,t)=>{if(!e)throw new tr("assertion",t??"Assertion failed")},tool:new Proxy({},{get:(e,n)=>e=>(a.throwIfAborted(),y(t.executeTool(String(n),e,{signal:a})))}),console:{log:w,info:w,warn:w,error:w,debug:w}},{name:ci,microtaskMode:"afterEvaluate"});try{a.throwIfAborted();let e=new Vr.Script(`((run) => (run.catch(() => undefined), run))((async () => {\n${n}\n})())`,{filename:ci,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(v)});return{displays:m.output.finish(),returnValue:hi(t),screenshots:[...m.screenshots],audit:[...p]}}catch(e){let n=di(e)?c():e;throw t.service.revokeControl().catch(e=>t.service.reportError(e)),n}finally{clearTimeout(d),e.signal?.removeEventListener("abort",h),f(),a.aborted||s.abort(new tr("ended","computer run has ended"))}}class fi extends Error{method;constructor(e,t){super(`desktop engine notification ${JSON.stringify(e)} ${t}`),this.name="DesktopNotificationError",this.method=e}}function mi(e,t){return e.add(t),()=>{e.delete(t)}}class gi{#se=new Set;#ae=new Set;#le=new Set;onAudit(e){return mi(this.#se,e)}onStopPathChange(e){return mi(this.#ae,e)}onError(e){return mi(this.#le,e)}emitError(e){for(let t of this.#le)t(e)}dispatch(e,t){let n=te.find(t=>t===e);void 0!==n?this.#ue(n,t):this.emitError(new fi(e,"is not part of the engine protocol"))}#ue(e,t){switch(e){case"audit":{let n=Dn(t);if(void 0!==n)for(let e of this.#se)e(n);else this.emitError(new fi(e,"is malformed"));return}case"stopPath.changed":if(Un(t))for(let e of this.#ae)e(t);else this.emitError(new fi(e,"is malformed"));return;case"engine.log":case"epoch.changed":return;default:!function(e){throw Error(`unhandled engine notification ${JSON.stringify(e)}`)}(e)}}}class vi{#ce=0;#de=0;#he=0;#pe=!1;get possiblyLive(){return this.#de>this.#he}get automaticLive(){return this.possiblyLive&&this.#pe}async grant(e,t,n=!1){if(t)return e();this.#ce+=1;let r=this.#ce,i={possiblyLive:this.#de,automatic:this.#pe};this.#de=r,this.#pe=n;try{return await e()}catch(e){throw e instanceof Yn&&this.#de===r&&(this.#de=i.possiblyLive,this.#pe=i.automatic),e}}async revoke(e){let t=this.#ce,n=await e();return this.#he=Math.max(this.#he,t),n}}function yi(e,t,n){return new Promise((r,i)=>{let o=setTimeout(()=>i(new Gn("Timeout",n)),t);e.then(e=>{clearTimeout(o),r(e)},e=>{clearTimeout(o),i(e)})})}import{randomUUID as bi}from"node:crypto";var wi=new Set(["click","moveMouse","drag","scroll","typeText","keyChord","holdKeys","holdMouse"]);function _i(e){return e instanceof Yn&&null!==e.data&&"code"in e.data&&"ControlRequired"===e.data.code}function ki(e,t){if(!0===t.signal?.aborted)throw new Gn("Cancelled",`${e} was cancelled`)}class xi{#fe;#me;constructor(e,t){this.#fe=e,this.#me=t}async fence(e){this.#fe.automaticLive&&!this.#me()&&await this.#ge(e)}async send(e,t,n,r){let i=!1;for(;;){ki(t,r);let o=this.#me();if(o||!this.#fe.automaticLive)if(!o||this.#fe.possiblyLive){try{return await e.rpc.request(t,n,r)}catch(e){if(!o||i||!_i(e)||!0===r.signal?.aborted)throw e}i=!0,await this.#ve(e,r)}else await this.#ve(e,r);else await this.#ge(e)}}#ge(e){return this.#fe.revoke(()=>e.rpc.request("control.revoke",{},{timeoutMs:2e3}))}async#ve(e,t){let n={reason:"full access: the session's permission preset consents to desktop input",confirmationId:bi()},r=t.signal;await this.#fe.grant(()=>e.rpc.request("control.grant",n,void 0===r?{}:{signal:r}),!1,!0)}}class Oi{#ye;#be=new gi;#we=Promise.resolve();#_e;#ke;#fe=new vi;#xe;#Oe=!1;constructor(e={}){this.#ye=e.createChild??Bn(),this.#xe=new xi(this.#fe,e.fullAccess??(()=>!1)),this.#be.onStopPathChange(e=>{e.suspended&&(this.#Oe=!0)})}onAudit(e){return this.#be.onAudit(e)}onStopPathChange(e){return this.#be.onStopPathChange(e)}onError(e){return this.#be.onError(e)}open(e){return this.#Se(async()=>{let t={...e,showCursor:e.showCursor??!0};this.#ke={params:t,chord:this.#ke?.chord};let n=this.#_e;return!0===n?.rpc.alive?this.#Ee(n,t):(void 0!==n&&this.#$e(n),(await this.#Pe(this.#ke)).capabilities)})}ensureStopPath(e){return this.#Se(async()=>{let t=await this.#Ie();if(t.armedChord===e)return this.#ae(t,"stopPath.status",{});let n=await this.#ae(t,"stopPath.start",{chord:e});return t.armedChord=e,void 0!==this.#ke&&(this.#ke.chord=e),n})}async call(e,t,n={}){let r=await this.#Te();await this.#xe.fence(r);let i=()=>r.rpc.request(e,t,n);return"control.grant"===e?this.#fe.grant(i,!0===n.signal?.aborted):"control.revoke"===e?this.#fe.revoke(i):function(e,t){if(!wi.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.#xe.send(r,e,t,n):i()}reportError(e){this.#be.emitError(e instanceof Error?e:Error(String(e)))}revokeControl(){let e=this.#_e;return void 0!==e&&e.rpc.alive&&this.#fe.possiblyLive?this.#fe.revoke(()=>e.rpc.request("control.revoke",{},{timeoutMs:2e3})).then(()=>{},e=>{if(!(e instanceof Gn||e instanceof Yn))throw e;this.#be.emitError(e)}):Promise.resolve()}async capabilities(){let e=await this.call("capabilities",{},{timeoutMs:1e4});if(!Ln(e))throw Ei("capabilities");return{...e,cursorOverlay:e.cursorOverlay??!1}}async stopPathStatus(){return this.#ae(await this.#Te(),"stopPath.status",{})}async stop(){return this.#ae(await this.#Te(),"stopPath.stop",{source:"host-relay"})}async resume(){let e=await this.#Te(),t=await this.#ae(e,"stopPath.resume",{token:e.resumeToken});return t.suspended||(this.#Oe=!1),t}close(){return this.#Se(async()=>{this.#ke=void 0;let e=this.#_e;if(void 0===e)return;if(this.#$e(e),!e.rpc.alive)return;try{await yi((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()}})}#Se(e){let t=this.#we.then(e);return this.#we=t.then(()=>{},()=>{}),t}#Te(){let e=this.#_e;return!0===e?.rpc.alive?Promise.resolve(e):this.#Se(()=>this.#Ie())}async#Ie(){let e=this.#_e;if(!0===e?.rpc.alive)return e;if(void 0!==e&&this.#$e(e),void 0===this.#ke)throw new Gn("Closed","desktop session is not open");return(await this.#Pe(this.#ke)).connection}async#Pe(e){let t=new Xn(await this.#ye(),{onNotification:(e,t)=>this.#be.dispatch(e,t),onExit:()=>{this.#_e?.rpc===t&&this.#$e(this.#_e)}}),n={rpc:t,resumeToken:"",features:[],armedChord:void 0,heartbeat:void 0};try{let t=await yi(this.#Ce(n,e),1e4,"Timed out starting desktop engine");return this.#_e=n,n.heartbeat=setInterval(()=>this.#ze(n),500),{connection:n,capabilities:t}}catch(e){throw t.kill(),e}}async#Ce(e,t){let n=Zn(await e.rpc.request("engine.hello",{}));if(void 0===n)throw Ei("engine.hello");if(n.abi!==Q||n.protocolVersion!==X)throw new oe(e.rpc.enginePath,{abi:n.abi,protocolVersion:n.protocolVersion});e.features=n.features;let r=await this.#Ee(e,t.params);return void 0!==t.chord&&(await this.#ae(e,"stopPath.start",{chord:t.chord}),e.armedChord=t.chord),this.#Oe&&await this.#ae(e,"stopPath.stop",{source:"host-relay"}),r}async#Ee(e,t){let n=function(e,t){let{reportMode:n,intervention:r,macosKeyPriming:i,trace:o,...s}=e,a=e=>t.includes(e);return{...s,...a("action-report")?{reportMode:n??Si.reportMode}:{},...a("intervention-policy")?{intervention:r??Si.intervention}:{},...a("key-priming")?{macosKeyPriming:i??Si.macosKeyPriming}:{},...a("trace")?{trace:o??Si.trace}:{}}}(t,e.features),r=function(e){if(Nn(e)&&"string"==typeof e.resumeToken&&Ln(e.capabilities))return{capabilities:{...e.capabilities,cursorOverlay:e.capabilities.cursorOverlay??!1},resumeToken:e.resumeToken}}(await e.rpc.request("session.open",n,{timeoutMs:1e4}));if(void 0===r)throw Ei("session.open");return e.resumeToken=r.resumeToken,r.capabilities}async#ae(e,t,n){let r=await e.rpc.request(t,n);if(!Un(r))throw Ei(t);return r.suspended&&(this.#Oe=!0),r}#ze(e){e.rpc.request("stopPath.heartbeat",{}).catch(e=>{if(!(e instanceof Gn&&"Closed"===e.code)){if(!(e instanceof Gn||e instanceof Yn))throw e;this.#be.emitError(e)}})}#$e(e){clearInterval(e.heartbeat),this.#_e===e&&(this.#_e=void 0)}}var Si={reportMode:"object",intervention:"pause",macosKeyPriming:"off",trace:!1};function Ei(e){return new Gn("Internal",`desktop engine sent a malformed ${e} result`)}var $i={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:N,executionMode:"sequential"},Pi={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",UserIntervened:"COMPUTER_USER_INTERVENED",AxUnconfirmed:"COMPUTER_AX_UNCONFIRMED",SpaceUnsupported:"COMPUTER_SPACE_UNSUPPORTED",SpaceMoveDenied:"COMPUTER_SPACE_MOVE_DENIED",AmbiguousTarget:"COMPUTER_AMBIGUOUS_TARGET",CaptureConsentRequired:"COMPUTER_CAPTURE_CONSENT_REQUIRED",ProtectedProcess:"COMPUTER_PROTECTED_PROCESS",StaleRef:"COMPUTER_STALE_REF",Cancelled:"COMPUTER_CANCELLED",Timeout:"COMPUTER_CANCELLED",timeout:"COMPUTER_CANCELLED",aborted:"COMPUTER_CANCELLED"};function Ii(e){return{code:"COMPUTER_LAUNCH_CONTEXT_REQUIRED",message:e.message,reason:e.reason}}function Ti(e,t,n,r,i){let o=e.startsWith("COMPUTER_")?e:Pi[e]??"COMPUTER_ERROR",s=function(e,t){switch(`${e}/${t??""}`){case"COMPUTER_DISPLAY_STALE/consumed":return"That frame was already used for input; capture a fresh screenshot before acting again.";case"COMPUTER_DISPLAY_STALE/wrong_target":return"The coordinates belong to another target's screenshot; capture the target you act on.";case"COMPUTER_DISPLAY_STALE/out_of_bounds":return"The point lies outside the screenshot; use coordinates within its frame.";case"COMPUTER_BACKGROUND_UNAVAILABLE/user_active_in_target":return"The user is typing in this app; wait until they pause, read the window again, then decide.";case"COMPUTER_CONTROL_REQUIRED/headless_host":return"This host cannot ask the human to confirm; target a window for background delivery instead.";case"COMPUTER_SUSPENDED/stop_marker":return"The user stopped computer use from outside this session; only the user resumes, with /computer resume.";default:return}}(o,i)??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.";case"COMPUTER_USER_INTERVENED":return"The user is working in this window. Read the window again after the user pauses and decide from what it shows now; never repeat the action as it was.";case"COMPUTER_AX_UNCONFIRMED":return"The app did not confirm the accessibility request, so it may already have taken effect. Read the element or window back before any retry.";case"COMPUTER_SPACE_UNSUPPORTED":return"Moving windows between Spaces is not available here; ask the user to bring the window to the current Space.";case"COMPUTER_SPACE_MOVE_DENIED":return"The window could not be moved to the current Space; ask the user to bring it over, then read the window again.";case"COMPUTER_AMBIGUOUS_TARGET":return"Several windows or elements match; list them again and target one by its id or ref.";case"COMPUTER_CAPTURE_CONSENT_REQUIRED":return"The system needs the user to approve screen capture; ask the user to approve it, then capture again.";case"COMPUTER_PROTECTED_PROCESS":return"This app is protected from automation; do not retry it, and ask the user to act in it.";default:return}}(o,n);return{code:o,message:`${o}: ${t}${void 0===s?"":` ${s}`}`,...r??{}}}import{Type as Ci}from"typebox";var zi=Ci.Object({method:Ci.String({description:"desktop helper name, e.g. screenshot, window, click, clipboard.read"}),args:Ci.Optional(Ci.Array(Ci.Unknown(),{description:"positional helper arguments"}))},{additionalProperties:!1}),Ri=Ci.Number({minimum:1,maximum:600,description:"run: budget in seconds (default 60)"}),Ai=[Ci.Object({action:Ci.Literal("call"),chain:Ci.Array(zi,{description:"one desktop helper call, optionally followed by one call on the window/element it returns"})},{additionalProperties:!1}),Ci.Object({action:Ci.Literal("run"),code:Ci.String({description:"JavaScript async function body; `desktop`, `wait`, `assert`, `tool` in scope; `return` sets the value"}),read_only:Ci.Optional(Ci.Boolean({description:"true = inspection only: screenshots and AX reads, input/mutation blocked"})),timeout:Ci.Optional(Ri)},{additionalProperties:!1}),Ci.Object({action:Ci.Literal("capabilities")},{additionalProperties:!1}),Ci.Object({action:Ci.Literal("close")},{additionalProperties:!1})],Ni=Ci.Union([...Ai]),ji=Ci.Object({action:Ci.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:Ci.Optional(Ci.Array(zi,{description:"call (required): one desktop helper call, optionally followed by one call on the window/element it returns"})),code:Ci.Optional(Ci.String({description:"run (required): JavaScript async function body; `desktop`, `wait`, `assert`, `tool` in scope; `return` sets the value"})),read_only:Ci.Optional(Ci.Boolean({description:"run: true = inspection only: screenshots and AX reads, input/mutation blocked"})),timeout:Ci.Optional(Ri)},{additionalProperties:!1});import{Check as Mi}from"typebox/value";import{readFileSync as Ui}from"node:fs";import{dirname as Li,join as Di}from"node:path";import{fileURLToPath as Zi}from"node:url";var Fi,Ji=["COMPUTER_PRELUDE_JAVASCRIPT","COMPUTER_PRELUDE_PYTHON","COMPUTER_DECLARATIONS","COMPUTER_DOCUMENTATION","COMPUTER_SAFETY"],qi=Di(Li(Zi(import.meta.url)),"assets.generated.json");function Wi(){if(void 0===Fi){let e=JSON.parse(Ui(qi,"utf8"));Fi=function(e){let t=e&&"object"==typeof e?e:void 0,n=Ji.filter(e=>"string"!=typeof t?.[e]);if(n.length>0)throw Error(`senpi-desktop-prelude asset JSON is malformed at ${qi}: missing ${n.join(", ")}`);return e}(e)}return Fi}var Vi={get javascript(){return Wi().COMPUTER_PRELUDE_JAVASCRIPT},get python(){return Wi().COMPUTER_PRELUDE_PYTHON},get declarations(){return Wi().COMPUTER_DECLARATIONS},get documentation(){return Wi().COMPUTER_DOCUMENTATION},get safety(){return Wi().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","menu.items","menu.select","move","observe","parent","perform","press","raise","ref","screenshot","scroll","setValue","type","value","window","windows","zoom"]},Bi={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:Vi.safety.split("\n").filter(e=>e.startsWith("- ")).map(e=>e.slice(2)),kernelPrelude:Vi,parameters:ji,executionMode:"sequential"},Hi=_(Ai);function Ki(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 Gi(e){return"string"==typeof e?e:JSON.stringify(e,null,2)??String(e)}function Yi(e,t){return{content:[{type:"text",text:void 0===e?t:Gi(e)}],details:{value:e}}}var Xi=new Set(["click","moveMouse","drag","scroll","typeText","keyChord","holdKeys","holdMouse","raiseWindow","menus.select","clipboard.write","ax.perform","ax.setValue","ax.focus","ax.click","ax.typeText"]),Qi={disposition:{delivery:"delivered_unverified",retry:"unsafe"},delivered:null,effect:"unverifiable",route:null,hit:null,focusRestoration:"not_confirmed",openedSurfaces:[],nextCall:null,note:null,warning:null,auditIds:[],timings:null,legacy:!0};function eo(e,t){return{call:async(n,r,i)=>{let o=await e.call(n,r,i);return Xi.has(n)&&t.push(function(e){if(null==e)return Qi;let t=e;return{disposition:t.disposition,delivered:t.delivered??null,effect:t.effect,route:t.route??null,hit:null==t.hit?null:{role:t.hit.role,label:t.hit.label??null},focusRestoration:t.focusRestoration,openedSurfaces:t.openedSurfaces??[],nextCall:t.nextCall??null,note:t.note??null,warning:t.warning??null,auditIds:t.auditIds,timings:null,legacy:!1}}("ax.typeText"===n?Reflect.get(Object(o),"report"):o)),o},onAudit:t=>e.onAudit(t),revokeControl:()=>e.revokeControl(),reportError:t=>e.reportError(t)}}async function to(e,t,n,r){let{handle:i,executeTool:o}=e;await i.activate(t);let s=i.settings(),a=function(e,t,n){let r=t.executionScope;return{cwd:t.cwd,sessionId:void 0===r?t.sessionManager.getSessionId():r.sessionId,captureMaxWidth:void 0===r?e.maxWidth:r.capture.maxWidth,captureMaxHeight:void 0===r?e.maxHeight:r.capture.maxHeight,captureMaxBytes:void 0===r?e.screenshotMaxBytes:r.capture.maxBytes,display:e.display,readOnly:n,stopHotkey:e.stopHotkey,allowHostRelayOnlyStop:e.allowHostRelayOnlyStop}}(s,t,n.readOnly),l=1e3*n.timeoutSeconds,u=e.confirmControl,c=[],d=await async function(e,t){return"quickjs"===e.sandbox&&"host"!==e.origin?{...await ai(e,t),sandbox:"quickjs"}:{...await pi(e,t),sandbox:"vm"}}({code:n.code,snapshot:a,timeoutMs:l,sandbox:s.runSandbox,origin:n.origin,...void 0===r?{}:{signal:r}},{service:eo(i.service,c),executeTool:o,...void 0===u?{}:{confirmControl:(e,n,r)=>u({context:t,reason:e,signal:n,budgetMs:r})}}),h=[...d.displays],p=new Set(h.flatMap(e=>"text"===e.type&&""!==e.text?[e.text]:[]));return void 0!==d.returnValue&&h.push({type:"text",text:Ki(d.returnValue,p)}),0===h.length&&h.push({type:"text",text:"Done."}),{content:h,details:{value:d.returnValue,readOnly:n.readOnly,screenshots:d.screenshots,audit:d.audit,sandbox:d.sandbox,...0===c.length?{}:{report:c[c.length-1]},...c.length>1?{reports:c}:{}}}}function no(e){let{handle:t}=e,n=(t,n,r)=>to(e,t,n,r);return{...Bi,async execute(e,r,i,o,s){let a=function(e){if(Mi(Ni,e))return e;throw k(Hi,e,"computer")}(r);switch(a.action){case"call":{let e=Y(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 io(n(s,{code:r,readOnly:e,timeoutSeconds:60,origin:"host"},i),t)}case"run":{let e=a.timeout??60;return io(n(s,{code:a.code,readOnly:!0===a.read_only,timeoutSeconds:e,origin:"model"},i),t)}case"capabilities":return io((async()=>(await t.activate(s),Yi(await t.service.capabilities(),"capabilities unavailable")))(),t);case"close":return await t.close(),Yi(void 0,"Closed the desktop session.");default:return function(e){throw TypeError(`unhandled computer action ${JSON.stringify(e)}`)}(a)}}}}var ro=new Set(["PermissionDenied","ControlRequired","InputBusy","Suspended","StaleRef"]);async function io(e,t){try{return await e}catch(e){if(e instanceof Z){let t=Ii(e);return{content:[{type:"text",text:e.message}],details:{value:t,isError:!0},isError:!0}}if(!(e instanceof Yn&&null!==e.data&&"code"in e.data&&ro.has(e.data.code)))throw e;let n=Ti(e.data.code,e.message,t.settings().stopHotkey,e.data.permission,e.data.reason);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{value:n,isError:!0},isError:!0}}}function oo(e){let t=null;return{...$i,async execute(n,r,i,o,s){let a,l=e.handle.settings().stopHotkey;try{a=function(e){if(O(z,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=>!O(T,e));if(e>=0)throw k(j,t[e],`computer_actions actions[${e}]`)}throw k(M,e,"computer_actions")}(r)}catch(e){if(!(e instanceof w))throw e;let t=Ti(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&&U.has(String(Reflect.get(e,"action"))))}(a),h=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, reason: error?.data?.reason });\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 to(e,s,{code:h,readOnly:d,timeoutSeconds:c,origin:"host"},i)}catch(e){if(!(e instanceof Error))throw e;if(e instanceof Z){let t=Ii(e);return{content:[{type:"text",text:t.message}],details:{value:t,isError:!0},isError:!0}}let t=e instanceof Yn&&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=Ti(String(n),e.message,l,t?.permission,t?.reason);return{content:[{type:"text",text:r.message}],details:{value:r,isError:!0},isError:!0}}let p=u.details.value;if("object"!=typeof(f=p)||null===f||!Array.isArray(Reflect.get(f,"steps")))return u;var f;t=p.bounds;let m=u.content.filter(e=>"image"===e.type),g=null===p.failedIndex?void 0:p.steps[p.failedIndex];if(void 0===g){let e=`${p.steps.length} action(s) done: ${p.steps.map(e=>e.action).join(", ")}.`;return{...u,content:[...m,{type:"text",text:e}]}}let v=Ti(g.code??"Error",g.message??"action failed",l,g.permission,g.reason),y=`Action ${g.index+1} (${g.action}) failed. ${void 0===v.permission?v.message:JSON.stringify(v)}`;return{content:[...m,{type:"text",text:y}],details:{...u.details,value:{...p,failure:v},isError:!0},isError:!0}}}}import{Type as so}from"typebox";import{Check as ao,Errors as lo}from"typebox/value";so.Object({enabled:so.Optional(so.Boolean({description:"Register the computer tool (experimental; default: host supported)"})),showCursor:so.Optional(so.Boolean({default:!0,description:"Show the display-only virtual cursor on macOS"})),display:so.Optional(so.String({description:"`active` (default) follows the focused monitor; `all` composites every display; otherwise a display id"})),maxWidth:so.Optional(so.Integer({minimum:1,default:3840})),maxHeight:so.Optional(so.Integer({minimum:1,default:2400})),screenshotMaxBytes:so.Optional(so.Integer({minimum:1,default:5e6})),stopHotkey:so.Optional(so.String({minLength:1,description:"Stop chord, e.g. ctrl+alt+shift+escape"})),allowHostRelayOnlyStop:so.Optional(so.Boolean({default:!1})),macosCanary:so.Optional(so.Union([so.Literal("session"),so.Literal("off")],{default:"session"})),auditLog:so.Optional(so.Object({enabled:so.Optional(so.Boolean({default:!0}))},{additionalProperties:!1})),screenshotGc:so.Optional(so.Object({enabled:so.Optional(so.Boolean({default:!0})),staleMs:so.Optional(so.Integer({minimum:0,default:432e5})),scanIntervalMs:so.Optional(so.Integer({minimum:0,default:18e5}))},{additionalProperties:!1})),enginePath:so.Optional(so.String({minLength:1,description:"Override the located engine binary"})),cuaAdapter:so.Optional(so.Boolean({default:!1,description:"Also register computer_actions (OpenAI computer-use actions)"})),runSandbox:so.Optional(so.Union([so.Literal("vm"),so.Literal("quickjs")],{default:"vm",description:"Where `run` code executes; reserved: every run uses `vm` until the QuickJS cell lands"})),intervention:so.Optional(so.Union([so.Literal("continue"),so.Literal("pause")],{default:"continue",description:"What a background action does while the user uses the target app; sent only to engines that support it"})),macosKeyPriming:so.Optional(so.Union([so.Literal("on"),so.Literal("off")],{default:"off",description:"macOS background keys first make the target window key; sent only to engines that support it"})),trace:so.Optional(so.Boolean({default:!1,description:"Per-request timing traces; sent only to engines that support it"}))},{additionalProperties:!1});var uo=(e,t)=>{let n=setTimeout(e,t);return()=>clearTimeout(n)};import{readFileSync as co}from"node:fs";import{dirname as ho,join as po}from"node:path";import{accessSync as fo,constants as mo,existsSync as go}from"node:fs";import{homedir as vo}from"node:os";import{join as yo}from"node:path";function bo(e,t,n,r=e=>Ce(e,n)){let i={host:t,attemptedPaths:[e]};if(!go(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:wo(i,t,`${e}: not executable (expected a .exe file)`);try{return void fo(e,mo.X_OK)}catch(n){if(!(n instanceof Error&&"code"in n))throw n;return wo(i,t,`${e}: not executable (chmod +x)`)}}function wo(e,t,n){return{...e,code:"native-unavailable",message:`No senpi-desktop-engine binary is available for ${t}.`,cause:n}}function _o(e,t,n,r={}){let i=r.platform??process.platform,o=Se(i,r.arch,r.libc);if(void 0!==e){let t=bo(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=Ie(s);if(null!==a.path){let e=Pe(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=Ye({host:o,version:n,cacheDir:yo(t.HOME??vo(),".omo","cache","senpi-desktop-engine")});if(null!==e.path)return{path:e.path,source:"cache"}}return null===be(o)?{diagnostic:a.diagnostic}:{notInstalled:a.diagnostic}}function ko(e,t){let n;try{n=JSON.parse(co(po(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 xo(e){let t=e.OMO_PACKAGE_DIR?.trim();if(t){let e=ko(t,["omo"]);if(void 0!==e)return e}let n=e.OMO_BIN?.trim();return n?ko(ho(ho(n)),["omo-ai"]):void 0}function Oo(e=process.env,t){return n=>{if(void 0!==n)return function(e){let t=Se(),n=bo(e,t,process.platform);return void 0!==n?()=>{throw new Vn(n)}:Bn(e)}(n);let r=xo(e);return void 0!==r?function(e){let t=e.acquire??Xe,n=e.spawnEngine??Hn;return async()=>{let r=await Qe({version:e.version,host:e.host??Se()},n,t);if(null===r.path)throw new Vn(r.diagnostic);return r.value}}({version:r}):void 0===t?Bn():()=>{let e=Ie(t);if(null===e.path)throw new Vn(e.diagnostic);return Bn(e.path)()}}}function So(e,t,n={}){let r=xo(t),i=_o(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=be(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}`}var Eo={"native-unavailable":"Computer use is unavailable: no usable desktop engine was found for this host.",quarantined:"Computer use is unavailable: macOS Gatekeeper has quarantined the desktop engine.","abi-mismatch":"Computer use is unavailable: the installed desktop engine does not match this omo release.","launch-context-unavailable":"Computer use cannot start safely from this host's current macOS launch context."};class $o extends Error{diagnostic;userFacing;constructor(e,t){super(`Desktop engine unavailable (${e}): ${t.message}`,{cause:t}),this.name="ComputerEngineUnavailableError",this.diagnostic=e,this.userFacing={code:"COMPUTER_ENGINE_UNAVAILABLE",message:Eo[e],action:"Run /computer status to see the engine path and what is wrong with it."}}}function Po(e){return e instanceof Vn?e.diagnostic.code:e instanceof oe?"abi-mismatch":e instanceof Z?e.code:void 0}class Io extends Oi{#Re="not started";#Ae;#Ne;constructor(e={}){super(e),this.#Ae=e.onError,this.#Ne=e.onPermissionRequired,this.onError(e=>this.#je(e))}get engineState(){return this.#Re}async open(e){try{let t=await super.open(e);return this.#Re="ready",t}catch(e){if(!(e instanceof Error))throw e;if(this.#je(e),e instanceof Z)throw e;let t=Po(e);if(void 0===t)throw e;throw this.#Re=t,new $o(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.#Re&&"launch-context-unavailable"!==this.#Re||(this.#Re="ready"),t}catch(e){if(!(e instanceof Error))throw e;throw this.#je(e),e}}#je(e){let t=Po(e);void 0!==t&&(this.#Re=t),e instanceof Yn&&null!==e.data&&"code"in e.data&&"PermissionDenied"===e.data.code&&null!=e.data.permission&&this.#Ne?.(e.data.permission),this.#Ae?.(e)}}import{spawn as To}from"node:child_process";import{createInterface as Co}from"node:readline";function zo(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 Ro(e,t="|"){return e.map(e=>ts(e)).join(t)}function Ao(e,t){return"bigint"==typeof t?t.toString():t}class No{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 jo(e){return new No(e)}function Mo(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Uo(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Lo(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Do(e){return Lo(e._zod.def)??e._zod.def.shape}function Zo(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return Uo(this,t,e),e},enumerable:!0,configurable:!0})}function Fo(e,t,n){t in e?Uo(e,t,n):e[t]=n}function Jo(e,t,n,r){let i=Do(t);for(let o of n){let n=Object.getOwnPropertyDescriptor(i,o);n.enumerable&&(n.get?Zo(e,o,()=>{let e=t._zod.def.shape[o];return r?r(e,o):e}):Fo(e,o,r?r(n.value,o):n.value))}}function qo(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Wo(e){return JSON.stringify(e)}var Vo="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Bo(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Ho=jo(()=>{if(As.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Ko(e){if(!1===Bo(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!==Bo(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function Go(e){return Ko(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var Yo=new Set(["string","number","symbol"]);function Xo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Qo(e,t,n){let r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function es(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 ts(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}var ns={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]},rs={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function is(e,t){let n=Do(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 os(e,t){let n={};return Jo(n,e,Reflect.ownKeys(Do(e))),function(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?Zo(e,n,()=>t[n]):Fo(e,n,r.value))}}(n,t),n}function ss(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(is(t,n)):void 0,s={};return Jo(s,t,Reflect.ownKeys(Do(t)),e&&((t,n)=>o&&!o.has(n)?t:new e({type:"optional",innerType:t}))),Qo(t,qo(t._zod.def,{shape:s,checks:[]}))}function as(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 ls(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 us(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function cs(e){return"string"==typeof e?e:e?.message}function ds(e){let t=[];for(let n of e??[]){let e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let r=e.maximum??e.length??e.size;r>=0&&t.push([r,n])}return t}function hs(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function ps(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:cs(e.inst?._zod.def?.error?.(e))??cs(o?.(e))??cs(t?.error?.(e))??cs(n.customError?.(e))??cs(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 fs=/[\uD800-\uDBFF]/;function ms(e){let t=e.length;if(!fs.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 gs(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function vs(...e){let[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}function ys(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function bs(e,t,n){return ys(e,t,n,!1)}function ws(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return ys(this,n,r(this))},set(e){ys(this,n,e)}})}return t}function _s(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return null==this?n:ys(this,t,n.bind(this))},set(e){ys(this,t,e)}})}var ks,xs=!1,Os={configurable:!0,get(){xs=!0}};function Ss(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&ks!==e._zod?ks=void 0:(ks=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Os);let e=xs;xs=!1;try{let r=n(this);return xs?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),xs=xs||e,r}catch(n){throw delete this[t],xs=xs||e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function Es(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 $s;function Ps(e){let t=()=>e;return t["~constantCatch"]=!0,t}var Is={value:void 0,enumerable:!1},Ts="captureStackTrace"in Error?Error:null;function Cs(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{Is.value=new i(r);try{Object.defineProperty(n,"_zod",Is)}finally{Is.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}):_s(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=Ts;if(t){let n=t.stackTraceLimit;if("number"==typeof n){try{t.stackTraceLimit=0}catch{return Ts=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 zs extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Rs extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}($s=globalThis).__zod_globalConfig??($s.__zod_globalConfig={});var As=globalThis.__zod_globalConfig;function Ns(e){return e&&Object.assign(As,e),As}var js={get:function(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Ao,2)),e.message},set:function(e){this._zod.message=e},enumerable:!0,configurable:!0},Ms={value:void 0,enumerable:!1},Us=new WeakSet([Object.prototype,Error.prototype]),Ls=(e,t)=>{e.name="$ZodError",Ms.value=t,Object.defineProperty(e,"issues",Ms),Ms.value=void 0,Object.defineProperty(e,"message",js);let n=Object.getPrototypeOf(e);Us.has(n)||(Us.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})}}))},Ds=Cs("$ZodError",Ls);Cs("$ZodError",Ls,void 0,{Parent:Error});function Zs(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 Fs(e,t){return{callee:t?.callee??e,Err:t?.Err}}var Js=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 zs;if(a.issues.length){let n=new(o?.Err??e)(a.issues.map(e=>ps(e,s,Ns())));throw Vo(n,o?.callee??t),n}return a.value};return t},qs=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=>ps(e,s,Ns())));throw Vo(n,o?.callee??t),n}return a.value};return t},Ws=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 zs;return o.issues.length?Vs(e,o.issues,i):{success:!0,data:o.value}};function Vs(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>ps(e,n,Ns()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}var Bs=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?Vs(e,o.issues,i):{success:!0,data:o.value}},Hs=Symbol.for("zod.compile.invalid"),Ks=Symbol.for("zod.compile.fallback"),Gs=(e,t,n)=>{let r=e._zod.bag.validator;if(void 0!==r){if(r(t)!==Hs)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[Ks]=!0,r=o({value:t,issues:[]},i)):r=e._zod.run({value:t,issues:[]},i);if(r instanceof Promise)throw new zs;return 0===r.issues.length}(e,t,n)};var Ys=/^[cC][0-9a-z]{6,}$/,Xs=/^[0-9a-z]+$/,Qs=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,ea=/^[0-9a-vA-V]{20}$/,ta=/^[A-Za-z0-9]{27}$/,na=/^[a-zA-Z0-9_-]{21}$/;var ra=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ia=/^([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})$/,oa=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)$/,sa=/^(?:[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 aa=/^(?:(?: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])$/,la=/^(([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}|:))$/,ua=/^((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])$/,ca=/^(([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])$/,da=/^https?$/,ha=/^\+[1-9]\d{6,14}$/,pa="(?:(?:\\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 fa=new RegExp(`^${pa}$`);function ma(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 ga=/^[\s\S]{0,}$/,va=/^-?\d+(?:\.\d+)?$/,ya=/^(?:true|false)$/i,ba=/^[^A-Z]*$/,wa=/^[^a-z]*$/,_a=Cs("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ka=e=>{let t=e.value;return!(n=t,null==n||void 0===t.length);var n},xa={number:"number",bigint:"bigint",object:"date"},Oa=Cs("$ZodCheckLessThan",(e,t)=>{_a.init(e,t);let n=xa[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:xa[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})}}),Sa=Cs("$ZodCheckGreaterThan",(e,t)=>{_a.init(e,t);let n=xa[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:xa[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})}}),Ea=Cs("$ZodCheckMultipleOf",(e,t)=>{_a.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})}}),$a=Cs("$ZodCheckNumberFormat",(e,t)=>{_a.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[i,o]=ns[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})}}),Pa=Cs("$ZodCheckMaxLength",(e,t)=>{var n;_a.init(e,t),(n=e._zod.def).when??(n.when=ka),e._zod.check=n=>{let r=n.value,i=r.length;if(("string"==typeof r&&i>t.maximum?ms(r):i)<=t.maximum)return;let o=gs(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ia=Cs("$ZodCheckMinLength",(e,t)=>{var n;_a.init(e,t),(n=e._zod.def).when??(n.when=ka),e._zod.check=n=>{let r=n.value,i=r.length;if(("string"==typeof r&&i>=t.minimum&&i<2*t.minimum?ms(r):i)>=t.minimum)return;let o=gs(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ta=Cs("$ZodCheckLengthEquals",(e,t)=>{var n;_a.init(e,t),(n=e._zod.def).when??(n.when=ka),e._zod.check=n=>{let r=n.value,i=r.length,o="string"==typeof r&&i>=t.length&&i<=2*t.length?ms(r):i;if(o===t.length)return;let s=gs(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})}}),Ca=Cs("$ZodCheckStringFormat",(e,t)=>{var n,r;_a.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=()=>{})}),za=Cs("$ZodCheckRegex",(e,t)=>{Ca.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})}}),Ra=Cs("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=ba),Ca.init(e,t)}),Aa=Cs("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=wa),Ca.init(e,t)}),Na=Cs("$ZodCheckIncludes",(e,t)=>{_a.init(e,t);let n=Xo(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})}}),ja=Cs("$ZodCheckStartsWith",(e,t)=>{_a.init(e,t);let n=new RegExp(`^${Xo(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})}}),Ma=Cs("$ZodCheckEndsWith",(e,t)=>{_a.init(e,t);let n=new RegExp(`.*${Xo(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})}}),Ua=Cs("$ZodCheckOverwrite",(e,t)=>{_a.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class La{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 Da={major:4,minor:6,patch:7},Za=Cs("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Da;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=as(t);for(let s of n){if(s._zod.def.when){if(ls(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 zs;if(i||a instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await a,t.issues.length!==n&&(hs(t.issues,n,e),o||(o=as(t,n)))});else{if(t.issues.length===n)continue;hs(t.issues,n,e),o||(o=as(t,n))}}return i?i.then(()=>t):t},n=(n,r,o)=>{if(as(n))return n.aborted=!0,n;let s=t(r,i,o);if(s instanceof Promise){if(!1===o.async)throw new zs;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 zs;return s.then(e=>t(e,i,o))}return t(s,i,o)}}},{get"~standard"(){return bs(this,"~standard",Ja(this))},set"~standard"(e){ys(this,"~standard",e)}}),Fa=(e,t)=>e.issues.length?{issues:e.issues.map(e=>ps(e,t,Ns()))}:{value:e.value};function Ja(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return Fa(r,n)}catch(e){}return async function(e,t){let n={async:!0};return Fa(await e._zod.run({value:t,issues:[]},n),n)}(e,t)},vendor:"zod",version:1}}var qa=Cs("$ZodString",(e,t)=>{Za.init(e,t),e._zod.pattern=t.pattern??ga,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}}),Wa=Cs("$ZodStringFormat",(e,t)=>{Ca.init(e,t),qa.init(e,t)}),Va=Cs("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ia),Wa.init(e,t)}),Ba=Cs("$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=oa(e))}else t.pattern??(t.pattern=oa());Wa.init(e,t)}),Ha=Cs("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=sa),Wa.init(e,t)});function Ka(e){try{return typeof URL<"u"&&"function"==typeof URL.canParse?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function Ga(e,t){return"normalize"in t||"hostname"in t||"protocol"in t?function(e,t){if(!t.normalize&&t.protocol?.source===da.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):Ka(e)||2}var Ya=/[\t\n\r]/g;function Xa(e){return e.replace(Ya,"")}var Qa=Cs("$ZodURL",(e,t)=>{Wa.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=Ga(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=Xa(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:Xa(r)))}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),el=Cs("$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")),Wa.init(e,t)}),tl=Cs("$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?na:(n=t.length,new RegExp(`^[a-zA-Z0-9_-]{${n}}$`))),Wa.init(e,t)}),nl=Cs("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Ys),Wa.init(e,t)}),rl=Cs("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Xs),Wa.init(e,t)}),il=Cs("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Qs),Wa.init(e,t)}),ol=Cs("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ea),Wa.init(e,t)}),sl=Cs("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ta),Wa.init(e,t)}),al=Cs("$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=`${ma({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${ma({precision:e.precision})}`:n;return new RegExp(`^${pa}T(?:${r})$`)}(t)),Wa.init(e,t)}),ll=Cs("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=fa),Wa.init(e,t)}),ul=Cs("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${ma(t)}$`)),Wa.init(e,t)}),cl=Cs("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ra),Wa.init(e,t)}),dl=Cs("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=aa),Wa.init(e,t)}),hl=/^[0-9a-fA-F:.]+$/;function pl(e){return!!hl.test(e)&&Ka(`http://[${e}]`)}var fl=Cs("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=la),Wa.init(e,t),e._zod.check=n=>{pl(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),ml=Cs("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ua),Wa.init(e,t)});var gl=Cs("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ca),Wa.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)&&pl(n)})(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function vl(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 yl=/^[0-9a-zA-Z+/]*={0,2}$/,bl=Cs("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=yl),Wa.init(e,t),e._zod.check=n=>{vl(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),wl=/^[A-Za-z0-9_-]*$/;var _l=Cs("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=wl),Wa.init(e,t),e._zod.check=n=>{(function(e){if(!wl.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return vl(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})}}),kl=Cs("$ZodE164",(e,t)=>{t.pattern??(t.pattern=ha),Wa.init(e,t)});var xl=Cs("$ZodJWT",(e,t)=>{Wa.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})}}),Ol=Cs("$ZodNumber",(e,t)=>{Za.init(e,t),e._zod.pattern=va,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}}),Sl=Cs("$ZodNumberFormat",(e,t)=>{$a.init(e,t),Ol.init(e,t)}),El=Cs("$ZodBoolean",(e,t)=>{Za.init(e,t),e._zod.pattern=ya,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}}),$l=Cs("$ZodUnknown",(e,t)=>{Za.init(e,t),e._zod.parse=e=>e}),Pl=Cs("$ZodNever",(e,t)=>{Za.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});var Il=e=>Array.isArray(e)?e.length:-1;function Tl(e,t,n){e.issues.length&&t.issues.push(...us(n,e.issues)),t.value[n]=e.value}var Cl=Cs("$ZodArray",(e,t)=>{Za.init(e,t);let n=As.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=>Tl(t,r,e)));else if(Tl(l,r,e),a&&0!==l.issues.length&&as(l))break}return s.length?Promise.all(s).then(()=>r):r},function(e,t){let n=ds(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(n,o)=>{let s=t(n.value);if(s>r&&!o?.skipChecks&&"backward"!==o?.direction)for(let[t,r]of ds(e._zod.def.checks))if(s>t&&r._zod.def.when(n)){let t=n.issues.length;return r._zod.check(n),n.issues[t].continue=!1,hs(n.issues,t,e),n}return i(n,o)}}(e,Il)});function zl(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(...us(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 Rl=[];function Al(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Rl,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 Nl(e,t,n,r,i,o,s){let a=[],l=i.keySet,u=i.catchall._zod,c=u.def.type,{optin:d,optout:h}=u,p=0;for(let i in t){if(s&&n.issues.length!==p){if(as(n,p))break;p=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=>zl(e,n,i,t,d,h))):zl(o,n,i,t,d,h)}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 jl=Cs("$ZodObject",(e,t)=>{Za.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=jo(()=>Al(t));Ss(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)||Uo(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=Bo,a=t.catchall,l=As.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,h=t.issues.length;for(let e of o.allKeys){if(d&&t.issues.length!==h){if(as(t,h))break;h=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=>zl(n,t,e,r,o,s))):zl(a,t,e,r,o,s)}return a?Nl(u,r,t,n,i.value,e,!0===d):u.length?Promise.all(u).then(()=>t):t}}),Ml=Cs("$ZodObjectJIT",(e,t)=>{jl.init(e,t);let n,r,i=e._zod.parse,o=jo(()=>Al(t)),s=As.memoizer,a=Bo,l=!As.jitless,u=l&&Ho.value,c=t.catchall;e._zod.parse=(d,h)=>{r??(r=o.value);let p=d.value;return a(p)?l&&u&&!1===h?.async&&!0!==h.jitless?(n||(n=(t=>{let n=o.value,r=n.symbolKeys,i=new La(["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)}]`:Wo(e),s=`${o} in input`,c=t[e],d=c?._zod?.optin,h=void 0!==d,p="optional"===c?._zod?.optout;if(i.write(`const ${n} = ${a(o)};`),h&&p){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 h?(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,h),c?Nl([],p,d,h,r,e,!0===h?.abortEarly):d):i(d,h):(d.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),d)}});function Ul(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=>!as(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=>ps(e,r,Ns())))}),t)}var Ll=Cs("$ZodUnion",(e,t)=>{Za.init(e,t),Ss(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),Ss(e,"optout",e=>e.def.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Ss(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)))}),Ss(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=>Mo(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=>Ul(t,r,e,i)):Ul(s,r,e,i)}}),Dl=Cs("$ZodIntersection",(e,t)=>{Za.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])=>Fl(e,t,n)):Fl(e,i,o)}});function Zl(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(Ko(e)&&Ko(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=Zl(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=Zl(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 Fl(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=Zl(t.value,n.value);if(!l.valid){if(as(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(l.mergeErrorPath)}`)}return e.value=l.data,e}var Jl=Cs("$ZodEnum",(e,t)=>{Za.init(e,t);let n=zo(t.entries),r=new Set(n);e._zod.values=r,Ss(e,"pattern",e=>{let t=zo(e.def.entries).filter(e=>Yo.has(typeof e));return new RegExp(t.length?`^(${t.map(e=>Xo(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}}),ql=Cs("$ZodLiteral",(e,t)=>{Za.init(e,t);let n=new Set(t.values);e._zod.values=n,Ss(e,"pattern",e=>{let t=e.def.values;return new RegExp(t.length?`^(${t.map(e=>"string"==typeof e?Xo(e):e?Xo(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}}),Wl=Cs("$ZodTransform",(e,t)=>{Za.init(e,t),e._zod.optin="optional",As.memoizer?.guard(e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new Rs(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 zs;return n.value=i,n}});function Vl(e,t){return e.value=t.issues.length?void 0:t.value,e}var Bl=Cs("$ZodOptional",(e,t)=>{Za.init(e,t),Ss(e,"optin",e=>"defaulted"===e.def.innerType._zod.optin?"defaulted":"optional"),e._zod.optout="optional",Ss(e,"values",e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),Ss(e,"pattern",e=>{let t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${Mo(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=>Vl(e,t)):Vl(e,r)}return t.innerType._zod.run(e,n)}}),Hl=Cs("$ZodExactOptional",(e,t)=>{Bl.init(e,t),Ss(e,"values",e=>e.def.innerType._zod.values),Ss(e,"pattern",e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Kl=Cs("$ZodNullable",(e,t)=>{Za.init(e,t),Ss(e,"optin",e=>e.def.innerType._zod.optin),Ss(e,"optout",e=>e.def.innerType._zod.optout),Ss(e,"pattern",e=>{let t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${Mo(t.source)}|null)$`):void 0}),Ss(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)}),Gl=Cs("$ZodDefault",(e,t)=>{Za.init(e,t),e._zod.optin="defaulted",Ss(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=>Yl(e,t)):Yl(r,t)}});function Yl(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var Xl=Cs("$ZodPrefault",(e,t)=>{Za.init(e,t),e._zod.optin="defaulted",Ss(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))}),Ql=Cs("$ZodNonOptional",(e,t)=>{Za.init(e,t),Ss(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=>eu(t,e)):eu(i,e)}});function eu(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 tu(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>ps(e,r,Ns()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var nu=Cs("$ZodCatch",(e,t)=>{Za.init(e,t),Ss(e,"optin",e=>"defaulted"===e.def.innerType._zod.optin?"defaulted":"optional"),Ss(e,"optout",e=>e.def.innerType._zod.optout),Ss(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=>tu(e,r,t,n)):tu(e,r,t,n)}}),ru=Cs("$ZodPipe",(e,t)=>{Za.init(e,t),Ss(e,"values",e=>e.def.in._zod.values),Ss(e,"optin",e=>e.def.in._zod.optin),Ss(e,"optout",e=>e.def.out._zod.optout),Ss(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=>iu(e,t.in,n)):iu(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>iu(e,t.out,n)):iu(r,t.out,n)}});function iu(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 ou=Cs("$ZodReadonly",(e,t)=>{Za.init(e,t),Ss(e,"propValues",e=>e.def.innerType._zod.propValues),Ss(e,"values",e=>e.def.innerType._zod.values),Ss(e,"optin",e=>e.def.innerType?._zod?.optin),Ss(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(su):su(r)}});function su(e){return e.memo||(e.value=Object.freeze(e.value)),e}var au=Cs("$ZodCustom",(e,t)=>{_a.init(e,t),Za.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=>lu(t,n,r,e));lu(i,n,r,e)}});function lu(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(vs(e))}}class uu extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}var cu="~memo",du=[];function hu(e){return null!==e&&"object"==typeof e}function pu(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var fu=new WeakMap;function mu(e,t,n){let r=fu.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=mu(e,t,n);r>i&&(i=r)}},s=e=>{e>i&&(i=e)},a=e._zod.def;switch(a.type){case"object":{let e=Lo(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?mu(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?mu(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&&fu.set(e,2===t);return t}(e,i)}var gu,vu=[],yu={alloc(e,t,n){let r=gu;if(!r)return n;gu=void 0;let i={value:n,issues:null};return r.set(t.value,i),vu.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[cu]?.backEdges;return void 0!==n&&hu(t)&&n.has(t)}(n,e.value))throw new uu;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=mu(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(!hu(u))return t(a,l);let c,d=l[cu];d||(d={buckets:new WeakMap,backEdges:void 0},l[cu]=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 h=c.get(u);if(h)return a.value=h.value,h.issues?h.issues.length&&a.issues.push(...pu(h.issues)):(a.memo=!0,d.backEdges??(d.backEdges=new WeakSet),d.backEdges.add(h.value)),a;gu=c;let p=vu.length,f=t(a,l);gu=void 0;let m=vu.length>p?vu.pop():void 0;return f instanceof Promise?f.then(e=>(m&&(m.issues=e.issues.length?pu(e.issues):du),e)):(m&&(m.issues=f.issues.length?pu(f.issues):du),f)};e._zod.parse=s,e._zod.run===t&&(e._zod.run=s)})}};var bu,wu=()=>{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 ${ts(e.values[0])}`:`Invalid option: expected one of ${Ro(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":""}: ${Ro(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 _u{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)}}(bu=globalThis).__zod_globalRegistry??(bu.__zod_globalRegistry=new _u);var ku=globalThis.__zod_globalRegistry;function xu(e){return e.checks&&(e.checks=[...e.checks]),e}function Ou(e,t){return new Oa({check:"less_than",...es(t),value:e,inclusive:!1})}function Su(e,t){return new Oa({check:"less_than",...es(t),value:e,inclusive:!0})}function Eu(e,t){return new Sa({check:"greater_than",...es(t),value:e,inclusive:!1})}function $u(e,t){return new Sa({check:"greater_than",...es(t),value:e,inclusive:!0})}function Pu(e,t){return new Ea({check:"multiple_of",...es(t),value:e})}function Iu(e,t){return new Pa({check:"max_length",...es(t),maximum:e})}function Tu(e,t){return new Ia({check:"min_length",...es(t),minimum:e})}function Cu(e,t){return new Ta({check:"length_equals",...es(t),length:e})}function zu(e){return new Ua({check:"overwrite",tx:e})}function Ru(e,t){let n=function(e,t){let n=new _a({check:"custom",...es(t)});return n._zod.check=e,n}(t=>(t.addIssue=e=>{if("string"==typeof e)t.issues.push(vs(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(vs(r))}},e(t.value,t)),t);return n}function Au(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Uo(e,t,n[t]);return e}function Nu(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??ku,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 ju(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 Mu(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),Mu(o,t,r),t.seen.get(o).isParent=!0)}let l=t.metadataRegistry.get(e);return l&&Au(s.schema,l),"input"===t.io&&Bu(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 Uu(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Lu(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}/${Uu(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+Uu(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 Du(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;Du(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 Zu=new Set(["type","properties","required","additionalProperties"]),Fu=["oneOf","anyOf"];function Ju(e){let t=e.additionalProperties;return void 0===t||!1===t||"object"!=typeof t||null===t?null:Object.keys(t).length?t:null}function qu(e){let t=[];for(let n of e){if("object"!=typeof n||"object"!==n.type)return null;for(let e in n)if(!Zu.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]??Ju(n);null!=t&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Uo(n,r,1===e.length?e[0]:qu(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=Ju(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 Wu(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of Zu)if(t in e)return;let n=t.filter(e=>Fu.some(t=>Array.isArray(e[t]))),r=null;if(n.length){let e=n[0],i=Fu.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=>qu([...o,e]));if(s.some(e=>!e))return;r={[i]:s}}else r=qu(t);r&&(delete e.allOf,Au(e,r))}function Vu(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?Au(i,a):(i.allOf=i.allOf??[],i.allOf.push(a)),Au(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())Du(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)??[])Wu(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)}Au(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,Uo(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:Hu(t,"input",e.processors),output:Hu(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw Error("Error converting schema to JSON.")}}function Bu(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 Bu(r.element,n);if("set"===r.type)return Bu(r.valueType,n);if("lazy"===r.type)return Bu(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 Bu(r.innerType,n);if("intersection"===r.type)return Bu(r.left,n)||Bu(r.right,n);if("record"===r.type||"map"===r.type)return Bu(r.keyType,n)||Bu(r.valueType,n);if("pipe"===r.type)return!!e._zod.traits.has("$ZodCodec")||(Bu(r.in,n)||Bu(r.out,n));if("object"===r.type){for(let e in r.shape)if(Bu(r.shape[e],n))return!0;return!1}if("union"===r.type){for(let e of r.options)if(Bu(e,n))return!0;return!1}if("tuple"===r.type){for(let e of r.items)if(Bu(e,n))return!0;return!(!r.rest||!Bu(r.rest,n))}return!1}var Hu=(e,t,n={})=>r=>{let{libraryOptions:i,target:o}=r??{},s=Nu({...i??{},target:o,io:t,processors:n});return Mu(e,s),Lu(s,e),Vu(s,e)},Ku=(e,t,n)=>{(void 0===e[t]||n>e[t])&&(e[t]=n)},Gu=(e,t,n)=>{(void 0===e[t]||n<e[t])&&(e[t]=n)},Yu=(e,t)=>{Ku(e,"minimum",t),Gu(e,"maximum",t)},Xu=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},Qu=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},ec=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},tc=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},nc=(e,t)=>Ku(e,"minimum",t.minimum),rc=(e,t)=>Gu(e,"maximum",t.maximum),ic=e=>(t,n)=>{tc(t,n.format);let[r,i]=e[n.format];Ku(t,"minimum",r),Gu(t,"maximum",i)},oc={greater_than:(e,t)=>Ku(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Gu(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Xu(e,t.value),number_format:ic(ns),bigint_format:ic(rs),min_length:nc,max_length:rc,length_equals:(e,t)=>Yu(e,t.length),min_size:nc,max_size:rc,size_equals:(e,t)=>Yu(e,t.size),string_format:(e,t)=>{tc(e,t.format),t.pattern&&Qu(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)=>ec(e,t.mime)};function sc(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let e of r)oc[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;void 0!==i.minimum&&Ku(t,"minimum",i.minimum),void 0!==i.exclusiveMinimum&&Ku(t,"exclusiveMinimum",i.exclusiveMinimum),void 0!==i.maximum&&Gu(t,"maximum",i.maximum),void 0!==i.exclusiveMaximum&&Gu(t,"exclusiveMaximum",i.exclusiveMaximum),void 0!==i.multipleOf&&Xu(t,i.multipleOf),void 0!==i.format&&(t.format??(t.format=i.format),i.format.includes("int")&&(t.isInt=!0)),i.mime&&ec(t,i.mime);for(let e of i.patterns??[])Qu(t,e);return t}var ac={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},lc=new Map([[yl,/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/],[wl,/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/]]),uc=e=>lc.get(e)??e;function cc(e){let t=e._zod.def;return"pipe"===t.type&&t.in._zod.traits.has("$ZodTransform")?cc(t.out):"catch"===t.type?cc(t.innerType):e._zod.optin}var dc=Symbol();function hc(e,t,n,r,i){let o=!1,s=JSON.stringify(e,(e,t)=>"bigint"!=typeof t?t:(o=!0,null));return o?(ju(t,n,r,i,"BigInt defaults cannot be represented in JSON Schema"),dc):JSON.parse(s)}var pc=(e,t,n,r)=>{let i=e._zod.def;Mu(i.innerType,t,r),t.seen.get(e).ref=i.innerType},fc=new WeakSet([Object.prototype,Error.prototype]);function mc(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 gc,vc=Cs("ZodError",(e,t)=>{Ds.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);fc.has(n)||(fc.add(n),mc(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)),mc(n,"flatten",e=>t=>function(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?Zs(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}(e,t)),mc(n,"addIssue",e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Ao,2)}),mc(n,"addIssues",e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Ao,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return 0===this.issues.length}}))},void 0,{Parent:Error}),yc=Js(vc),bc=qs(vc),wc=Ws(vc),_c=Bs(vc),kc=(e=>{let t=Js(e),n=(e,r,i,o)=>{let s=i?{...i,direction:"backward"}:{direction:"backward"};return t(e,r,s,Fs(n,o))};return n})(vc),xc=(e=>{let t=Js(e),n=(e,r,i,o)=>t(e,r,i,Fs(n,o));return n})(vc),Oc=(e=>{let t=qs(e),n=async(e,r,i,o)=>{let s=i?{...i,direction:"backward"}:{direction:"backward"};return await t(e,r,s,Fs(n,o))};return n})(vc),Sc=(e=>{let t=qs(e),n=async(e,r,i,o)=>await t(e,r,i,Fs(n,o));return n})(vc),Ec=(gc=vc,(e,t,n)=>{let r=n?{...n,direction:"backward"}:{direction:"backward"};return Ws(gc)(e,t,r)}),$c=(e=>(t,n,r)=>Ws(e)(t,n,r))(vc),Pc=(e=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return Bs(e)(t,n,i)})(vc),Ic=(e=>async(t,n,r)=>Bs(e)(t,n,r))(vc);function Tc(){As.localeError||Ns({localeError:wu()})}function Cc(){As.memoizer||Ns({memoizer:yu})}var zc=Cs("ZodType",(e,t)=>(Tc(),Za.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(qo(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 Qo(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,...es(n)})}(Ud,e,t)}(e,t))},superRefine(e,t){return this.check(function(e,t){return Ru(e,t)}(e,t))},overwrite(e){return this.check(zu(e))},optional(){return $d(this)},exactOptional(){return new Pd({type:"optional",innerType:this})},nullable(){return Td(this)},nullish(){return $d(Td(this))},nonoptional(e){return function(e,t){return new Rd({type:"nonoptional",innerType:e,...es(t)})}(this,e)},array(){return gd(this)},or(e){return wd([this,e])},and(e){return new _d({type:"intersection",left:this,right:e})},transform(e){return jd(this,new Sd({type:"transform",transform:e}))},default(e){return t=e,new Cd({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():Go(t)}});var t},prefault(e){return t=e,new zd({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():Go(t)}});var t},catch(e){return new Ad({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:Ps(t)});var t},pipe(e){return jd(this,e)},readonly(){return new Md({type:"readonly",innerType:this})},describe(e){let t=this.clone();return ku.add(t,{description:e}),t},meta(...e){if(0===e.length)return ku.get(this);let t=this.clone();return ku.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 bs(this,"~standard",{...Ja(this),jsonSchema:{input:Hu(this,"input"),output:Hu(this,"output")}})},set"~standard"(e){ys(this,"~standard",e)},parse:function e(t,n){return yc(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await bc(this,t,n,{callee:e})},safeParse(e,t){return wc(this,e,t)},async safeParseAsync(e,t){return _c(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){ys(this,"spa",e)},validate(e,t){return Gs(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 kc(this,t,n,{callee:e})},decode:function e(t,n){return xc(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Oc(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Sc(this,t,n,{callee:e})},safeEncode(e,t){return Ec(this,e,t)},safeDecode(e,t){return $c(this,e,t)},async safeEncodeAsync(e,t){return Pc(this,e,t)},async safeDecodeAsync(e,t){return Ic(this,e,t)},toJSONSchema(e){return((e,t={})=>n=>{let r=Nu({...n,processors:t});return Mu(e,r),Lu(r,e),Vu(r,e)})(this,{})(e)},get description(){return ku.get(this)?.description},get _def(){return this._zod.def}}),Rc=Cs("_ZodString",(e,t)=>{qa.init(e,t),zc.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}=sc(e);if("number"==typeof i&&(r.minLength=i),"number"==typeof o&&(r.maxLength=o),s&&(r.format=ac[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(uc);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)},ws({format:e=>sc(e).format??null,minLength:e=>sc(e).minimum??null,maxLength:e=>sc(e).maximum??null},{regex(...e){return this.check(function(e,t){return new za({check:"string_format",format:"regex",...es(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new Na({check:"string_format",format:"includes",...es(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new ja({check:"string_format",format:"starts_with",...es(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new Ma({check:"string_format",format:"ends_with",...es(t),suffix:e})}(...e))},min(...e){return this.check(Tu(...e))},max(...e){return this.check(Iu(...e))},length(...e){return this.check(Cu(...e))},nonempty(...e){return this.check(Tu(1,...e))},lowercase(e){return this.check(function(e){return new Ra({check:"string_format",format:"lowercase",...es(e)})}(e))},uppercase(e){return this.check(function(e){return new Aa({check:"string_format",format:"uppercase",...es(e)})}(e))},trim(){return this.check(zu(e=>e.trim()))},normalize(...e){return this.check(function(e){return zu(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(zu(e=>e.toLowerCase()))},toUpperCase(){return this.check(zu(e=>e.toUpperCase()))},slugify(){return this.check(zu(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}})),Ac=Cs("ZodString",(e,t)=>{qa.init(e,t),Rc.init(e,t)},{email(e){return this.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...es(t)})}(Zc,e))},url(e){return this.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...es(t)})}(qc,e))},jwt(e){return this.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...es(t)})}(od,e))},emoji(e){return this.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...es(t)})}(Wc,e))},guid(e){return this.check(function(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...es(t)})}(Fc,e))},uuid(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...es(t)})}(Jc,e))},uuidv4(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...es(t)})}(Jc,e))},uuidv6(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...es(t)})}(Jc,e))},uuidv7(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...es(t)})}(Jc,e))},nanoid(e){return this.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...es(t)})}(Vc,e))},cuid(e){return this.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...es(t)})}(Bc,e))},cuid2(e){return this.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...es(t)})}(Hc,e))},ulid(e){return this.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...es(t)})}(Kc,e))},base64(e){return this.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...es(t)})}(nd,e))},base64url(e){return this.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...es(t)})}(rd,e))},xid(e){return this.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...es(t)})}(Gc,e))},ksuid(e){return this.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...es(t)})}(Yc,e))},ipv4(e){return this.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...es(t)})}(Xc,e))},ipv6(e){return this.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...es(t)})}(Qc,e))},cidrv4(e){return this.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...es(t)})}(ed,e))},cidrv6(e){return this.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...es(t)})}(td,e))},e164(e){return this.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...es(t)})}(id,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,...es(t)})}(Mc,e))},date(e){return this.check(function(e,t){return new e({type:"string",format:"date",check:"string_format",...es(t)})}(Uc,e))},time(e){return this.check(function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...es(t)})}(Lc,e))},duration(e){return this.check(function(e,t){return new e({type:"string",format:"duration",check:"string_format",...es(t)})}(Dc,e))}});function Nc(e){return function(e,t){return new e(xu({type:"string",...es(t)}))}(Ac,e)}var jc=Cs("ZodStringFormat",(e,t)=>{Wa.init(e,t),Rc.init(e,t)}),Mc=Cs("ZodISODateTime",(e,t)=>{al.init(e,t),jc.init(e,t)}),Uc=Cs("ZodISODate",(e,t)=>{ll.init(e,t),jc.init(e,t)}),Lc=Cs("ZodISOTime",(e,t)=>{ul.init(e,t),jc.init(e,t)}),Dc=Cs("ZodISODuration",(e,t)=>{cl.init(e,t),jc.init(e,t)}),Zc=Cs("ZodEmail",(e,t)=>{Ha.init(e,t),jc.init(e,t)}),Fc=Cs("ZodGUID",(e,t)=>{Va.init(e,t),jc.init(e,t)}),Jc=Cs("ZodUUID",(e,t)=>{Ba.init(e,t),jc.init(e,t)}),qc=Cs("ZodURL",(e,t)=>{Qa.init(e,t),jc.init(e,t)}),Wc=Cs("ZodEmoji",(e,t)=>{el.init(e,t),jc.init(e,t)}),Vc=Cs("ZodNanoID",(e,t)=>{tl.init(e,t),jc.init(e,t)}),Bc=Cs("ZodCUID",(e,t)=>{nl.init(e,t),jc.init(e,t)}),Hc=Cs("ZodCUID2",(e,t)=>{rl.init(e,t),jc.init(e,t)}),Kc=Cs("ZodULID",(e,t)=>{il.init(e,t),jc.init(e,t)}),Gc=Cs("ZodXID",(e,t)=>{ol.init(e,t),jc.init(e,t)}),Yc=Cs("ZodKSUID",(e,t)=>{sl.init(e,t),jc.init(e,t)}),Xc=Cs("ZodIPv4",(e,t)=>{dl.init(e,t),jc.init(e,t)}),Qc=Cs("ZodIPv6",(e,t)=>{fl.init(e,t),jc.init(e,t)}),ed=Cs("ZodCIDRv4",(e,t)=>{ml.init(e,t),jc.init(e,t)}),td=Cs("ZodCIDRv6",(e,t)=>{gl.init(e,t),jc.init(e,t)}),nd=Cs("ZodBase64",(e,t)=>{bl.init(e,t),jc.init(e,t)}),rd=Cs("ZodBase64URL",(e,t)=>{_l.init(e,t),jc.init(e,t)}),id=Cs("ZodE164",(e,t)=>{kl.init(e,t),jc.init(e,t)}),od=Cs("ZodJWT",(e,t)=>{xl.init(e,t),jc.init(e,t)}),sd=Cs("ZodNumber",(e,t)=>{Ol.init(e,t),zc.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}=sc(e);i.type=c?"integer":"number";let d="number"==typeof u&&u>=(o??Number.NEGATIVE_INFINITY),h="number"==typeof l&&l<=(s??Number.POSITIVE_INFINITY),p="draft-04"===t.target||"openapi-3.0"===t.target;if(d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:"number"==typeof o&&(i.minimum=o),h?p?(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)):ju(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},ws({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=sc(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=sc(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:n}=sc(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>sc(e).format??null},{gt(e,t){return this.check(Eu(e,t))},gte(e,t){return this.check($u(e,t))},min(e,t){return this.check($u(e,t))},lt(e,t){return this.check(Ou(e,t))},lte(e,t){return this.check(Su(e,t))},max(e,t){return this.check(Su(e,t))},int(e){return this.check(ld(e))},safe(e){return this.check(ld(e))},positive(e){return this.check(Eu(0,e))},nonnegative(e){return this.check($u(0,e))},negative(e){return this.check(Ou(0,e))},nonpositive(e){return this.check(Su(0,e))},multipleOf(e,t){return this.check(Pu(e,t))},step(e,t){return this.check(Pu(e,t))},finite(){return this}}));var ad=Cs("ZodNumberFormat",(e,t)=>{Sl.init(e,t),sd.init(e,t)});function ld(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...es(t)})}(ad,e)}var ud=Cs("ZodBoolean",(e,t)=>{El.init(e,t),zc.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function cd(e){return function(e,t){return new e({type:"boolean",...es(t)})}(ud,e)}var dd=Cs("ZodUnknown",(e,t)=>{$l.init(e,t),zc.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function hd(){return new dd({type:"unknown"})}var pd=Cs("ZodNever",(e,t)=>{Pl.init(e,t),zc.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function fd(e){return function(e,t){return new e({type:"never",...es(t)})}(pd,e)}var md=Cs("ZodArray",(e,t)=>{Cc(),Cl.init(e,t),zc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=n,o=e._zod.def,{minimum:s,maximum:a}=sc(e);"number"==typeof s&&(i.minItems=s),"number"==typeof a&&(i.maxItems=a),i.type="array",i.items=Mu(o.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Tu(e,t))},nonempty(e){return this.check(Tu(1,e))},max(e,t){return this.check(Iu(e,t))},length(e,t){return this.check(Cu(e,t))},unwrap(){return this.element}});function gd(e,t){return function(e,t,n){return new e({type:"array",element:t,...es(n)})}(md,e,t)}var vd=Cs("ZodObject",(e,t)=>{Cc(),Ml.init(e,t),zc.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&&ju(e,t,i,r,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(let e in s)Uo(i.properties,e,Mu(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===cc(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=Mu(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(i.additionalProperties=!1)})(e,t,n,r),Es(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 kd({type:"enum",entries:n,...es(t)})}(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(qo(this._zod.def,{catchall:e}))},passthrough(){return this.clone(qo(this._zod.def,{catchall:hd()}))},loose(){return this.clone(qo(this._zod.def,{catchall:hd()}))},strict(){return this.clone(qo(this._zod.def,{catchall:fd()}))},strip(){return this.clone(qo(this._zod.def,{catchall:void 0}))},extend(e){return function(e,t){if(!Ko(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let n=Do(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 Qo(e,qo(e._zod.def,{shape:os(e,t)}))}(this,e)},safeExtend(e){return function(e,t){if(!Ko(t))throw Error("Invalid input to safeExtend: expected a plain object");return Qo(e,qo(e._zod.def,{shape:os(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 Jo(n,e,Reflect.ownKeys(Do(e))),Jo(n,t,Reflect.ownKeys(Do(t))),Qo(e,qo(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 Jo(i,e,is(e,t)),Qo(e,qo(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(is(e,t)),o={};return Jo(o,e,Reflect.ownKeys(Do(e)).filter(e=>!i.has(e))),Qo(e,qo(n,{shape:o,checks:[]}))}(this,e)},partial(...e){return ss(Ed,this,e[0])},exactPartial(...e){return ss(Pd,this,e[0],"exactPartial")},required(...e){return function(e,t,n){let r=n?new Set(is(t,n)):void 0,i={};return Jo(i,t,Reflect.ownKeys(Do(t)),(t,n)=>r&&!r.has(n)?t:new e({type:"nonoptional",innerType:t})),Qo(t,qo(t._zod.def,{shape:i}))}(Rd,this,e[0])}});function yd(e,t){let n={type:"object",shape:e??{},...es(t)};return new vd(n)}var bd=Cs("ZodUnion",(e,t)=>{Ll.init(e,t),zc.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)=>Mu(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 wd(e,t){return new bd({type:"union",options:e,...es(t)})}var _d=Cs("ZodIntersection",(e,t)=>{Dl.init(e,t),zc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def,o=Mu(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=Mu(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 kd=Cs("ZodEnum",(e,t)=>{Jl.init(e,t),zc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{let r=zo(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 kd({...t,checks:[],...es(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 kd({...t,checks:[],...es(r),entries:i})}});var xd=Cs("ZodLiteral",(e,t)=>{ql.init(e,t),zc.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(ju(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if("bigint"==typeof s){if(ju(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 Od(e,t){return new xd({type:"literal",values:Array.isArray(e)?e:[e],...es(t)})}var Sd=Cs("ZodTransform",(e,t)=>{Cc(),Wl.init(e,t),zc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{ju(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 Rs(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(vs(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(vs(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});var Ed=Cs("ZodOptional",(e,t)=>{Bl.init(e,t),zc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pc(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function $d(e){return new Ed({type:"optional",innerType:e})}var Pd=Cs("ZodExactOptional",(e,t)=>{Hl.init(e,t),zc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pc(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var Id=Cs("ZodNullable",(e,t)=>{Kl.init(e,t),zc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def,o=Mu(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 Td(e){return new Id({type:"nullable",innerType:e})}var Cd=Cs("ZodDefault",(e,t)=>{Gl.init(e,t),zc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;Mu(i.innerType,t,r),t.seen.get(e).ref=i.innerType;let o=hc(i.defaultValue,e,t,n,r);o!==dc&&(n.default=o)})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});var zd=Cs("ZodPrefault",(e,t)=>{Xl.init(e,t),zc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;if(Mu(i.innerType,t,r),t.seen.get(e).ref=i.innerType,"input"!==t.io)return;let o=hc(i.defaultValue,e,t,n,r);o!==dc&&(n._prefault=o)})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var Rd=Cs("ZodNonOptional",(e,t)=>{Ql.init(e,t),zc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;Mu(i.innerType,t,r),t.seen.get(e).ref=i.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var Ad=Cs("ZodCatch",(e,t)=>{nu.init(e,t),zc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i,o=e._zod.def;Mu(o.innerType,t,r),t.seen.get(e).ref=o.innerType;try{i=o.catchValue(void 0)}catch{return void ju(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 Nd=Cs("ZodPipe",(e,t)=>{ru.init(e,t),zc.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;Mu(s,t,r),t.seen.get(e).ref=s})(e,t,0,r),e.in=t.in,e.out=t.out});function jd(e,t){return new Nd({type:"pipe",in:e,out:t})}var Md=Cs("ZodReadonly",(e,t)=>{ou.init(e,t),zc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;Mu(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 Ud=Cs("ZodCustom",(e,t)=>{au.init(e,t),zc.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{ju(e,t,n,r,"Custom types cannot be represented in JSON Schema")})(e,t,n,r)});var Ld,Dd=yd({protocolVersion:Nc(),engineVersion:Nc(),buildSha:Nc(),abi:Nc()}),Zd=yd({backend:Nc(),displayServer:Nc().nullable().optional(),capture:cd(),input:cd(),ax:cd(),backgroundWindowInput:cd(),cursorOverlay:cd().default(!1),deliveryModes:gd(Nc()),capturePermission:Nc(),inputPermission:Nc(),axPermission:Nc(),displayCount:function(e,t){return new e(xu({type:"number",checks:[],...es(t)}))}(sd,Ld).int().nonnegative(),focusGuard:cd(),stopPath:Nc(),stopReason:Nc().nullable().optional(),integrityLevel:Nc().nullable().optional(),screenLocked:cd(),displayAsleep:cd().default(!1)}),Fd=yd({id:wd([Od(1),Od(2)]),result:hd().optional(),error:hd().optional()});var Jd=(e,t,n)=>To(e,[...t],{stdio:"pipe",windowsHide:!0,detached:!0,env:n});function qd(e,t,n,r=Jd){let i=r(e,["--stdio"],{...process.env,...t});return new Promise(t=>{let r,o=new Map,s="",a=new F,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=To("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=Co({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=Fd.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=Dd.safeParse(e);if(!r.success)return{ok:!1,code:"handshake-failed",message:`malformed engine.hello result at ${n}`};if(r.data.abi!==Q||r.data.protocolVersion!==X)return{ok:!1,code:"abi-mismatch",message:`desktop engine ABI mismatch at ${n}: expected abi ${Q} protocol ${X}, engine reported abi ${r.data.abi} protocol ${r.data.protocolVersion}`};let i=Zd.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 Wd(e,t,n={}){let r=_o(e,t,xo(t),n);if(!("path"in r))return"OS permissions: unknown until first use (no usable installed engine)";let i=await qd(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 Vd(e){let t=e.engineChild??Oo(),n=new Io({createChild:t(e.settings.enginePath),onError:t=>e.onEngineError(function(e){return e instanceof Vn?e.diagnostic.code:e instanceof oe?"abi-mismatch":e instanceof Yn?null!==e.data&&"code"in e.data?e.data.code:"other":e instanceof Gn?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??uo;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:no(i),computerActionsTool:oo(i),describeEngineSource:So,describeEnginePermissions:Wd}}export{Vd as createComputerUseRuntime};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
// omo:
|
|
1
|
+
// omo:OnNd2iuNTQQ6mK7Npd0LlcHNKiy-xO-4OV3NLK_Qc4E:qHD4fZafaB4yalXv2n106fJmoV6hsnrT8L1o_EFNETc
|
|
2
2
|
import{isAbsolute as t}from"node:path";function e(t,e,o){void 0===t.deferStartupWork?o():t.deferStartupWork(e,o)}import{readFile as o}from"node:fs/promises";function r(t){if("object"!=typeof t||null===t||Array.isArray(t))throw Error("invalid desktop toolkit response");return t}async function i(t,e,i,n){let a=AbortSignal.timeout(e),s=void 0===n?a:AbortSignal.any([a,n]),l=(await o(t.tokenFile,{encoding:"utf8",signal:s})).trim();if(0===l.length)throw Error("desktop toolkit credential unavailable");let d=new Headers({Authorization:`Bearer ${l}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),c=0;async function u(e,o,i=!1){let n=c++,a=await fetch(t.endpoint,{method:"POST",headers:d,redirect:"error",signal:s,body:JSON.stringify({jsonrpc:"2.0",...i?{}:{id:n},method:e,params:o})});if(!a.ok)throw await(a.body?.cancel()),Error("desktop toolkit HTTP request failed");if("initialize"===e){let t=a.headers.get("mcp-session-id");null!==t&&d.set("Mcp-Session-Id",t)}if(i)return await(a.body?.cancel()),{};let u=await async function(t,e){let o=t.headers.get("content-type")?.split(";")[0]?.trim();if("application/json"===o){let o=r(await t.json());if("2.0"!==o.jsonrpc||o.id!==e)throw Error("invalid desktop toolkit response id");return o}if("text/event-stream"!==o||null===t.body)throw Error("invalid desktop toolkit response type");let i=t.body.getReader(),n=new TextDecoder,a="",s=[];try{for(;;){let t=await i.read();if(t.done)throw Error("desktop toolkit stream ended without a response");for(a+=n.decode(t.value,{stream:!0});;){let t=a.search(/[\r\n]/);if(t<0||"\r"===a[t]&&t===a.length-1)break;let o=a.slice(0,t);if(a=a.slice(t+("\r\n"===a.slice(t,t+2)?2:1)),""===o){if(0===s.length)continue;let t=r(JSON.parse(s.join("\n")));if(s=[],"2.0"===t.jsonrpc&&t.id===e)return t}else("data"===o||o.startsWith("data:"))&&s.push(o.slice(5).replace(/^ /,""))}}}finally{await i.cancel(),i.releaseLock()}}(a,n);if("error"in u)throw Error("desktop toolkit RPC request failed");let p=r(u.result);if(JSON.stringify(p).includes(l))throw Error("desktop toolkit response contains a credential");return p}try{let t=await u("initialize",{protocolVersion:"2025-03-26",capabilities:{extensions:{"senpi/host-tools":{}}},clientInfo:{name:"omo-desktop-thread",version:"1"}});if("string"!=typeof t.protocolVersion)throw Error("missing desktop toolkit protocol version");return d.set("MCP-Protocol-Version",t.protocolVersion),await u("notifications/initialized",void 0,!0),await i(u)}finally{if(d.has("Mcp-Session-Id"))try{await((await fetch(t.endpoint,{method:"DELETE",headers:d,redirect:"error",signal:AbortSignal.timeout(2e3)})).body?.cancel())}catch{}}}function n(t){let e=r(t),{name:o,label:i,exposure:n,allowLazyActivation:a,searchKeywords:s}=r(e["senpi/host-tool"]);if("string"!=typeof o||!/^[a-zA-Z0-9_-]{1,64}$/.test(o)||"string"!=typeof i)throw Error("invalid host tool identity");if(void 0!==n&&"direct"!==n&&"search"!==n&&"eval"!==n&&"model-only"!==n&&"hidden"!==n)throw Error("invalid host tool exposure");if(void 0!==a&&"boolean"!=typeof a)throw Error("invalid host tool activation");if(!(void 0===s||Array.isArray(s)&&s.every(t=>"string"==typeof t)))throw Error("invalid host tool search keywords");return{name:o,label:i,...void 0===n?{}:{exposure:n},...void 0===a?{}:{allowLazyActivation:a},...void 0===s?{}:{searchKeywords:s}}}var a="senpi:host-tool-route";function s(){return Object.assign(Error("The host could not serve this call."),{name:"HostToolRouteUnavailable"})}async function l(t,e,o,n,a,l=!1){if(l&&a?.aborted)throw new DOMException("Desktop toolkit call aborted.","AbortError");if(void 0===t){if(l)throw s();return{isError:!0,content:[{type:"text",text:"Desktop thread toolkit is not granted to the calling session."}],details:{reason:"no_session_grant"}}}let d=AbortSignal.timeout(n),c=void 0===a?d:AbortSignal.any([d,a]);try{let a=await i(t,n,t=>t("tools/call",{name:e,arguments:o}),c);if(!Array.isArray(a.content)||void 0!==a.isError&&"boolean"!=typeof a.isError)throw Error("invalid desktop toolkit content");if(l){if(!0===a.isError)return{isError:!0,content:a.content,details:{}};let t=r(r(a._meta)["senpi/tool-result-details"]);return{content:a.content,details:t}}return{...a,details:{}}}catch{if(l&&c.aborted)throw new DOMException("Desktop toolkit call aborted.","AbortError");if(l)throw s();return{isError:!0,content:[{type:"text",text:"Desktop thread toolkit call failed."}],details:{reason:"call_failed"}}}}function d(t){if("object"!=typeof t||null===t||!("sessionManager"in t))return;let e=t.sessionManager;if("object"!=typeof e||null===e||!("getSessionId"in e)||"function"!=typeof e.getSessionId)return;let o=e.getSessionId();return"string"==typeof o&&o.length>0?o:void 0}var c=()=>import("@code-yeongyu/senpi");function u(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function p(t,e,o=c){t.rpc?.handle?.("omo.toolkit.executeHostTool",async(r,i)=>{let n=function(t){if(!u(t)||"show_html_page"!==t.name||!u(t.args))return;let{html:e,title:o,height:r}=t.args;return"string"!=typeof e||0===e.length||"string"!=typeof o||0===o.length||o.length>200||void 0!==r&&!Number.isInteger(r)?void 0:{name:"show_html_page",args:"number"==typeof r?{html:e,title:o,height:r}:{html:e,title:o}}}(r);if(void 0===n||!e.has(n.name)||void 0===t.cwd||"function"!=typeof i?.admit)return{isError:!0,content:[{type:"text",text:"The host tool is not available to this session."}],details:{}};let a=t.cwd;try{let t=await o();if("object"!=typeof t||null===t||!("writeHtmlPage"in t)||"function"!=typeof t.writeHtmlPage)throw Error("The pinned SDK does not provide writeHtmlPage.");let e=t.writeHtmlPage;return await i.admit(()=>e(n.args,a))}catch(t){if(!(t instanceof Error))throw t;return{isError:!0,content:[{type:"text",text:t.message}],details:{}}}})}var f=[1,2,4],h=["thread","host"],g={type:"object",properties:{op:{type:"string",enum:["acquire"]},toolkit:{type:"string"}},required:["op","toolkit"],additionalProperties:!1};function m(t){return{content:[{type:"text",text:JSON.stringify(t)}],details:t}}function y(t){if("object"!=typeof t||null===t)return new Set;let e=t.omo_toolkits;return"string"!=typeof e?new Set:new Set(e.split(",").map(t=>t.trim()).filter(t=>t.length>0))}function v(t){t.failed=!0,t.failures+=1,t.turnsSinceFailure=0,t.running=void 0}function k(t){t.turnsSinceFailure+=1;let e=f[t.failures-1];return void 0!==e&&t.turnsSinceFailure>=e}function w(o={}){let s=o.timeoutMs??15e3;return{name:"desktop-toolkit",register(c,u){if("function"!=typeof c.registerTool)return;let f=new Map,w=new Map,b=new Map,_=new Set,S="object"==typeof c.sessionContext&&null!==c.sessionContext&&"host_tool_names"in c.sessionContext&&"string"==typeof c.sessionContext.host_tool_names?new Set(c.sessionContext.host_tool_names.split(",").map(t=>t.trim()).filter(Boolean)):new Set;p(c,S,o.loadSdk);let E=function(t,e){let o=new Map;function r(r){for(let[e,i]of o)i.sessionId===r&&(o.delete(e),t.events?.emit(a,{name:e}));e.grants.delete(`host:${r}`)}return{clear:r,set(i,n,s){let c=o.get(i);void 0!==c&&c.sessionId!==s&&r(c.sessionId);let u={sessionId:s};o.set(i,u),t.events?.emit(a,{name:i,async execute(t,a,s,c,p){let f=d(p),h=void 0===f?void 0:e.grants.get(`host:${f}`);try{return await l(h,n,a,e.timeoutMs,s,!0)}catch(t){throw t instanceof Error&&"HostToolRouteUnavailable"===t.name&&o.get(i)===u&&(r(u.sessionId),e.onLost(u.sessionId)),t}}})}}}(c,{grants:b,timeoutMs:s,onLost(t){let e=w.get(`host:${t}`);void 0!==e&&v(e)}});async function x(t,e){if(e?.aborted)return{ok:!1,reason:"cancelled"};if(void 0===c.rpc||!y(c.sessionContext).has(t))return{ok:!1,reason:"unavailable"};let o=crypto.randomUUID();return new Promise(r=>{let i=setTimeout(()=>a({ok:!1,reason:"timeout"}),s),n=()=>a({ok:!1,reason:"cancelled"}),a=t=>{clearTimeout(i),f.delete(o),e?.removeEventListener("abort",n),r(t)};f.set(o,a),e?.addEventListener("abort",n,{once:!0}),c.rpc?.emit("omo.toolkit.request",{requestId:o,toolkit:t})})}async function A(t,e){if(e.controller.signal.aborted||b.has(`${e.toolkit}:${t}`))return;if(void 0!==e.running)return e.running;e.startupPending=!1;let o=async function(t,e){let o=e.controller.signal;try{let a=await x(e.toolkit,o);if(o.aborted)return;if(!a.ok)return v(e),void u.logger.info("desktop thread toolkit unavailable",{reason:"timeout"===a.reason?"timeout":"grant_refused"});let p=await function(t,e,o,a){return i(t,e,async t=>{let e,o=[];do{let i=await t("tools/list",void 0===e?void 0:{cursor:e});if(!Array.isArray(i.tools))throw Error("invalid desktop toolkit tools");for(let t of i.tools){if("object"!=typeof t||null===t||Array.isArray(t)){a?.("invalid_descriptor");continue}let e,i=r(t);try{e="object"==typeof i._meta&&null!==i._meta&&"senpi/host-tool"in i._meta?n(i._meta):void 0}catch{a?.("invalid_descriptor");continue}if("string"!=typeof i.name||0===i.name.length||!/^[a-zA-Z0-9_-]{1,64}$/.test(void 0===e?`desktop_${i.name}`:i.name)){a?.("invalid_name");continue}if("object"!=typeof i.inputSchema||null===i.inputSchema||Array.isArray(i.inputSchema)||!("type"in i.inputSchema)||"object"!==i.inputSchema.type){a?.("invalid_schema");continue}if(void 0!==i.description&&"string"!=typeof i.description){a?.("invalid_descriptor");continue}let s=r(i.inputSchema);o.push({name:i.name,inputSchema:s,...void 0===i.description?{}:{description:i.description},...void 0===e?{}:{attachment:e}})}if(void 0!==i.nextCursor&&"string"!=typeof i.nextCursor)throw Error("invalid desktop toolkit cursor");e=i.nextCursor}while(void 0!==e);return o},o)}(a.grant,s,o,t=>u.logger.info("desktop thread toolkit skipped tool",{reason:t}));if(o.aborted)return;e.failed=!1,e.failures=0,b.set(`${e.toolkit}:${t}`,a.grant);for(let o of p){let r=o.attachment;if("host"===e.toolkit){if(void 0===r||!S.has(r.name))continue;E.set(r.name,o.name,t);continue}if(void 0!==r)continue;let i=`desktop_${o.name}`;if(_.has(i))continue;let n="getAllTools"in c&&"function"==typeof c.getAllTools?c.getAllTools():[];Array.isArray(n)&&n.some(t=>"object"==typeof t&&null!==t&&"name"in t&&t.name===i)||(c.registerTool({name:i,label:i,description:o.description??"",parameters:o.inputSchema,async execute(t,e,r,i,n){let a=d(n);return l(void 0===a?void 0:b.get(`thread:${a}`),o.name,e,s,r)}}),_.add(i))}}catch{if(o.aborted)return;v(e),u.logger.info("desktop thread toolkit unavailable",{reason:"discovery_failed"})}}(t,e).finally(()=>{e.running===o&&(e.running=void 0)});return e.running=o,o}c.registerTool({name:"omo_desktop_toolkit",label:"Desktop toolkit",description:"Internal channel for skills: ask the app for a toolkit it hosts for this thread, such as its in-app browser. Not for direct use.",parameters:g,exposure:"eval",permissionParser:()=>[],executionMode:"parallel",async execute(t,e){let o="string"==typeof e.toolkit?e.toolkit:"";return"acquire"!==e.op||""===o?m({ok:!1,reason:"invalid_request"}):m(await x(o))}}),c.rpc?.handle?.("omo.toolkit.grant",e=>{let o="object"==typeof e&&null!==e?e:{},r="string"==typeof o.requestId?f.get(o.requestId):void 0;if(void 0===r)return{accepted:!1};let i=function(e){if("object"!=typeof e||null===e)return;let{endpoint:o,tokenFile:r}=e;if("string"==typeof o&&"string"==typeof r&&t(r)){try{let t=new URL(o);if("http:"!==t.protocol||"127.0.0.1"!==t.hostname||""!==t.username||""!==t.password||""!==t.search)return}catch{return}return{endpoint:o,tokenFile:r}}}(o.grant);if(void 0!==i)return r({ok:!0,grant:i}),{accepted:!0};let n=o.refusal;return r({ok:!1,reason:"object"==typeof n&&null!==n&&"string"==typeof n.reason?String(n.reason):"invalid_grant"}),{accepted:!0}}),c.on("session_start",(t,o)=>{let r=y(c.sessionContext),i=h.filter(t=>r.has(t));if(void 0===c.rpc||0===i.length)return void u.logger.debug?.("desktop thread toolkit unavailable",{reason:"not_offered"});let n=d(o);if(void 0!==n)for(let t of i){let o=`${t}:${n}`;if(w.has(o))continue;let r={toolkit:t,controller:new AbortController,startupPending:!0,failed:!1,failures:0,turnsSinceFailure:0};w.set(o,r),e(u,"desktop thread toolkit",()=>r.startupPending?A(n,r):void 0)}else u.logger.info("desktop thread toolkit unavailable",{reason:"missing_session"})}),c.on("before_agent_start",(t,e)=>{if(function(t){return"object"==typeof t&&null!==t&&"preview"in t&&!0===t.preview}(t))return;let o=d(e);if(void 0===o)return;let r=[];for(let t of h){let e=w.get(`${t}:${o}`);void 0!==e&&(e.failed?void 0===e.running&&k(e)&&A(o,e):r.push(A(o,e)))}return Promise.all(r)},{previewSafe:!0}),c.on("session_shutdown",(t,e)=>{let o=d(e);if(void 0!==o){for(let t of h){let e=`${t}:${o}`;w.get(e)?.controller.abort(),w.delete(e),b.delete(e)}E.clear(o)}})}}}export{w as createDesktopToolkitRuntime};
|