omo-ai 5.1.63 → 5.1.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/bin/darwin/omo-keychain +0 -0
  2. package/bin/lib/engine-boot.js +27 -0
  3. package/bin/lib/launcher.js +23 -0
  4. package/bin/lib/memory-sync-boot.js +19 -0
  5. package/bin/lib/service-auth.generated.js +1 -1
  6. package/package.json +1 -1
  7. package/plugin/CHANGELOG.md +32 -0
  8. package/plugin/extensions/gateway-store-worker.mjs +2 -2
  9. package/plugin/extensions/memory-run-supervisor.mjs +1 -1
  10. package/plugin/extensions/omo-claim-receipt.js +1 -1
  11. package/plugin/extensions/omo-computer-use.js +1 -1
  12. package/plugin/extensions/omo-desktop-toolkit.js +1 -1
  13. package/plugin/extensions/omo-device-account.js +2 -2
  14. package/plugin/extensions/omo-device-service.js +2 -2
  15. package/plugin/extensions/omo-feedback.js +2 -2
  16. package/plugin/extensions/omo-init-deep-advisor.js +1 -1
  17. package/plugin/extensions/omo-member.js +1 -1
  18. package/plugin/extensions/omo-memory-commands.js +3 -3
  19. package/plugin/extensions/omo-memory-doctor.js +3 -3
  20. package/plugin/extensions/omo-memory-memfs.js +3 -3
  21. package/plugin/extensions/omo-memory-palace.js +3 -3
  22. package/plugin/extensions/omo-memory-sync.js +2 -2
  23. package/plugin/extensions/omo-onboarding-scan.js +3 -3
  24. package/plugin/extensions/omo-recall-store.js +1 -1
  25. package/plugin/extensions/omo-session-history.js +1 -1
  26. package/plugin/extensions/omo-side-panel.js +1 -1
  27. package/plugin/extensions/omo-task.js +1 -1
  28. package/plugin/extensions/omo-telemetry-otlp.js +1 -1
  29. package/plugin/extensions/omo-telemetry-posthog.js +1 -1
  30. package/plugin/extensions/omo-telemetry-recovery.js +1 -1
  31. package/plugin/extensions/omo-thread-client.js +1 -1
  32. package/plugin/extensions/omo.js +3 -3
  33. package/plugin/package.json +1 -1
  34. package/plugin/runtime/agent-toolkit-sdk/sdk.js +2 -2
  35. package/plugin/runtime/ast-grep-mcp/manifest.json +1 -1
  36. package/plugin/runtime/bunshin-ts/sdk.js +2 -2
  37. package/plugin/runtime/rollback-migrate.js +1 -1
  38. package/plugin/runtime/thread-sdk/sdk.js +2 -2
  39. package/plugin/skills/browser/runtime/omowright/manifest.json +1 -1
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // omo:dyJk5FHNrzuaOB9Hoit5nmtcWdZ7LgR-4Gd_xKJtmGg:eEVdeK0moAcAqQZUwW9osUeTT1aNFqIGHBr4Au-Maaw
2
+ // omo:KFqzGXfTo_mhyfTn7ffhGAxwSVw0xbivU3X8Ve2olUs:eEVdeK0moAcAqQZUwW9osUeTT1aNFqIGHBr4Au-Maaw
3
3
  var e=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(e){r=[e]}if(r)throw r[0];return t};function t(e){if(e instanceof Error&&"code"in e)return"string"==typeof e.code?e.code:void 0}async function r(e){for(let r=0;;r+=1)try{return await e()}catch(e){if("EINTR"!==t(e)||r>=128)throw e}}function n(e){for(let r=0;;r+=1)try{return e()}catch(e){if("EINTR"!==t(e)||r>=128)throw e}}var i,o,a=e=>new Promise(t=>setTimeout(t,e)),s=e(()=>{i=new Set(["EPERM","EBUSY","EACCES"]),o=[10,25,50,100,200,400]});import{Buffer as l}from"node:buffer";import{constants as c}from"node:fs";import*as u from"node:fs/promises";function d(e){return"number"==typeof e?0!==(e&c.O_EXCL):"string"==typeof e&&e.toLowerCase().includes("x")}async function f(e,t,n,i){let o="string"==typeof t?l.from(t,n??"utf8"):t,a=0;for(;a<o.length;){i?.throwIfAborted();let{bytesWritten:t}=await r(()=>e.write(o,a));if(t<=0)throw Error(`fs write made no progress at offset ${a}`);a+=t}}import{Buffer as m}from"node:buffer";import*as p from"node:fs";import*as w from"node:fs/promises";function h(e){return"function"==typeof e}function y(e){return(...t)=>r(async()=>e(...t))}function v(e){return(...t)=>n(()=>e(...t))}function g(e,t){let r="async"===t?y:v,n=new Map;return new Proxy(e,{get(e,t){if(n.has(t))return n.get(t);let i=Reflect.get(e,t);if(!h(i))return i;let o=r(i),a=Reflect.get(i,"native");return h(a)&&Object.assign(o,{native:r(a)}),n.set(t,o),o}})}function b(e,n,s){return async function(e,n,s){let l="win32"===s.platform?s.delaysMs??o:[],c=s.sleep??a;for(let o=0;;o+=1)try{return void await r(()=>void 0===s.admit?s.rename(e,n):s.admit(()=>s.rename(e,n)))}catch(e){let r=l[o],n=t(e);if(void 0===r||void 0===n||!i.has(n))throw e;await c(r)}}(e,n,{rename:(e,t)=>w.rename(e,t),platform:process.platform,...void 0===s?{}:{admit:s}})}function E(e){try{p.closeSync(e)}catch(e){if("EINTR"!==t(e))throw e}}function S(e){try{return n(()=>p.statSync(e)),!0}catch{return!1}}var _,k,x,O,I,$,N,A,M,T,P,R,D,C,L,z,j,F,U,q,Z,B,J,G,H,W,K,Y,V,X,Q,ee,te,re,ne,ie,oe,ae,se=async(...e)=>{let n=()=>w.open(...e);return function(e){return new Proxy(e,{get(e,n){let i=Reflect.get(e,n);if(!h(i))return i;let o=t=>Reflect.apply(i,e,[...t]);return"close"===n||n===Symbol.asyncDispose?(...e)=>{let r=o(e);return r instanceof Promise?r.catch(e=>{if("EINTR"!==t(e))throw e}):r}:"string"==typeof n&&_.has(n)?(...e)=>{let n=o(e);return n instanceof Promise?n.catch(n=>{if("EINTR"!==t(n))throw n;return r(async()=>o(e))}):n}:(...e)=>o(e)}})}(await(d(e[1]??"r")?n():r(n)))},le=async(e,n,i)=>{if("string"!=typeof n&&!(n instanceof Uint8Array))return w.writeFile(e,n,i);if("object"==typeof(o=e)&&!(o instanceof URL)&&!m.isBuffer(o)&&"fd"in o){let t="string"==typeof i?{encoding:i}:i??{};return t.signal?.throwIfAborted(),await f(e,n,t.encoding??void 0,t.signal),void(!0===t.flush&&await r(()=>e.sync()))}var o;return async function(e,n,i,o){let a="string"==typeof i?{encoding:i}:i??{};a.signal?.throwIfAborted();let s=a.flag??o,l=()=>u.open(e,s,a.mode),c=await(d(s)?l():r(l));try{await f(c,n,a.encoding??"utf8",a.signal),!0===a.flush&&await r(()=>c.sync())}finally{await c.close().catch(e=>{if("EINTR"!==t(e))throw e})}}(e,n,i??void 0,"w")},ce=(e,t,r)=>function(e,t,r,i){return d(r)?e(t,r,i):n(()=>e(t,r,i))}(p.openSync,e,t,r??void 0),ue=e(()=>{s(),_=new Set(["stat","sync","datasync","chmod","chown","utimes","truncate"]),k=g(w,"async"),x=g(p,"sync"),({access:O,chmod:I,copyFile:$,cp:N,link:A,lstat:M,mkdir:T,mkdtemp:P,readFile:R,readdir:D,readlink:C,realpath:L,rm:z,rmdir:j,stat:F,statfs:U,unlink:q}=k),({accessSync:Z,chmodSync:B,fsyncSync:J,linkSync:G,lstatSync:H,mkdirSync:W,readFileSync:K,readdirSync:Y,realpathSync:V,statSync:X,unlinkSync:Q,writeFileSync:ee,writeSync:te}=x),({constants:re,watch:ne}=p)});function de(e){return function(e){if(oe.test(e))try{let t=JSON.parse(e);return"string"==typeof t?t:void 0}catch{return}if(ae.test(e))return e.slice(1,-1).replace(/''/g,"'")}(e)??e}var fe,me,pe,we=e(()=>{ie=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,oe=/^"(?:[^"\\\u0000-\u001f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"$/,ae=/^'(?:[^']|'')*'$/});var he=e(()=>{fe={"а":"a","е":"e","о":"o","р":"p","с":"c","у":"y","х":"x","і":"i","ј":"j","ѕ":"s","ԁ":"d","ԛ":"q","ԝ":"w","ӏ":"l","А":"a","Е":"e","О":"o","Р":"p","С":"c","Х":"x","І":"i","Ј":"j","Ѕ":"s","К":"k","М":"m","Н":"h","Т":"t","В":"b","α":"a","ε":"e","ο":"o","ρ":"p","τ":"t","υ":"u","ν":"v","κ":"k","ι":"i","Ο":"o","Α":"a","Β":"b","Ε":"e","Η":"h","Ι":"i","Κ":"k","Μ":"m","Ν":"n","Ρ":"p","Τ":"t","Υ":"y","Χ":"x","ı":"i","İ":"i"},me=/[\p{Default_Ignorable_Code_Point}\p{Mn}]/gu,pe=new RegExp(`[${Object.keys(fe).join("")}]`,"gu")});function ye(e){let t=[];for(let r of e.split(/\r?\n/)){let e=r.indexOf(":");e<=0||t.push({key:r.slice(0,e).trim(),value:r.slice(e+1).trim(),line:r})}return t}function ve(e){let t=e.match(ie);return null===t?void 0:ye(t[1]??"")}function ge(e){let t=new Set,r=new Set;for(let{key:n}of ve(e)??[])(t.has(n)?r:t).add(n);return[...r]}function be(e){return(t=e,t.normalize("NFKC").replace(me,"").replace(pe,e=>fe[e]??e).toLowerCase()).replace(/^["']+|["']+$/g,"").trim();var t}var Ee=e(()=>{we(),he()}),Se=e(()=>{we()});function _e(e){let t=e.match(ie);if(!t)throw new xe($e);let r,n,i,o,a=t[1]??"",s=t[2]??"",l={};for(let{key:e,value:t,line:s}of ye(a))"description"===e?r=de(t):"read_only"===e?n=t:"kind"===e?i=de(t):"aliases"===e?o=ke(t,s):"limit"!==e&&Oe.test(e)&&(l[e]=t);if(!r||!r.trim())throw new xe(Ne);return{frontmatter:{description:r,...void 0!==n?{read_only:n}:{},...void 0!==i?{kind:i}:{},...void 0!==o?{aliases:o}:{},...Object.keys(l).length>0?{extra:l}:{}},body:s}}function ke(e,t){let r,n=e.trim();if(!n.startsWith("["))throw new xe(`frontmatter: 'aliases' must be a JSON array of non-empty strings (line: ${t})`);try{r=JSON.parse(n)}catch{throw new xe(`frontmatter: 'aliases' is not valid JSON (line: ${t})`)}if(!Array.isArray(r))throw new xe(`frontmatter: 'aliases' must be a JSON array, not ${typeof r} (line: ${t})`);for(let e of r)if("string"!=typeof e||""===e.trim())throw new xe(`frontmatter: 'aliases' array must contain only non-empty strings (line: ${t})`);return r}var xe,Oe,Ie,$e="frontmatter: target file is missing required frontmatter",Ne="frontmatter: target file frontmatter is missing 'description'",Ae=e(()=>{Ee(),we(),Se(),xe=class extends Error{name="FrontmatterError"},Oe=/^[A-Za-z0-9_-]+$/}),Me=e(()=>{Ie={ko:["응","네","예","좋아","그래","지워","지워줘","삭제해","삭제해줘","진행해"],en:["yes","ok","okay","do it","go ahead","delete it","yes delete it"]},new Set(Object.values(Ie).flat())});function Te(e){switch(e.source){case"user":return`user replied "${function(e){let t=e.replace(/\s+/g," ").trim();return t.length>Pe?`${t.slice(0,Pe)}...`:t}(e.userQuote)}" to proposal ${e.approves}; a record, not the user's approval`;case"agent":return!0===e.downgraded?"agent suggestion, not a user decision (claimed as the user's, but no matching user words)":"agent suggestion, not a user decision";case"inferred":return"inferred, not a user decision"}}var Pe=300,Re="A-Za-z\\uAC00-\\uD7A3",De=e(()=>{Me(),new RegExp(`^ *(?:[${Re}0-9 ]|(?<=[${Re}])'(?=[${Re}]))*[${Re}0-9][.!]? *$`,"u")}),Ce=e(()=>{De()});function Le(e,t,r,n){let i=void 0===e?void 0:function(e){return function(e){return!0===e?.startsWith(Ue)}(e)?void 0:e}(function(e){let t=e.extra?.[je];if(void 0===t)return;try{let e=JSON.parse(t);return"string"==typeof e?e:t}catch{return t}}(e.frontmatter)),o=void 0!==e&&e.body===r&&function(e,t){let r=e=>{let t=Object.entries(e.extra??{}).filter(([e])=>be(e)!==je);return JSON.stringify([e.description,e.read_only,e.kind,e.aliases,t.map(([e,t])=>[e,t]).sort()])};return r(e)===r(t)}(e.frontmatter,t),a=void 0===n?o?i:function(e){return ze(e)?Fe:e}(i):function(e,t){return void 0===e||ze(e)===ze(t)?t:Fe}(i,Te(n)),s=Object.fromEntries(Object.entries(t.extra??{}).filter(([e])=>be(e)!==je)),l=void 0===a?s:{...s,[je]:JSON.stringify(a)},{extra:c,...u}=t;return 0===Object.keys(l).length?u:{...u,extra:l}}function ze(e){return!0===e?.startsWith("user replied ")}var je="provenance",Fe="mixed: parts of this note are not the user's recorded words",Ue="user said ",qe=e(()=>{Ae(),Ee(),Ce()});import{homedir as Ze}from"node:os";import{join as Be,resolve as Je}from"node:path";function Ge(e,t){let r=e[He];return void 0===r||""===r.trim()?Be(Ze(),".omo","memory"):Je(t,r)}var He="OMO_MEMORY_HOME",We=e(()=>{ue()}),Ke=e(()=>{ue()}),Ye=e(()=>{ue(),We()}),Ve=e(()=>{We(),Ke(),Ye()}),Xe=e(()=>{Ve(),Ye()});import{constants as Qe}from"node:os";function et(){return nt??=async function(){let e,t=rt[process.platform];if(void 0===t)return null;try{e=await(import("bun:ffi"))}catch{return null}for(let r of t.names)try{let n=e.dlopen(r,{flock:{args:[e.FFIType.i32,e.FFIType.i32],returns:e.FFIType.i32},[t.errnoSymbol]:{args:[],returns:e.FFIType.ptr}}),i=n.symbols[t.errnoSymbol];if(void 0===i)continue;return(t,r)=>{let o=Number(n.symbols.flock(t,r));if(0===o)return{rc:o,errno:0};let a=i();return{rc:o,errno:null===a?-1:e.read.i32(a,0)}}}catch{continue}return null}(),nt}async function tt(){return null!==await et()}var rt,nt=null,it=e(()=>{rt={darwin:{names:["/usr/lib/libSystem.B.dylib"],errnoSymbol:"__error"},linux:{names:["libc.so.6","libc.musl-x86_64.so.1","libc.musl-aarch64.so.1","libc.so"],errnoSymbol:"__errno_location"}},Qe.errno}),ot=e(()=>{ue()}),at=e(()=>{Xe(),ue(),it(),ot()}),st=e(()=>{ue()}),lt=e(()=>{ue(),at(),st()}),ct=e(()=>{}),ut=e(()=>{ue(),ft()}),dt=e(()=>{ue(),ut(),ct()}),ft=e(()=>{ue(),ct(),dt(),ut()}),mt=e(()=>{ue()});function pt(){return yt??=async function(){if("darwin"!==process.platform)return null;try{let{dlopen:e,FFIType:t}=await(import("bun:ffi")),r=e("/usr/lib/libSystem.B.dylib",{proc_pidinfo:{args:[t.i32,t.i32,t.u64,t.ptr,t.i32],returns:t.i32}});return(e,t,n,i,o)=>Number(r.symbols.proc_pidinfo(e,t,n,i,o))}catch{return null}}(),yt}async function wt(e){if("win32"!==process.platform)return null;if(!Number.isSafeInteger(e)||e<=0)return null;gt??=async function(){if("win32"!==process.platform)return null;try{let{dlopen:e,FFIType:t}=await(import("bun:ffi"));return e("kernel32.dll",{OpenProcess:{args:[t.u32,t.i32,t.u32],returns:t.ptr},GetProcessTimes:{args:[t.ptr,t.ptr,t.ptr,t.ptr,t.ptr],returns:t.i32},CloseHandle:{args:[t.ptr],returns:t.i32}}).symbols}catch{return null}}();let t=await gt;if(null===t)return null;let r=t.OpenProcess(vt,0,e);if(null===r||0===r||0n===r)return null;try{let e=new BigUint64Array(1),n=t.GetProcessTimes(r,e,new BigUint64Array(1),new BigUint64Array(1),new BigUint64Array(1)),i=e[0]??0n;return 0===n||0n===i?null:i}finally{t.CloseHandle(r)}}var ht,yt=null,vt=4096,gt=null;import{execFile as bt}from"node:child_process";async function Et(e,t){return await new Promise(r=>{bt(e,t,{encoding:"utf8",timeout:2e3,windowsHide:!0},(e,t)=>{if(null!==e)return void r(null);let n=t.trim();r(n.length>0?n:null)})})}async function St(e){if("linux"===process.platform)return await async function(e){try{let t=await R(`/proc/${e}/stat`,"utf8"),r=t.lastIndexOf(")");if(r<0)return null;let n=t.slice(r+2).trim().split(/\s+/)[19];return void 0===n?null:`linux-proc-start-ticks:${n}`}catch{return null}}(e);if("darwin"===process.platform||"freebsd"===process.platform){if("dead"===kt(e))return null;let t=await async function(e){if("darwin"!==process.platform)return null;if(!Number.isSafeInteger(e)||e<=0)return null;let t=await pt();if(null===t)return null;let r=new Uint8Array(136),n=0;try{n=t(e,3,0n,r,136)}catch{return null}if(136!==n)return null;let i=new DataView(r.buffer,r.byteOffset,r.byteLength),o=Number(i.getBigUint64(120,!0));return o>0?o:null}(e);if(null!==t)return`proc-start-epoch:${t}`;let r=await Et("/bin/ps",["-o","lstart=","-p",String(e)]);return null===r?null:`ps-lstart:${r.replace(/\s+/g," ")}`}return"win32"===process.platform?await async function(e){if("dead"===kt(e))return null;let t=await wt(e);if(null!==t)return`win32-creation-filetime:${t}`;let r=await Et("powershell.exe",["-NoProfile","-Command",`(Get-Process -Id ${e} -ErrorAction SilentlyContinue).StartTime.ToUniversalTime().ToString('o')`]);return null===r?null:`win32-creation-date:${r}`}(e):null}function _t(e){let t=e.indexOf(":");return t<=0?null:e.slice(0,t)}function kt(e){try{return process.kill(e,0),"alive"}catch(e){let t=function(e){if(e instanceof Error&&"code"in e)return"string"==typeof e.code?e.code:void 0}(e);return"ESRCH"===t?"dead":"EPERM"===t?"alive":"unknown"}}var xt=e(()=>{ue(),ht=function(e,t){let r;return n=>n!==t?e(n):(r??=e(n).then(e=>(null===e&&(r=void 0),e),e=>{throw r=void 0,e}),r)}(St,process.pid)});import{randomUUID as Ot}from"node:crypto";import{hostname as It}from"node:os";function $t(e){return"string"==typeof e&&e.length>0}function Nt(e){let t;try{t=JSON.parse(e)}catch{return null}if("object"!=typeof t||null===t||Array.isArray(t))return null;let r=t;return!Number.isInteger(r.pid)||Number(r.pid)<=0?null:$t(r.process_start)&&$t(r.hostname)&&$t(r.nonce)?!$t(r.created_at)||Number.isNaN(Date.parse(r.created_at))?null:$t(r.purpose)&&(void 0===r.run_id||$t(r.run_id))?{pid:Number(r.pid),process_start:r.process_start,hostname:r.hostname,nonce:r.nonce,created_at:r.created_at,purpose:r.purpose,...void 0===r.run_id?{}:{run_id:r.run_id},...!0===r.git_activity_lock?{git_activity_lock:!0}:{}}:null:null}async function At(e,t={}){if(0===e.length)throw Error("lock purpose must not be empty");let r=await ht(process.pid);return{pid:process.pid,process_start:r??"unavailable",hostname:It(),nonce:Ot(),created_at:(new Date).toISOString(),purpose:e,...void 0===t.runId?{}:{run_id:t.runId},...await tt()?{git_activity_lock:!0}:{}}}var Mt,Tt=e(()=>{it(),xt()});function Pt(e,t,r){Mt.set(e,{previous:t,takeoverNonce:r})}function Rt(e,t){Mt.get(e)?.takeoverNonce===t&&Mt.delete(e)}var Dt=e(()=>{Mt=new Map});import Ct from"node:path";function Lt(e){if(e instanceof Error&&"code"in e)return"string"==typeof e.code?e.code:void 0}async function zt(e){try{let t=await R(e,"utf8"),r=await F(e,{bigint:!0});return{raw:t,record:Nt(t),dev:r.dev,ino:r.ino,mtimeMs:Number(r.mtimeMs)}}catch(e){let t=Lt(e);if("ENOENT"===t)return null;if("\\"===Ct.sep&&"EPERM"===t)return{raw:"",record:null,dev:0,ino:0,mtimeMs:Date.now()};throw e}}function jt(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.mtimeMs===t.mtimeMs&&e.raw===t.raw}async function Ft(e,t){Rt(e,t.nonce);let r=await zt(e);if(null===r||r.record?.nonce!==t.nonce)return!1;try{return await q(e),!0}catch(e){if("ENOENT"===Lt(e))return!1;throw e}}var Ut=e(()=>{ue(),Tt(),Dt()});import qt from"node:path";function Zt(e){Kt.add(e)}function Bt(e){Kt.delete(e)}function Jt(e){let t=Yt.exec(e)?.[1];return void 0!==t&&"dead"===kt(Number(t))}function Gt(e){if(e instanceof Error&&"code"in e)return"string"==typeof e.code?e.code:void 0}function Ht(e,t){try{e.onFailure?.(t)}catch{}}function Wt(e){if("win32"!==process.platform)return!1;let t=Gt(e);return"EBUSY"===t||"EPERM"===t||"EACCES"===t}var Kt,Yt,Vt,Xt=36e5,Qt=3,er=e(()=>{ue(),xt(),Kt=new Set,Yt=/\.candidate-(?:(\d+)-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i});function tr(e){Vt.delete(e)}var rr,nr,ir=e(()=>{Vt=new Map});import{randomUUID as or}from"node:crypto";import ar from"node:path";function sr(e){if(e instanceof Error&&"code"in e)return"string"==typeof e.code?e.code:void 0}function lr(e,t){if(void 0!==t)return t(e);if("win32"!==process.platform)return!1;let r=sr(e);return"EBUSY"===r||"EPERM"===r||"EACCES"===r}function cr(){return nr}async function ur(e){for(let t=0;t<Qt;t+=1)try{return await(nr.unlink??q)(e),Bt(e),!0}catch(r){if("ENOENT"===sr(r))return Bt(e),!0;if(!lr(r,nr.isSharingError))throw Zt(e),tr(ar.dirname(e)),r;if(t+1===Qt)return Zt(e),tr(ar.dirname(e)),!1}return!1}async function dr(e,t){await T(ar.dirname(e),{recursive:!0,mode:448});let{candidatePath:r,handle:n}=await async function(e){for(let t=0;;t+=1){let r=`${e}.candidate-${process.pid}-${or()}`;try{return{candidatePath:r,handle:await se(r,"wx",384)}}catch(n){if(await ur(r)||tr(ar.dirname(e)),"EINTR"!==sr(n)||t>=128)throw n}}}(e);try{try{await f(n,`${JSON.stringify(t)}\n`,"utf8"),await n.sync()}finally{await n.close()}try{return await(nr.link??A)(r,e),!0}catch(r){if(function(e){let t=sr(e);return"EEXIST"===t||"ENOENT"===t}(r))return!1;if(rr.has(sr(r)??""))return await async function(e,t){let r;try{r=await se(e,"wx",384)}catch(e){if("EEXIST"===sr(e))return!1;throw e}try{return await(nr.writeFallback??f)(r,`${JSON.stringify(t)}\n`,"utf8"),await r.sync(),!0}finally{await r.close()}}(e,t);throw r}}finally{await ur(r)||tr(ar.dirname(e))}}var fr=e(()=>{ue(),er(),ir(),rr=new Set(["EACCES","EPERM","ENOTSUP"]),nr={}});function mr(e,t,r=Math.random){let n=Math.min(250,t*2**Math.min(e,30));return Math.max(1,Math.round(n/2+r()*n/2))}function pr(e,t){return t?.throwIfAborted(),new Promise((r,n)=>{let i=setTimeout(a,e),o=()=>a(t?.reason??new DOMException("The operation was aborted","AbortError"));function a(e){clearTimeout(i),t?.removeEventListener("abort",o),void 0===e?r():n(e)}t?.addEventListener("abort",o,{once:!0})})}import{randomUUID as wr}from"node:crypto";import{hostname as hr}from"node:os";function yr(e){if(e instanceof Error&&"code"in e)return"string"==typeof e.code?e.code:void 0}async function vr(e){if(e.hostname!==hr())return!1;let t=kt(e.pid);if("dead"===t)return!0;if("unknown"===t)return!1;let r=await ht(e.pid);return null!==r&&"unavailable"!==e.process_start&&function(e,t){let r=_t(e);return null!==r&&r===_t(t)&&e!==t}(e.process_start,r)}async function gr(e,t,r){return null!==e.record?vr(e.record):t-e.mtimeMs>r}async function br(e,t,r){let n=await zt(e);if(null===n||!await gr(n,t,r))return!1;let i=`${e}.reaping-${wr()}`;try{await b(e,i)}catch(e){if("ENOENT"===yr(e))return!1;if(lr(e))return!1;throw e}let o=await zt(i);if(null!==o&&jt(o,n))return await q(i),!0;try{await A(i,e)}catch(e){if("EEXIST"!==yr(e))throw e}return await q(i),!1}async function Er(e,t,r,n,i){if(!await gr(t,n,i))return!1;let o=`${e}.recovery`,a={...r,nonce:wr(),created_at:(new Date).toISOString(),purpose:`${r.purpose}:recovery`};for(let e=0;null!==await zt(o)||!await dr(o,a);e+=1)if(e>0||!await br(o,n,i))return!1;try{let s=await zt(e);if(null===s)return!0;if(!jt(s,t))return!1;if(!await gr(s,n,i))return!1;let l=await zt(o);return null!==l&&l.record?.nonce===a.nonce&&(await q(e),null!==s.record&&Pt(e,s.record,r.nonce),!0)}finally{await Ft(o,a)}}var Sr=e(()=>{ue(),Ut(),xt(),Dt(),fr()});async function _r(e,t,r={}){let n=r.waitTimeoutMs??0,i=r.retryDelayMs??25,o=r.incompleteLockGraceMs??Or,a=r.now??Date.now;if(n<0||i<=0||o<0)throw Error("lock wait options must be positive");let s=a()+n;try{return await async function(e,t,r,n){let{retryDelayMs:i,incompleteLockGraceMs:o,now:a,deadline:s}=n,l=!1,c=!1;for(let n=0;;n+=1){r.signal?.throwIfAborted();let u=await zt(e);if(null===u){if(await dr(e,t))return{sawOtherOwner:l};if(r.signal?.throwIfAborted(),l=!0,c=kr(e,t,c),u=await zt(e),null===u)continue}if(l=!0,c=kr(e,t,c),await Er(e,u,t,a(),o))c=!0;else{if(r.signal?.throwIfAborted(),a()>=s)throw new xr(e,u.record);await pr(Math.min(mr(n,i),Math.max(1,s-a())),r.signal)}}}(e,t,r,{retryDelayMs:i,incompleteLockGraceMs:o,now:a,deadline:s})}catch(r){throw Rt(e,t.nonce),r}}function kr(e,t,r){return r&&Rt(e,t.nonce),!1}var xr,Or=5e3,Ir=e(()=>{Ut(),Dt(),fr(),Sr(),xr=class extends Error{lockPath;owner;retriable=!0;constructor(e,t){super(`Lock is held: ${e}`),this.lockPath=e,this.owner=t,this.name="LockContentionError"}}});import{hostname as $r}from"node:os";import Nr from"node:path";function Ar(e){if(e instanceof Error&&"code"in e)return"string"==typeof e.code?e.code:void 0}async function Mr(e,t){let r=!0===(await M(e).catch(()=>{}))?.isFile()?await async function(e){let t;try{t=await R(e,"utf8")}catch(e){if("ENOENT"===Ar(e))return null;throw e}let r=Nt(t);return null===r||r.hostname!==$r()||"dead"!==kt(r.pid)?null:await vr(r)?r:null}(e):null;if(null===r)return!1;let n=await At("dead-owner-sweep");try{await _r(e,n,{waitTimeoutMs:0})}catch(e){if(e instanceof xr)return!1;throw e}return await Ft(e,n),t.onReclaimed?.(e,r),!0}var Tr=".lock",Pr=e(()=>{ue(),Ir(),Ut(),Sr(),Tt(),xt()});import Rr from"node:path";async function Dr(e,t,r={}){let n,i=Rr.dirname(e);if(function(e,t){let r=Vt.get(e);return!(void 0!==r&&t-r<6e5||(Vt.set(e,t),0))}(i,(r.now??Date.now)())){let t=cr();await async function(e,t=Date.now,r={}){let n;try{n=await D(e)}catch(t){if("ENOENT"===Gt(t)){for(let t of Kt)qt.dirname(t)===e&&Bt(t);return 0}throw t}let i=0;for(let o of n){if(!Yt.test(o))continue;let n=qt.join(e,o);try{let e=await F(n);if(!(Kt.has(n)||Jt(o)||t()-e.mtimeMs>Xt))continue;let a=!1;for(let e=0;e<Qt;e+=1)try{await(r.unlink??q)(n),Bt(n),a=!0;break}catch(t){if("ENOENT"===Gt(t)){Bt(n),a=!0;break}if(!(r.isSharingError?.(t)??Wt(t)))throw t;e+1===Qt&&Ht(r,n)}a&&(i+=1)}catch(e){"ENOENT"===Gt(e)&&Bt(n),Ht(r,n)}}return i}(i,Date.now,{...void 0===t.unlink?{}:{unlink:t.unlink},...void 0===t.isSharingError?{}:{isSharingError:t.isSharingError},onFailure:()=>tr(i)}).catch(()=>{tr(i)}),await async function(e,t={}){let r;try{r=await D(e)}catch(r){return"ENOENT"!==Ar(r)&&t.onFailure?.(e,r),0}let n=0;for(let i of r){if(!i.endsWith(Tr))continue;let r=Nr.join(e,i);try{await Mr(r,t)&&(n+=1)}catch(e){t.onFailure?.(r,e)}}return n}(i,{onReclaimed:(t,r)=>{Rr.resolve(t)===Rr.resolve(e)&&(n=r)}})}let o=await _r(e,t,r);void 0===n||o.sawOtherOwner||void 0!==function(e,t){let r=Mt.get(e);return r?.takeoverNonce===t?r.previous:void 0}(e,t.nonce)||Pt(e,n,t.nonce)}async function Cr(e,t,r,n){await Dr(e,t,n);try{return await r()}finally{await Ft(e,t)}}var Lr=e(()=>{ue(),Ir(),er(),Pr(),Ut(),Dt(),fr(),ir(),Ir(),Ut(),fr(),Sr(),ir()});import{randomUUID as zr}from"node:crypto";import jr from"node:path";function Fr(e,t,r){if(!Number.isInteger(r)||r<1)throw Error(`${t} slot must be a positive integer, got ${r}`);return jr.join(e,`${t}.slot-${r}.lock`)}async function Ur(e,t,r){await T(e,{recursive:!0,mode:448});let n=jr.join(e,`${t}.staging`);await le(n,`${JSON.stringify(r)}\n`,{mode:384}),await b(n,jr.join(e,t))}async function qr(e){try{return(await D(e)).filter(e=>e.endsWith(Yr)).sort()}catch(e){if("ENOENT"===Hr(e))return[];throw e}}async function Zr(e){try{await q(e)}catch(e){if("ENOENT"!==Hr(e))throw e}}async function Br(e,t){let r,n=jr.join(e,t);try{r=await(Kr.readFile??R)(n,"utf8")}catch(e){if("ENOENT"===Hr(e))return!0;if(function(e){if(void 0!==Kr.isSharingError)return Kr.isSharingError(e);if("win32"!==process.platform)return!1;let t=Hr(e);return"EBUSY"===t||"EPERM"===t||"EACCES"===t}(e))return!1;throw e}let i=Nt(r);return!(null===i||!await vr(i))&&(await Zr(n),!0)}async function Jr(e,t,r,n){for(let i=1;i<=r;i+=1){let r=Fr(e,t.purpose,i);try{return await Dr(r,t,{waitTimeoutMs:0,...void 0===n?{}:{signal:n}}),{slot:i,release:()=>Ft(r,t),retainFor:async(e,n)=>{let i=`${r}.handoff-${t.nonce}`;try{await le(i,`${JSON.stringify({...t,pid:e,process_start:n??"unavailable",git_activity_lock:void 0})}\n`,{mode:384}),await b(i,r)}finally{await Zr(i)}},releaseSync:()=>{try{return Nt(K(r,"utf8"))?.nonce===t.nonce&&(Q(r),!0)}catch(e){if("ENOENT"===Hr(e))return!1;throw e}}}}catch(e){if(e instanceof xr)continue;throw e}}}async function Gr(e,t,r={}){let n=r.maxConcurrent??t.defaultSlots,i=r.waitTimeoutMs??t.waitTimeoutMs,o=r.retryDelayMs??25;if(!Number.isInteger(n)||n<1)throw Error(`${t.purpose} maxConcurrent must be a positive integer, got ${n}`);if(i<0||o<=0)throw Error("lock wait options must be positive");let{signal:a}=r,s=function(e,t){return jr.join(e,`${t}.tickets`)}(e,t.purpose),l=(Vr=(Vr+1)%1e6,`${String(Date.now()).padStart(16,"0")}-${String(Vr).padStart(6,"0")}-${String(process.pid).padStart(10,"0")}-${zr()}${Yr}`),c=Date.now(),u=c+i,d=Wr.then(async()=>{a?.throwIfAborted(),await Ur(s,l,await At(`${t.purpose}:ticket`))});Wr=d.catch(()=>{});try{await d;let r=await At(t.purpose);for(let i=0;;i+=1){a?.throwIfAborted();let d=await qr(s),f=d[0];if(void 0!==f&&d.includes(l)){if(f===l){let t=await Jr(e,r,n,a);if(void 0!==t){try{await Zr(jr.join(s,l))}catch(e){throw await t.release(),e}return t}}else if(await Br(s,f))continue}else await Ur(s,l,await At(`${t.purpose}:ticket`));let m=Date.now();if(m>=u)throw t.busyError(m-c,n);await pr(Math.min(mr(i,o),Math.max(1,u-m)),a)}}finally{await Zr(jr.join(s,l)).catch(()=>{})}}function Hr(e){if(e instanceof Error&&"code"in e)return"string"==typeof e.code?e.code:void 0}var Wr,Kr,Yr=".ticket",Vr=0,Xr=e(()=>{ue(),Lr(),Tt(),Wr=Promise.resolve(),Kr={}}),Qr=e(()=>{Xr(),Xr()});var en=e(()=>{Xr()}),tn=e(()=>{Lr(),Tt(),xt(),Qr(),en()}),rn=e(()=>{ue()}),nn=e(()=>{ue(),rn(),rn()}),on=e(()=>{ue(),nn(),rn()}),an=e(()=>{nn(),on()});var sn,ln,cn=e(()=>{ue(),tn(),Lr(),Dt(),at(),an(),function(){let e=process.env.OMO_TEST_GIT_LOCK_SETTLE_MS;if(void 0===e)return;let t=Number.parseInt(e,10);return Number.isInteger(t)&&t>=0?t:void 0}()??300}),un=e(()=>{}),dn=e(()=>{ue()}),fn=e(()=>{ue()}),mn=e(()=>{ue()}),pn=e(()=>{ct(),mn()}),wn=e(()=>{mt()}),hn=e(()=>{ue()}),yn=e(()=>{sn=["process\\.env\\.[A-Za-z_][A-Za-z0-9_]*","os\\.environ(?:\\.get\\(|\\[)?","env\\.[A-Za-z_][A-Za-z0-9_]*","\\$\\{[A-Za-z_][A-Za-z0-9_]*\\}","\\$[A-Za-z_][A-Za-z0-9_]*","\\{\\{[^}\\n]*\\}\\}","\\[(?:redacted|filtered)\\]","(?:redacted|filtered)","(?:bearer|changeme|placeholder|example|none|null|undefined|true|false)"].join("|"),[["aws_access_key","\\bAKIA[0-9A-Z]{16}\\b",""],["credential_assignment",`\\b(?:bearer|token|api[_-]?key|secret|password|passwd|pwd)\\s*[=:]\\s*${ln=`(?!(?:${sn})(?![^\\s"'<>,}\\])]))`}[^\\s"'<>,}\\])]{1,256}`,"i"],["authorization_header",`\\bAuthorization\\s*:\\s*Bearer\\s+${ln}[^\\s"'<>,}\\])]{1,256}`,"i"],["openai_key","\\bsk-(?:proj-)?[-_A-Za-z0-9]+\\b",""],["vendor_token","\\b(?:ghp|github_pat|glpat|xox[baprs])[-_][-_A-Za-z0-9]+\\b",""]]}),vn=e(()=>{yn()}),gn=e(()=>{vn()}),bn=e(()=>{ue(),ue(),cn(),un(),lt(),mt(),ft(),ct(),dn(),fn(),pn(),wn(),hn(),gn()}),En=e(()=>{ue(),tn(),an(),cn()}),Sn=e(()=>{lt(),ft(),mt(),bn(),En(),vn()}),_n=e(()=>{String.raw`#!/bin/sh
4
4
  # Refuse a hand-written claim receipt header in memory notes. Installed by omo memory-core; regenerated on startup.
5
5
  grep -q '^Omo-Writer: memory-tool$' "$1" && exit 0
@@ -1,2 +1,2 @@
1
- // omo:OrdUqK7aZl7CKQEi0AZo8P_tt5xhBR1QH3rlgJzG4MU:xK-QHvwHF0Q5NsloBcL-YIKSA04047MqTHzSX2sZbxs
1
+ // omo:4g9bQJ_cgJ5gGTeBty2F9Kx-8PCkUqxKHx-HuP885MU:xK-QHvwHF0Q5NsloBcL-YIKSA04047MqTHzSX2sZbxs
2
2
  var e=/<(omo-[a-z0-9-]+-(?:pointer|mode)|ultrawork-mode|omo-ultrawork-reminder)>[\s\S]*?<\/\1>/gi,t=/(?<!`)(`+)(?!`)[\s\S]*?(?<!`)\1(?!`)/g,n=/^\s*(?:\[(?:[A-Z][A-Z0-9_-]{2,}|[\w.:@#-]+(?: via [\w.:@#-]+)* -> [\w.:@#-]+[^\]\n]{0,160})\]|[A-Z][\w.-]{0,30} \([^()\s]{1,40}\)(?:, | to )[\w.-]{1,40}:)/,s=/^ {0,3}>[^\n]*/gm,i=/"[^"\n]*"|\u201C[^\u201D\n]*\u201D/g,r=/(?<![\w'])'[^'\n]{1,200}'(?![\w])|\u2018[^\u2019\n]{1,200}\u2019/g,l=/(?<![a-z0-9+.-])[a-z][a-z0-9+.-]*:\/\/[^\s<>"'`]+/gi,o=(String.raw`(?<![A-Za-z0-9][-_.]|[/\\])`,String.raw`(?![-_.]?[A-Za-z0-9]*[/\\])`,String.raw`(?![-_.]?[A-Za-z0-9])`);String.raw`(?![-_](?!(?:loop|plan|research|execute|mass)${o})[A-Za-z0-9]|\.[A-Za-z0-9])`;function a(e){return e.replace(/[^\r\n]/g,"\0")}var d=[{id:"test.zero-fail",kind:"test",pattern:/(?<![0-9])0\s*(?:failed|failures?|fail)\b/i},{id:"test.ko-zero-fail",kind:"test",pattern:/실패\s*:?\s*0(?![0-9])/},{id:"test.n-of-n",kind:"test",pattern:/(?<![\w.])(\d+)\s*\/\s*\1\s*(?:pass(?:ed|ing|es)?|통과)/i},{id:"test.count-passed",kind:"test",pattern:/(?<![\w.])[1-9]\d*\s+pass(?:ed|ing)?\b/i},{id:"test.tests-pass",kind:"test",pattern:/\btests?\b[^.\n\0]{0,30}?\b(?:pass(?:es|ed|ing)?|(?:are|is|stays?) green)\b/i},{id:"test.suite-pass",kind:"test",pattern:/\b(?:suite|ci|checks)\b[^.\n\0]{0,20}?\b(?:pass(?:es|ed)?|green|succeed(?:s|ed)?)\b/i},{id:"test.should-pass",kind:"test",pattern:/\b(?:should|will|would)\s+(?:now\s+|still\s+|all\s+)?pass\b/i},{id:"test.ko-tests",kind:"test",pattern:/테스트[^.\n\0]{0,15}통과/},{id:"test.ko-all",kind:"test",pattern:/(?:모두|전부|다)\s*통과/},{id:"test.ko-passed",kind:"test",pattern:/통과(?:했|합니다|해요|함|됐|된다|될|할)/},{id:"test.ko-count",kind:"test",pattern:/(?<![0-9])[1-9]\d*\s*(?:개|건)?\s*통과/},{id:"typecheck.clean",kind:"typecheck",pattern:/\b(?:typecheck(?:s|ing)?|type ?check(?:s|ing)?|tsc|tsgo|types)\b[^.\n\0]{0,20}?\b(?:pass(?:es|ed)?|clean|green|succeed(?:s|ed)?|ok)\b/i},{id:"typecheck.no-errors",kind:"typecheck",pattern:/\bno (?:type|ts|typescript) errors?\b/i},{id:"typecheck.ko",kind:"typecheck",pattern:/타입\s*(?:체크|검사)[^.\n\0]{0,12}(?:통과|성공|깨끗)|타입\s*(?:에러|오류)\s*(?:없|0)/},{id:"lint.clean",kind:"lint",pattern:/\blint(?:er|ing)?\b[^.\n\0]{0,20}?\b(?:pass(?:es|ed)?|clean|green)\b|린트[^.\n\0]{0,12}(?:통과|성공|깨끗)/i},{id:"build.ok",kind:"build",pattern:/\bbuilds?\b[^.\n\0]{0,15}?\b(?:pass(?:es|ed)?|succeed(?:s|ed)?|green|works|ok)\b/i},{id:"build.ko",kind:"build",pattern:/빌드[^.\n\0]{0,12}(?:성공|통과|됩니다|됐|돼요)/},{id:"run.works",kind:"run",pattern:/\b(?:works|is working|runs) (?:as expected|correctly|end to end|fine)\b|(?:정상(?:적으로)?|잘)\s*(?:동작|작동)/i},{id:"exists.already",kind:"exists",pattern:/\balready\s+(?:exists?|implemented|in place|supported|wired up|present)\b/i},{id:"exists.ko",kind:"exists",pattern:/이미\s*(?:있|존재|구현(?:되어|돼|됐|되었|했|해)|되어|돼|지원(?:되|돼|해|합)|반영(?:되|돼|됐|했)|들어)/},{id:"done.leading",kind:"done",pattern:/^(?:done|completed|finished|fixed|implemented|verified|confirmed|all set)\b/i},{id:"done.ko-leading",kind:"done",pattern:/^(?:완료|끝|구현 완료|수정 완료|확인 완료)/},{id:"done.ko",kind:"done",pattern:/완료(?:했|됐|되었|입니다|됨)|끝났(?:어요|습니다|다)/}],u=/(?<![0-9])[1-9]\d*\s*(?:failed|failures?|fail)\b|실패\s*:?\s*[1-9]|(?<![0-9])[1-9]\d*\s*(?:건|개)?\s*실패/i,c=/\b(?:not|never|cannot|no longer)\b|n't\b/i,f=/\b(?:fail(?:s|ed|ing|ures?)?|broken|red)\b/i,p=/않|못|아니|(?:^|\s)안\s|미(?:통과|완료|구현|검증|반영)|불통과|실패(?:하|했|해|함|입니다|예요|중)|(?:에러|오류)가\s*(?:나|발생)/,h=/\b(?:not (?:yet )?(?:been )?(?:run|ran|verified|tested|checked|executed)|(?:haven't|have not|hasn't|has not|didn't|did not|couldn't|could not)\s+(?:yet\s+)?(?:run|verify|test|check|execute|re-?run)|untested|unverified|without (?:running|testing|verifying))\b/i,k=/아직\s*(?:안|못)|안\s*(?:돌렸|돌려|돌림|해\s*봤|실행)|못\s*(?:돌렸|돌려|돌림|해\s*봤|실행)|돌리지\s*(?:않|못)|실행(?:하지|은)?\s*(?:않|못|안)|미검증|미확인|(?:검증|확인)(?:하지|은|도)?\s*(?:전|안|못)|(?:검증|확인)되지\s*않/,b=/\b(?:should|would|ought to|expected to|likely|probably|presumably|i think|i believe|i assume|might)\b|거예요|겁니다|거야|것\s*같|거\s*같|듯|아마|예상|(?:할|될|일)\s*(?:거|것)/i,m=/^(?:Ask|Now|Next|wanted):/i,g=/\b(?:if|once|when|whenever|whether|until|unless|as soon as|as each)\b|(?:하|되|으|이|라)면(?=[\s,.]|$)|(?:할|될)\s*때/i,w=/(?<![\w.])\d+\s*(?:\/\s*\d+|pass(?:ed|ing)?|tests?|fail(?:ed|ures?)?)\b|(?<![\w.])\d+\s+(?:of\s+\d+|(?:[A-Za-z-]+\s+){1,2}tests?)\b|(?<![\w.])\d+\s*(?:\uAC1C|\uAC74)|\bexit(?:s|ed)?\s*(?:code\s*)?0\b|\b[A-Z_]*EXIT=0\b/i,v=/\u2018[^\u2019\n]*\u2019|[\u300C\u300E][^\u300D\u300F\n]*[\u300D\u300F]/g,y=/^[\s\0]*(?:[-*\u2022]|\d+[.)]|[\u2705\u2714\u2611]\uFE0F?)?\s*/;function x(e){return e.replace(/[^\r\n]/g,"\0")}function S(o){return function(o){if(n.test(o))return a(o);let d=o.replace(e,a),u=/^ {0,3}(`{3,}|~{3,})[^\n]*(?:\n|$)/gm;for(;;){let e=u.exec(d);if(null===e)break;let t=e[1],n=new RegExp(`^ {0,3}${t[0]}{${t.length},}[ \\t]*\\r?$`,"gm");n.lastIndex=u.lastIndex;let s=null===n.exec(d)?d.length:n.lastIndex;d=d.slice(0,e.index)+a(d.slice(e.index,s))+d.slice(s),u.lastIndex=s}return d.replace(t,a).replace(s,a).replace(i,a).replace(r,a).replace(l,a)}(o).replace(v,x)}var A=new Set(["test.zero-fail","test.ko-zero-fail","typecheck.no-errors","typecheck.ko"]);function _(e){let t=S(e),n=function(e){let t=[],n=0;for(let s=0;s<=e.length;s+=1){let i=e[s],r=s===e.length,l=void 0!==i&&/[.!?\u3002]/.test(i)&&(s+1===e.length||/\s/.test(e[s+1]??""));if(!r&&"\n"!==i&&!l)continue;let o=l?s+1:s;""!==e.slice(n,o).replace(/[\s\0]/g,"")&&t.push({start:n,end:o}),n=o}return t}(t),s=[];return n.forEach((i,r)=>{let l=t.slice(i.start,i.end),o=function(e){let t=y.exec(e)?.[0].length??0,n=e.slice(t).trimEnd();if(m.test(n))return;let s=u.test(n);for(let e of d){if(s&&"test"===e.kind)continue;let i=e.pattern.exec(n);if(null!==i)return{rule:e,index:t+i.index,length:i[0].length}}}(l);if(void 0===o||g.test(l))return;let a=function(e){return h.test(e)||k.test(e)}(n.slice(Math.max(0,r-1),r+2).map(e=>t.slice(e.start,e.end)).join(" "));!a&&function(e,t,n,s){let i=A.has(t)?(l=n,o=s,(r=e).slice(0,l)+" ".repeat(o-l)+r.slice(o)):e;var r,l,o;return!(!c.test(i)&&!p.test(i))||f.test(i.slice(s))}(l,o.rule.id,o.index,o.index+o.length)||s.push({kind:o.rule.kind,strength:b.test(l)?"hedged":"asserted",admitted:a,reported:w.test(l),sentence:e.slice(i.start,i.end).trim(),rule:o.rule.id})}),s}function $(e){return"object"==typeof e&&null!==e}function C(e,t){let n=function(e){if(!$(e))return[];let t=P(e.files);if(t.length>0)return t;let n=e.result,s=$(n)?P(n.files):[];if(s.length>0)return s;let i=e.metadata;return $(i)?P(i.files):[]}(e).filter(e=>"delete"!==e.type?.toLowerCase()).map(e=>({filePath:e.movePath??e.filePath,before:e.before,after:e.after}));if(n.length>0)return n;let s=void 0===t?void 0:I(t,["patchText","input","patch","command"]);return void 0===s?[]:function(e){let t,n=[],s=()=>{if(void 0!==t){if("add"===t.operation){let e=Z(t.newLines);e.length>0&&n.push({filePath:t.filePath,before:"",after:e})}if("update"===t.operation){let e=Z(t.newLines);e.length>0&&n.push({filePath:t.movePath??t.filePath,before:Z(t.oldLines),after:e})}t=void 0}};for(let n of e.split(/\r?\n/))"*** Begin Patch"!==n&&"*** End Patch"!==n&&(n.startsWith("*** Add File: ")?(s(),t=z("add",n.slice(14).trim())):n.startsWith("*** Update File: ")?(s(),t=z("update",n.slice(17).trim())):n.startsWith("*** Delete File: ")?(s(),t=z("delete",n.slice(17).trim())):n.startsWith("*** Move to: ")?"update"===t?.operation&&(t.movePath=n.slice(13).trim()):void 0===t||n.startsWith("@@")||("add"!==t.operation?"update"===t.operation&&(n.startsWith("-")&&t.oldLines.push(n.slice(1)),n.startsWith("+")&&t.newLines.push(n.slice(1))):n.startsWith("+")&&t.newLines.push(n.slice(1))));return s(),n}(s)}function P(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!$(n))continue;let e=I(n,["filePath","file_path","path"]),s=I(n,["movePath","move_path"]),i=I(n,["before","old","oldString","old_string"]),r=I(n,["after","new","newString","new_string"]),l=I(n,["type","operation"]);void 0!==e&&void 0!==i&&void 0!==r&&t.push({filePath:e,before:i,after:r,...void 0===s?{}:{movePath:s},...void 0===l?{}:{type:l}})}return t}function z(e,t){return{operation:e,filePath:t,oldLines:[],newLines:[]}}function I(e,t){for(let n of t){let t=e[n];if("string"==typeof t)return t}}function Z(e){return 0===e.length?"":`${e.join("\n")}\n`}var E=new Set(["write","edit","apply_patch"]);function F(e){let t=new Set,n=e=>{"string"==typeof e&&e&&t.add(e)},s=e=>{Array.isArray(e)&&e.forEach(n)};n(e.input.path),n(e.input.filePath),s(e.input.paths),s(e.input.filePaths);for(let t of C(e.details,e.input))n(t.filePath);if("string"==typeof e.input.input)for(let t of e.input.input.split(/\r?\n/))for(let e of["*** Add File: ","*** Update File: ","*** Move to: "])t.startsWith(e)&&n(t.slice(e.length).trim());for(let t of["files","changes"]){let s=e.input[t];if(Array.isArray(s))for(let e of s)if("object"==typeof e&&e){let t=e;n(t.path),n(t.filePath),n(t.movePath)}}return[...t]}var j=/(?<!<)<<(?!<)-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/,W=/(?<!<<-?\s*)(?:'[^']*'|"(?:\\.|[^"\\])*")/g,T=new Set(["\n",";","|","&","(",")","`"]);function L(e){let t=null;for(let n=0;n<e.length;n+=1){let s=e[n];if(null!==t)s===t&&(t=null);else if("'"===s||'"'===s)t=s;else if("#"===s&&(0===n||/\s/.test(e[n-1])))return e.slice(0,n)}return e}function R(e){let t=function(e){let t=[],n=null;for(let s of e.split("\n"))null===n?(t.push(L(s)),n=j.exec(L(s).replace(W,""))?.[2]??null):s.trim()===n&&(n=null);return t.join("\n")}(e),n=[],s=[],i="",r=!1,l=null,o=()=>{r&&s.push(i),i="",r=!1},a=()=>{o(),s.length>0&&n.push(s),s=[]};for(let e=0;e<t.length;e+=1){let n=t[e];null===l?"'"!==n&&'"'!==n?"\\"===n&&e+1<t.length?(i+=t[e+1],r=!0,e+=1):"$"===n&&"("===t[e+1]||(T.has(n)?a():" "!==n&&"\t"!==n?(i+=n,r=!0):o()):(l=n,r=!0):n===l?l=null:i+=n}return a(),n}var M=/^[A-Za-z_][A-Za-z0-9_]*=/,D=/(?:^|\/)(?:heavy-slot|early-static-slot|launch-detached)\.sh$/,N=new Set(["bash","sh","zsh"]),O=new Set(["do","then","else","elif","if","while","until","!","{","}"]),X=new Set(["env","time","nohup","command","exec","sudo"]),q={env:new Set(["-u","-C","-P"]),sudo:new Set(["-u","-g","-h","-p","-c","-C","-D","-r","-R","-t","-U","-T"]),time:new Set(["-f","-o"])},B=new Set(["uv","poetry","pdm","pipx","hatch","rye"]),U=/^python(?:3(?:\.\d+)?)?$/,J=new Set(["make","just","task"]),Q=/(?:^|\/)scripts\/qa\//,G=new Set(["bun","npm","pnpm","yarn"]),H=new Set(["bunx","npx","pnpx"]),K=new Set(["rg","grep","egrep","cat","head","tail","ls","find","fd","sg","ast-grep"]),V=new Set("BbcDEeFIiJLlmOoPpQRSWw".split("")),Y=/check-runs|check-suites|\/status(?:es)?\b/;function ee(e,t,n){let s=t;for(;s<e.length&&e[s].startsWith("-");)s+=n?.has(e[s])?2:1;return e.slice(s)}var te=e=>e.flatMap(e=>{let t=function(e){return/^test(?::|$)/.test(e)?"test":/^(?:typecheck|type-check)(?::|$)/.test(e)?"typecheck":/^lint(?::|$)/.test(e)?"lint":/^build(?::|$)/.test(e)?"build":void 0}(e);return t?[t]:[]});function ne(e,t){let[n="",s=""]=t;if(("bun"===e||"node"===e||"tsx"===e)&&t.some(e=>Q.test(e)))return["run"];if(J.has(e))return te(ee(t,0)).slice(0,1);if("vitest"===e||"jest"===e||"pytest"===e)return["test"];if("playwright"===e&&"test"===n)return["test"];if("tsc"===e||"tsgo"===e||"mypy"===e||"pyright"===e)return["typecheck"];if("eslint"===e||"oxlint"===e||"ruff"===e)return["lint"];if("biome"===e&&["check","lint","ci"].includes(n))return["lint"];if("cargo"===e){if("test"===n)return["test"];if("check"===n)return["typecheck"];if("clippy"===n)return["lint"];if("build"===n)return["build"]}if("go"===e&&("test"===n||"build"===n))return["test"===n?"test":"build"];if("deno"===e&&"test"===n)return["test"];if(("vite"===e||"next"===e)&&"build"===n)return["build"];if("gh"===e)return function(e){let[t="",n=""]=e;return"pr"===t&&"checks"===n||"pr"===t&&"view"===n&&e.some(e=>e.includes("statusCheckRollup"))?["test"]:"run"!==t||"view"!==n&&"watch"!==n?"api"===t&&e.some(e=>Y.test(e))?["test"]:[]:["test"]}(t);if("vp"===e){if("test"===n)return["test"];if("check"===n)return["typecheck","lint"];if("lint"===n)return["lint"];if("run"===n)return te(t.slice(1))}if(G.has(e)){if("bun"===e&&"test"===n)return["test"];if("bun"===e&&"check"===n)return["typecheck"];if("bun"===e&&"build"===n)return["build"];if("run"===n)return te([s]);if("bun"!==e&&"test"===n)return["test"]}return K.has(e)?["lookup"]:"git"!==e||"grep"!==n&&"show"!==n?[]:["lookup"]}function se(e,t,n){if("env"===e&&t.includes("-S")){let e=t.indexOf("-S");return n>=3?[]:re(t.slice(e+1).join(" "),n+1)}if(X.has(e))return ie(ee(t,1,q[e]),n);if(B.has(e)&&"run"===t[1])return ie(ee(t,2),n);if(U.test(e)){let e=t.indexOf("-m");return-1!==e?ie(t.slice(e+1),n):t.some(e=>Q.test(e))?["run"]:[]}if("timeout"===e)return ie(function(e){let t=1;for(;t<e.length&&e[t].startsWith("-");){let n=e[t];t+="-k"===n||"-s"===n||"--kill-after"===n||"--signal"===n?2:1}return e.slice(t+1)}(t),n);if("nice"===e)return ie("-n"===t[1]?t.slice(3):t.slice(1),n);if(D.test(t[0])){let e=t.indexOf("--");return-1===e?[]:ie(t.slice(e+1),n)}if("ssh"===e){let e=function(e){let t=1;for(;t<e.length&&e[t].startsWith("-");){let n=e[t];t+=2===n.length&&V.has(n.slice(1))?2:1}let n=e.slice("--"===e[t+1]?t+2:t+1);return 0===n.length?void 0:n.join(" ")}(t);return void 0===e||n>=3?[]:re(e,n+1)}if(N.has(e)){let e=t.findIndex((e,t)=>t>0&&/^-[a-z]*c$/.test(e));if(-1===e)return ee(t,1).slice(0,1).some(e=>Q.test(e))?["run"]:[];let s=t[e+1];return void 0===s||n>=3?[]:re(s,n+1)}return H.has(e)?ie(t.slice(1).filter(e=>!e.startsWith("-")),n):"bun"===e&&"x"===t[1]||"pnpm"===e&&"exec"===t[1]?ie(t.slice(2),n):void 0}function ie(e,t){let n=e;for(;n.length>0&&(M.test(n[0])||O.has(n[0]));)n=n.slice(1);if(0===n.length)return[];if(Q.test(n[0]))return["run"];let s=(i=n[0]).slice(i.lastIndexOf("/")+1);var i;return se(s,n,t)??ne(s,n.slice(1))}function re(e,t=0){let n=[];for(let s of R(e))for(let e of ie(s,t))n.includes(e)||n.push(e);return n}var le=/"""[\s\S]*?"""|'''[\s\S]*?'''|`(?:\\[\s\S]|[^`\\])*`|'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"/g,oe=/\[\s*(?:"""|'''|[`'"])[^\[\]]*\]/g,ae=/^(?:"""|'''|[`'"])|(?:"""|'''|[`'"])$/g,de=/^(?:f|r|rf|fr|b)?$/i,ue=/\$\{[^}]*\}|\{[A-Za-z_][\w.]*\}/g,ce=String.raw`(?:sh|sh\d+|shr|shm|sh_\w+|run|run_\w+|\w+_run|exec|execa|execSync|exec_\w+|\w+_exec|spawn|spawnSync|system|popen|Popen|check_output|check_call|call|shell|bash|zsh|ssh|rsh|rd|q|s|\$)`,fe=new RegExp([String.raw`(?:^|[^\w$])${ce}\s*\(\s*(?:\[\s*)?[A-Za-z]{0,2}$`,String.raw`(?:^|[^\w])(?:\$|sh|run|exec)\s*$`,String.raw`\b(?:commands?|cmds?|scripts?|shell|jobs?|steps?|s)\s*[:=]\s*(?:\[\s*)?[A-Za-z]{0,2}$`,String.raw`\bfor\s*\(?\s*(?:const|let|var)?\s*\w+\s+(?:in|of)\s*$`].join("|")),pe=/(?:\[|\],)\s*$/,he=(e,t)=>e.slice(Math.max(0,t-80),t),ke=(e,t)=>fe.test(he(e,t)),be=(e,t)=>ke(e,t)||pe.test(he(e,t)),me=e=>e.replace(ae,"").replace(ue,"X"),ge=e=>`'${e.replaceAll("'","'\\''")}'`,we=e=>re(e).filter(e=>"lookup"!==e);function ve(e,t){let n=function(e){let t=[];for(let n of e.slice(1,-1).split(",")){let e=n.trim();if(""===e)continue;let s=e.match(le)?.[0],i=void 0!==s&&e.endsWith(s)&&de.test(e.slice(0,-s.length));t.push(i?me(s):"X")}return t}(e),[s="",i=""]=n;if(/\s/.test(s))return n.flatMap(we);let r=we(n.map(ge).join(" "));return t&&2===n.length&&/^[\w:.-]+$/.test(s)&&/\s/.test(i)?[...r,...we(i)]:r}var ye=[/(?<![0-9])[1-9]\d*\s+fail(?:ed|ures?)?\b(?![=:])/i,/\bfail(?:ed|ures?)?=(?:[1-9]|\[[^\]\s])/i,/^\(fail\)/m,/\bFAIL\b/,/\berror TS\d+/,/AssertionError/,/^\s*error(?:\[[^\]]*\])?:/im,/\b[A-Z_]*EXIT[=:]\s*[1-9]\d*\b/,/\bexit(?:ed)?(?: with)?(?: code| status)?\s*[:=]?\s*[1-9]\d*\b/i,/\bTests?:?\s+[1-9]\d* failed/,/\bTest Files\s+[1-9]\d* failed/,/"exitCode":\s*[1-9]/,/\bFound [1-9]\d* errors?\b/,/Files with errors:\s*[1-9]/,/\tfail\t/],xe=[/\t(?:pending|queued|in_progress)\t/],Se=[/(?<![0-9])0\s+fail(?:ed|ures?)?\b/i,/\bfail(?:ed|ures?)?=(?:0\b|\[\])/i,/(?<![0-9])[1-9]\d*\s+pass(?:ed)?\b/i,/\bTests?:?\s+\d+ passed/,/\bTest Files\s+\d+ passed/,/"exitCode":\s*0\b/,/\bAll tests passed\b/i,/\b[A-Z_]*EXIT[=:]\s*0\b/,/\bexit(?:ed)?(?: with)?(?: code| status)?\s*[:=]?\s*0\b/i,/\bFound 0 errors\b/,/\bNo diagnostics found\b/,/Files with errors:\s*0\b/,/\bNo fixes applied\b/,/\tpass\t/],Ae=/\bTool \S+ not found\b|\bpermission denied by\b|\b(?:was|were) denied\b|\bblocked by (?:policy|the user|a hook)\b|\brequires approval\b|\b(?:aborted|cancelled) by the user\b/i;function _e(e,t){return e?Ae.test(t)?"unknown":"failed":$e(t)}function $e(e){return ye.some(t=>t.test(e))?"failed":xe.some(t=>t.test(e))?"unknown":Se.some(t=>t.test(e))?"passed":"unknown"}var Ce=/(?:^|\/)(?:\.omo|omo-runs|tmp|evidence|notepads?)\/|^\/(?:private\/)?tmp\/|\.(?:md|txt|log|jsonl|csv)$/i;function Pe(e){return!Ce.test(e)}var ze=new Set(["read","grep","glob","find","ls","lsp_goto_definition","lsp_find_references","lsp_symbols","ast_grep"]),Ie=e=>{let t=re(e);return{kinds:t.filter(e=>"lookup"!==e),lookup:t.includes("lookup")}},Ze=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ee=e=>Array.isArray(e)?e:[],Fe=e=>"string"==typeof e?e:"";function je(e){return"string"==typeof e?e:Ee(e).map(e=>Ze(e)&&"text"===e.type?Fe(e.text):"").join("\n")}var We=/\bID:\s*([\w-]+)/,Te=/Detached eval cell (\S+) \(\w+\) (completed|failed)/,Le=/Background terminal session (\S+) finished: (\w+) \(exit code (-?\d+)\)/,Re=/Monitor event\(([^)]*)\)/;class Me{checks=[];edits=[];#e=new Map;#t=new Map;#n=new Map;addCheck(e,t,n,s){for(let i of n.kinds)this.checks.push({at:e,entryId:t,kind:i,outcome:s,command:n.command.slice(0,200)})}addEdit(e,t,n){this.edits.push({at:e,entryId:t,paths:n,relevant:0===n.length||n.some(Pe)})}entry(e,t){if(!Ze(e))return;let n=Fe(e.id);if("custom_message"===e.type)return this.notification(Fe(e.customType),je(e.content),e.details,t,n);let s=e.message;if("message"===e.type&&Ze(s))if("assistant"!==s.role)"toolResult"===s.role&&this.toolResult(s,t,n);else for(let e of Ee(s.content))Ze(e)&&"toolCall"===e.type&&this.#e.set(Fe(e.id),{name:Fe(e.name),args:Ze(e.arguments)?e.arguments:{}})}toolResult(e,t,n){let s=Fe(e.toolName),i=Fe(e.toolCallId),r=this.#e.get(i)?.args??{},l=!0===e.isError,o=je(e.content);if("eval"===s)return this.evalResult(i,r,e.details,o,l,t,n);if(E.has(s))l||this.addEdit(t,n,F({toolName:s,input:r,details:e.details}));else{if("lsp_diagnostics"===s)return this.lsp(o,l,t,n);if(ze.has(s))return this.lookup(l,o,t,n);if("bash"===s||"powershell"===s){let e=Fe(r.command),{kinds:s,lookup:i}=Ie(e);s.length>0&&this.addCheck(t,n,{kinds:s,command:e},_e(l,o)),i&&0===s.length&&this.lookup(l,o,t,n)}}}lookup(e,t,n,s){e||""===t.trim()||this.checks.push({at:n,entryId:s,kind:"lookup",outcome:"passed"})}lsp(e,t,n,s){if(t)return;let i=$e(e);"unknown"!==i&&this.checks.push({at:n,entryId:s,kind:"lsp",outcome:i})}evalResult(e,t,n,s,i,r,l){let o=Ze(n)?n:{},a=Ee(o.toolCalls).filter(Ze);for(let e of a)this.hostCall(e,r+.5,l);if(a.some(e=>"bash"===e.name))return;let d=Ee(o.cells).filter(Ze),u={code:Fe(t.code),output:s,status:i?"error":"complete"};for(let t of d.length>0?d:[u])this.cell(e,Fe(t.code),Fe(t.output),t.status,r,l)}hostCall(e,t,n){let s=Fe(e.name),i=Ze(e.args)?e.args:{},r=Fe(e.resultPreview);if(E.has(s))return void(!1!==e.ok&&this.addEdit(t,n,F({toolName:s,input:i})));if("lsp_diagnostics"===s)return this.lsp(r,!1===e.ok,t,n);if(ze.has(s))return this.lookup(!1===e.ok,r,t,n);if("bash"!==s&&"monitor"!==s)return;let l=Fe(i.command),{kinds:o,lookup:a}=Ie(l);if(0===o.length)return void(a&&"bash"===s&&this.lookup(!1===e.ok,r,t,n));let d="monitor"===s||!0===i.run_in_background;if(d&&!1===e.ok)return;let u=d?We.exec(r)?.[1]:void 0;if(void 0!==u)return this.#t.set(u,{kinds:o,command:l}),void("monitor"===s&&this.#t.set(`desc:${Fe(i.description)}`,{kinds:o,command:l}));this.addCheck(t,n,{kinds:o,command:l},_e(!1===e.ok,r))}cell(e,t,n,s,i,r){let{kinds:l,offset:o}=function(e){let t=[],n=-1,s=(e,s)=>{if(0!==s.length){(-1===n||e<n)&&(n=e);for(let e of s)t.includes(e)||t.push(e)}},i=[];for(let t of e.matchAll(oe))i.push([t.index,t.index+t[0].length]),be(e,t.index)&&s(t.index,ve(t[0],pe.test(he(e,t.index))));for(let t of e.matchAll(le))i.some(([e,n])=>t.index>=e&&t.index<n)||ke(e,t.index)&&s(t.index,we(me(t[0])));return{kinds:t,offset:n}}(t);if(0===l.length)return;let a={kinds:l,command:t},d=i+(o+1)/(t.length+2);return"complete"===s&&"passed"===$e(n)?this.addCheck(d,r,a,"passed"):"complete"===s||"error"===s?this.addCheck(d,r,a,"unknown"):(this.#n.set(e,a),void this.addCheck(d,r,a,"unknown"))}notification(e,t,n,s,i){if("omo-senpi:wake"!==e){if("senpi-codemode:notification"===e){let e=Te.exec(t),n=null===e?void 0:this.#n.get(e[1]??"");if(null===e||void 0===n)return;this.#n.delete(e[1]??"");let r="completed"===e[2]&&"passed"===$e(t.slice(e.index+e[0].length));return void this.addCheck(s,i,n,r?"passed":"unknown")}if("senpi-terminal:notification"===e){let e=Le.exec(t),n=null===e?void 0:this.#t.get(e[1]??"");if(null===e||void 0===n)return;if(this.#t.delete(e[1]??""),"killed"===e[2])return;return void this.addCheck(s,i,n,"0"===e[3]?$e(t):"failed")}if("senpi-monitor:notification"===e){if(/\bwatcher (?:killed|timed_out)\b|\bwatcher\b[^\n]*\bkilled\b/.test(t))return;let e=Ee(Ze(n)?n.monitors:void 0).map(e=>Ze(e)?Fe(e.id):""),r=Re.exec(t)?.[1],l=e.map(e=>this.#t.get(e)).find(e=>void 0!==e)??(void 0===r?void 0:this.#t.get(`desc:${r}`)),o=$e(t);void 0!==l&&"unknown"!==o&&this.addCheck(s,i,l,o)}}else for(let e of Ee(n).filter(Ze)){let n=Ee(e.contentRange),[r,l]=[n[0],n[1]],o="number"==typeof r&&"number"==typeof l?t.slice(r,l):t;this.notification(Fe(e.customType),o,e.details,s,i)}}}var De=new Set(["test","typecheck","lint","build","run","lsp"]),Ne={test:new Set(["test"]),typecheck:new Set(["typecheck","lsp"]),lint:new Set(["lint"]),build:new Set(["build"]),run:new Set(["run","test","build"]),exists:new Set([...De,"lookup"]),done:De},Oe=new Set(["done","run"]),Xe=e=>({entryId:e.entryId,kind:e.kind,outcome:e.outcome}),qe=e=>e.reduce((e,t)=>void 0===e||t.at>=e.at?t:e,void 0);function Be(e,t,n){if(e.admitted)return{claim:e,status:"admitted"};if(Oe.has(e.kind)&&!n.some(e=>e.relevant))return{claim:e,status:"unknown"};let s=Ne[e.kind],i=t.filter(e=>s.has(e.kind));if("exists"===e.kind)return function(e,t,n){let s=qe(t.filter(e=>"passed"===e.outcome));return void 0!==s?{claim:e,status:"supported",receipt:Xe(s)}:e.reported||n>0?{claim:e,status:"unknown"}:{claim:e,status:"unsupported",reason:"no-check"}}(e,i,t.length);let r=qe(i);if(void 0===r){let n=t.some(e=>"lookup"!==e.kind);return e.reported||n?{claim:e,status:"unknown"}:{claim:e,status:"unsupported",reason:"no-check"}}let l=qe(i.filter(e=>"unknown"!==e.outcome)),o=e.reported&&"unknown"===r.outcome;if("failed"===l?.outcome&&!o)return{claim:e,status:"unsupported",reason:"last-check-failed",receipt:Xe(l)};if("unknown"===r.outcome)return{claim:e,status:"unknown",receipt:Xe(r)};let a=qe(n.filter(e=>e.relevant&&e.at>r.at));return void 0!==a?{claim:e,status:"unsupported",reason:"stale-after-edit",receipt:Xe(r),invalidatedBy:{entryId:a.entryId,paths:a.paths}}:{claim:e,status:"supported",receipt:Xe(r)}}var Ue=e=>"unsupported"===e.status;function Je(e,t,n){let s=_(je(n));if(0===s.length)return;let i=function(e,t,n){let s=e.checks.filter(e=>e.at<n),i=e.edits.filter(e=>e.at<n);return t.map(e=>Be(e,s,i))}(function(e){let t=new Me;return e.forEach((e,n)=>t.entry(e,n)),{checks:t.checks,edits:t.edits}}(e),s,t);return{verdicts:i,flagged:i.filter(Ue)}}export{Je as evaluateAnswer};
@@ -1,2 +1,2 @@
1
- // omo:7rceahrHgPuvaY-JBtGwfzxLLpmb9Onoqj3L22A4OL8:rwfly50qq8cw1HZyKbCz-GaoyIhDjP9CCcRuhdRoRMo
1
+ // omo:q_uAI57aKOdl6nTf10zwL8Ne_1RmIIdRZsLOlTi-mcs:rwfly50qq8cw1HZyKbCz-GaoyIhDjP9CCcRuhdRoRMo
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 c}from"node:path";import{DatabaseSync as u}from"node:sqlite";function d(t){return e("sha256").update(o(t)).digest("hex")}import{tmpdir as p}from"node:os";import{join as h}from"node:path";var f=".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 y extends Error{constructor(){super("Computer use is off for this session; the user can turn it on with /computer on."),this.name="ComputerDisabledError"}}class v{#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 y;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?h(i.auditDir,f):null,artifactDir:p(),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?h(t.sessionManager.getSessionDir(),f):null,artifactDir:p(),screenshotGc:{staleMs:r.enabled?r.staleMs:m,scanIntervalMs:r.scanIntervalMs},captureCaps:{maxWidth:e.maxWidth,maxHeight:e.maxHeight,coordinateSafe:g(t.model),maxBytes:e.screenshotMaxBytes}}}(e,t),r=JSON.stringify(n);this.#o?.key!==r&&(this.#o={key:r,done:this.#e.open(n)});let i=this.#o;try{await i.done}catch(e){throw this.#o===i&&(this.#o=void 0),e}}#l(e){if(this.#s!==e){this.#s=e;for(let t of this.#n)t(e)}}}import{Errors as 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 E=x.Union([x.Literal("left"),x.Literal("right"),x.Literal("middle")]),$={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."}))},S={x:x.Number(),y:x.Number()},P={additionalProperties:!1},z=[x.Object({action:x.Literal("screenshot"),...$},P),x.Object({action:x.Literal("click"),...S,button:x.Optional(E),...$},P),x.Object({action:x.Literal("double_click"),...S,button:x.Optional(E),...$},P),x.Object({action:x.Literal("move"),...S,button:x.Optional(E),...$},P),x.Object({action:x.Literal("drag"),...S,to_x:x.Number(),to_y:x.Number(),button:x.Optional(E),...$},P),x.Object({action:x.Literal("scroll"),...S,scroll_x:x.Number(),scroll_y:x.Number(),...$},P),x.Object({action:x.Literal("type"),text:x.String(),...$},P),x.Object({action:x.Literal("keypress"),keys:x.Array(x.String(),{minItems:1}),...$},P),x.Object({action:x.Literal("wait"),ms:x.Integer({minimum:0}),...$},P)],I=x.Union([...z]),T=x.Object({action:x.Literal("batch"),actions:x.Array(I,{minItems:1}),...$},P),A=x.Union([I,T]),C=["screenshot","click","double_click","move","drag","scroll","type","keypress","wait"],R={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"})),...$},N=x.Object({action:x.Enum([...C,"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([...C],{type:"string",description:"The action to perform"}),...R},P),{minItems:1,description:"batch (required): actions to execute in order"})),...R},P),j=_(z),M=_([...z,T]);var U=new Set(["screenshot","wait"]);var D=/^senpi-desktop-engine: refusing to run as its own responsible process \(pid [1-9]\d*\): spawn the engine as a child of the app, terminal or host that holds the computer-use grants, without the responsibility-disclaim attribute and not as a launchd job or through a shell exec$/,L=/^senpi-desktop-engine: refusing to run: the responsible process of engine pid [1-9]\d* cannot be resolved$/;class 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{#c="";#u=!1;#d=!1;#p=!1;#h=!1;#f;#m;#g="";disable(){this.#d=!0,this.#c=""}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.#u||=Buffer.byteLength(this.#c+r,"utf8")>=512,this.#c+=r.slice(0,Math.max(0,512-this.#c.length)),-1===n)return;this.#y(),this.#c="",this.#u=!1,t=n+1}}finish(e,t,n){if(this.#c.startsWith("SENPI_DESKTOP_LAUNCH_REFUSED")&&(this.#h=!0),this.#d||this.#h||1!==e||null!==t)return;let r=this.#p?this.#f:this.#m;return void 0===r?void 0:new Z(r,`${this.#g}\n${n}`)}#y(){if(this.#c.startsWith("SENPI_DESKTOP_LAUNCH_REFUSED")){this.#p&&(this.#h=!0),this.#p=!0;let e=this.#u?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.#c);return void(void 0===e?this.#h=!0:(this.#f=e,this.#g=this.#c))}if(this.#u)return;let e=D.test(this.#c)?"self-responsible":L.test(this.#c)?"unresolved":void 0;void 0!==e&&(void 0!==this.#m&&this.#m!==e&&(this.#h=!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"},V={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"},W={value:"read",setValue:"exec",bounds:"read",attributes:"read",actions:"read",perform:"exec",press:"exec",click:"exec",type:"exec",focus:"exec",parent:"read",children:"read"},H={display:{label:"display",methods:q},window:{label:"window",methods:V},ref:{label:"element",methods:W}};class B 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 X(e){return"read"===function(e){let[t,n,...r]=e;if(void 0===t)throw new B("empty","Action 'call' requires a non-empty 'chain'.");if(r.length>0)throw new B("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 B("unknownMethod",`Unknown desktop method "${t.method}". Desktop helpers support: ${G(J)}.`);if(void 0===n)return i;let o=Object.hasOwn(H,t.method)?H[t.method]:void 0;if(void 0===o)throw new B("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 B("unknownMethod",`Unknown ${o.label} method "${n.method}". Supported ${o.label} methods: ${G(o.methods)}.`);return s}(e)}var Y="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="unknown";class ie extends Error{code="abi-mismatch";enginePath;expected;actual;constructor(e,t){let n={abi:Q,protocolVersion:Y};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 oe}from"node:child_process";import{createHash as se}from"node:crypto";import{accessSync as ae,constants as le,existsSync as ce,readFileSync as ue,realpathSync as de}from"node:fs";import{dirname as pe,join as he,sep as fe}from"node:path";import{fileURLToPath as me}from"node:url";var ge="senpi-desktop-engine-checksums.txt",ye=["darwin-arm64","darwin-x64","linux-x64","linux-arm64","win32-x64","win32-arm64"];function ve(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 be(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=>ve(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 we,_e="senpi-desktop-engine",ke="com.apple.quarantine",xe=he(pe(me(import.meta.url)),"..");function Oe(e=process.platform,t=process.arch,n=("linux"===e&&e===process.platform?function(){return we??=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),we}():void 0)){return"linux"===e&&"musl"===n?`${e}-${t}-musl`:`${e}-${t}`}function Ee(){try{return ue("/proc/self/maps","utf8")}catch(e){if(e instanceof Error&&"code"in e)return;throw e}}function $e(e=process.platform){return"win32"===e?`${_e}.exe`:_e}function Se(e={}){let t=Oe(e.platform,e.arch,e.libc),n=$e(e.platform),r=e.packageDir??xe,i=e.execDir??pe(process.execPath),o=e.repoRoot??he(r,"..",".."),s=he("native","prebuilds",t,n),a=e.runtimeDir??process.env.OMO_PACKAGE_DIR;return[...a?[he(a,s)]:[],he(i,s),he(r,s),he(o,"target","release",n)]}function Pe(e={}){let t=e.platform??process.platform,n=Oe(t,e.arch,e.libc),r=Se(e),i=e.execDir??pe(process.execPath),o=e.runtimeDir??process.env.OMO_PACKAGE_DIR?1:0,s=e.isQuarantined??(e=>Ie(e,t)),a=[],l=[];for(let[e,t]of r.entries())if(ce(t)){if(s(t)){if(e!==o||!ze(t,i,n)){l.push(t),a.push(`${t}: blocked because ${ke} 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(Te(t))return{path:t,diagnostic:null};a.push(`${t}: not executable (chmod +x)`)}else a.push(`${t}: missing`);let c=l.length>0?"quarantined":"native-unavailable",u=a.every(e=>e.endsWith(": missing"))&&null===ve(n)?"no-release-asset":void 0;return{path:null,diagnostic:{code:c,host:n,attemptedPaths:r,message:"quarantined"===c?`The ${_e} binary for ${n} is quarantined by macOS Gatekeeper: ${l.join(", ")}.`:"no-release-asset"===u?`No senpi-desktop-engine is built for ${n}; computer use is unavailable on this host.`:`No ${_e} binary is available for ${n}.`,cause:a.join("; "),...void 0===u?{}:{reason:u}}}}function ze(e,t,n){try{let r=`${he(de(t),"native","prebuilds")}${fe}`;if(!de(e).startsWith(r))return!1;let i=ve(n);if(null===i)return!1;let o=be(ue(he(t,"native","prebuilds",ge),"utf8"));if(null!==o.error)return!1;let s=o.checksums.get(i);return void 0!==s&&se("sha256").update(ue(e)).digest("hex")===s.toLowerCase()}catch(e){if(e instanceof Error&&"code"in e)return!1;throw e}}function Ie(e,t=process.platform){if("darwin"!==t)return!1;let n=oe("/usr/bin/xattr",["-p",ke,e],{stdio:["ignore","ignore","ignore"],timeout:2e3});return void 0===n.error&&0===n.status}function Te(e){try{return ae(e,le.X_OK),!0}catch(e){if(e instanceof Error&&"code"in e)return!1;throw e}}import{createHash as Ae,randomUUID as Ce}from"node:crypto";import{accessSync as Re,chmodSync as Ne,constants as je,existsSync as Me,mkdirSync as Ue,mkdtempSync as De,readFileSync as Le,readdirSync as Ze,renameSync as Fe,rmSync as Je,writeFileSync as qe}from"node:fs";import{homedir as Ve}from"node:os";import{join as We}from"node:path";import{spawnSync as He}from"node:child_process";function Be(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 Ke="-musl";function Ge(e,t){let{host:n,version:r}=e,i=ve(n),o=[];if(null===i)return{path:null,attemptedPaths:o};let s=n.slice(0,n.indexOf("-")),a=e.cacheDir??We(Ve(),".omo","cache","senpi-desktop-engine"),l=We(a,r,n);if(Me(l))for(let e of Ze(l)){let n=/^([0-9a-f]{64})-[0-9a-f-]{36}$/.exec(e);if(null===n)continue;let r=We(l,e,i);if(o=[...o,r],t?.(r),Me(r)&&Ae("sha256").update(Le(r)).digest("hex")===n[1]&&!Ie(r,s))try{return Re(r,je.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(Ke)?"musl":"glibc",c="musl"===l?a.slice(0,-5):a,u=Pe({...e.locatorOptions,platform:s,arch:c,libc:l});if(r=u.diagnostic?.attemptedPaths??[],null!==u.path){let r=e.locatorOptions?.runtimeDir??process.env.OMO_PACKAGE_DIR,o=r&&We(r,"native","prebuilds",t,$e(s));if("darwin"===s&&u.path===o&&r&&(e.isReleaseEngine??Be)(u.path)){let e=JSON.parse(Le(We(r,"package.json"),"utf8"));return"object"==typeof e&&null!==e&&"omo"===Reflect.get(e,"name")&&Reflect.get(e,"version")===n?{path:u.path,sha256:Ae("sha256").update(Le(u.path)).digest("hex")}:i("Extracted desktop engine does not belong to the requested omo release")}return{path:u.path}}if("quarantined"===u.diagnostic.code)return i(u.diagnostic.cause);let d=ve(t);if(null===d)return{path:null,diagnostic:{...u.diagnostic,reason:"no-release-asset",message:`No senpi-desktop-engine is built for ${t}; computer use is unavailable on this host.`}};if(!/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$/.test(n))return i(`Invalid omo release version: ${n}`);let p=e.cacheDir??We(Ve(),".omo","cache","senpi-desktop-engine"),h=We(p,n,t),f=Ge(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,We(h,d)];let[y,v]=await Promise.all([m(`${g}/${d}`,{signal:AbortSignal.timeout(3e4)}),m(`${g}/${ge}`,{signal:AbortSignal.timeout(3e4)})]);if(!y.ok)return i(`${d}: HTTP ${y.status}`);if(!v.ok)return i(`${ge}: HTTP ${v.status}`);let b=be(await v.text());if(null!==b.error)return i(b.error);let w=b.checksums.get(d);if(void 0===w)return i(`No SHA-256 checksum for ${d}`);let _=Buffer.from(await y.arrayBuffer()),k=Ae("sha256").update(_).digest("hex");if(k.toLowerCase()!==w.toLowerCase())return i(`SHA-256 mismatch for ${d}`);Ue(h,{recursive:!0});let x=De(We(h,".download-")),O=We(h,`${k}-${Ce()}`);try{let e=We(x,d);qe(e,_),Ne(e,493),Fe(x,O)}finally{Je(x,{recursive:!0,force:!0})}return{path:We(O,d),sha256:k}}catch(e){return i(e instanceof Error?e.message:String(e))}}async function Ye(e,p,h=Xe){let f=await h(e);if(null===f.path)return f;let m=e.isReleaseEngine??Be;return e.host.startsWith("darwin-")&&void 0!==f.sha256&&m(f.path)?(await Promise.resolve().then(()=>{}),function(e,p,h){i(e.directory,{recursive:!0});let f=c(e.directory,"senpi-desktop-engine"),m=new u(c(e.directory,"launch.lock"));try{if(m.exec("PRAGMA busy_timeout = 30000"),m.exec("BEGIN EXCLUSIVE"),!r(f)||d(f)!==e.sha256){let r=c(e.directory,`.engine-${t()}`);try{if(l(r,o(e.path),{flag:"wx",mode:493}),n(r,493),d(r)!==e.sha256)throw Error("Desktop engine source SHA-256 changed");if(!h(r))throw Error("Desktop engine release signature verification failed");s(r,f)}finally{a(r,{force:!0})}}if(d(f)!==e.sha256)throw Error("Stable desktop engine SHA-256 mismatch");return l(c(e.directory,"release.json"),JSON.stringify({version:e.version,sha256:e.sha256})),{path:f,value:p(f)}}finally{m.close()}}({path:f.path,sha256:f.sha256,version:e.version,directory:We(e.installDir??We(Ve(),".omo","engines","senpi-desktop-engine"),e.host)},t=>Ie(t)?{path:null,diagnostic:{code:"quarantined",host:e.host,attemptedPaths:[t],message:"The stable desktop engine is quarantined by macOS Gatekeeper.",cause:`${t}: blocked because com.apple.quarantine is present`}}:{path:t,value:p(t)},m).value):{path:f.path,value:p(f.path)}}class Qe extends Error{reason;constructor(e,t){super(t),this.name="ComputerRunError",this.reason=e}}class et{#v=[];text(e){this.#v.push({type:"text",text:e})}image(e,t){this.#v.push({type:"image",data:e,mimeType:t})}finish(){return[...this.#v]}}function tt(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 Qe("readOnly",`read-only run: '${n}' requires read_only: false`);e.signal.throwIfAborted()}(e.context,t,n),r(e))))}import{randomUUID as nt}from"node:crypto";var rt=new Set(["global","host-relay","none"]),it=["unknown","hostOnly","testOnly"],ot={suspended:"boolean",globalLive:"boolean",hostRelayLive:"boolean",heartbeatFresh:"boolean",stopPath:"string",reason:"string?"},st={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"},at={action:"string",target:"string",delivery:"string",frameId:"string?",code:"string?",durationMs:"number",focusRestored:"boolean?",textLength:"number?",textDelivered:"number?",textSha256:"string?"};function lt(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ct(e,t){return!!lt(e)&&Object.entries(t).every(([t,n])=>{let r=e[t];return n.endsWith("?")?null==r||typeof r===n.slice(0,-1):typeof r===n})}function ut(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function dt(e){return ct(e,ot)&&function(e,t){return"string"==typeof e&&t.has(e)}(e.stopPath,rt)}function pt(e){return ct(e,st)&&ut(e.deliveryModes)&&(void 0===e.cursorOverlay||"boolean"==typeof e.cursorOverlay)}function ht(e){if(!function(e){return ct(e,at)&&(void 0===e.keys||null===e.keys||ut(e.keys))}(e))return;let t=ee.find(t=>t===e.action)??re,{code:n}=e;return null==n?{...e,action:t,code:n}:{...e,action:t,code:ne.find(e=>e===n)??re}}function ft(e){if(!lt(e))return null;let t=ne.find(t=>t===e.code);if(void 0!==t){let n=function(e){if(!lt(e)||"screen_recording"!==e.permission&&"accessibility"!==e.permission||"string"!=typeof e.settingsUrl||"string"!=typeof e.app||"boolean"!=typeof e.relaunchRequired)return;return{permission:e.permission,settingsUrl:e.settingsUrl,app:e.app,relaunchRequired:e.relaunchRequired}}(e.permission);return{code:t,hint:"string"==typeof e.hint?e.hint:null,...void 0===n?{}:{permission:n}}}let n=it.find(t=>t===e.reason);return void 0===n?null:{reason:n}}import{spawn as mt}from"node:child_process";import{createInterface as gt}from"node:readline";class yt extends Error{diagnostic;constructor(e){super(`${e.message} ${e.cause}`),this.name="DesktopEngineUnavailableError",this.diagnostic=e}}function vt(e){return()=>bt(e??function(){let e=Pe();if(null===e.path)throw new yt(e.diagnostic);return e.path}())}function bt(e){return mt(e,["--stdio"],{stdio:"pipe",windowsHide:!0})}class wt{path;exited;#b;#w="";#_="";#k=!0;#x=new F;constructor(e,t){this.#b=e,this.path=e.spawnfile,e.stderr.setEncoding("utf8"),e.stderr.on("data",e=>{this.#x.push(e),this.#w=(this.#w+e).slice(-4096)}),e.stdin.on("error",e=>this.#O(`stdin: ${e.message}`)),e.on("error",e=>{this.#x.disable(),this.#O(`spawn: ${e.message}`)}),gt({input:e.stdout}).on("line",t.onLine),this.exited=new Promise(n=>{e.on("close",(e,r)=>{this.#k=!1;let i=this.#E(e,r);t.onExit(i,this.#x.finish(e,r,i)),n()})})}get alive(){return this.#k}finishStartup(){this.#x.disable()}write(e){this.#k&&!this.#b.stdin.writableEnded&&this.#b.stdin.write(`${JSON.stringify({jsonrpc:"2.0",...e})}\n`)}end(){this.#b.stdin.end()}kill(){this.#x.disable(),this.#k&&(this.#k=!1,this.#b.kill())}#O(e){this.#_=""===this.#_?e:`${this.#_}; ${e}`}#E(e,t){return`desktop engine exited (code ${e??"null"}, signal ${t??"null"})${""===this.#_?"":`; ${this.#_}`}; stderr: ${this.#w.trim()||"<empty>"}`}}class _t extends Error{code;engineRestarted;constructor(e,t,n=!1){super(t),this.name="DesktopServiceError",this.code=e,this.engineRestarted=n}}class kt extends Error{method;rpcCode;data;constructor(e,t){super(t.message),this.name="DesktopEngineRpcError",this.method=e,this.rpcCode=t.code,this.data=ft(t.data)}}class xt{#$;#S;#P=new Map;#z=1;#E;constructor(e,t){this.#S=t,this.#$=new wt(e,{onLine:e=>this.#I(e),onExit:(e,t)=>this.#T(e,t)})}get enginePath(){return this.#$.path}get alive(){return void 0===this.#E&&this.#$.alive}get exited(){return this.#$.exited}request(e,t,n={}){if(!this.alive)return Promise.reject(new _t("Closed",this.#E??"desktop engine was killed"));if(n.signal?.aborted)return Promise.reject(new _t("Cancelled",`${e} was cancelled before it was sent`));let r=this.#z++,{promise:i,resolve:o,reject:s}=Promise.withResolvers(),a={method:e,resolve:o,reject:s,release:()=>{},cancelled:void 0};this.#P.set(r,a);let{signal:l,timeoutMs:c}=n,u=()=>this.#A(r,new _t("Cancelled",`${e} was cancelled`)),d=void 0===c?void 0:setTimeout(()=>this.#A(r,new _t("Timeout",`${e} timed out after ${c} ms`)),c);return l?.addEventListener("abort",u,{once:!0}),a.release=()=>{clearTimeout(d),l?.removeEventListener("abort",u)},this.#$.write({id:r,method:e,params:t}),i}cancelHolds(){for(let[e,t]of this.#P)Ot(t.method)&&this.#A(e,new _t("Cancelled","desktop session is closing"))}end(){this.#$.end()}kill(){this.#$.kill()}#A(e,t){let n=this.#P.get(e);if(void 0===n||void 0!==n.cancelled)return;n.release(),n.cancelled=t,this.#$.finishStartup();let r=setTimeout(()=>{this.#C(e),n.reject(new _t(t.code,`${t.message}; desktop engine restarted; captures and ax refs were reset`,!0)),this.#$.kill()},Ot(n.method)?2500:750);n.release=()=>clearTimeout(r),this.#$.write({method:"$/cancel",params:{id:e}})}#C(e){let t=this.#P.get(e);return this.#P.delete(e),t?.release(),t}#I(e){let t=function(e){try{return JSON.parse(e)}catch(e){if(e instanceof SyntaxError)return;throw e}}(e);if(!lt(t))return this.#$.kill(),void(this.#E=`desktop engine wrote a non-protocol line ${JSON.stringify(e.slice(0,200))}`);if("string"==typeof t.method&&void 0===t.id)return void this.#S.onNotification(t.method,t.params);let n="number"==typeof t.id?this.#C(t.id):void 0;if(void 0===n)return;if("engine.hello"===n.method&&this.#$.finishStartup(),void 0!==n.cancelled){let e=function(e,t){if(!Ot(e)||!lt(t)||"number"!=typeof t.code||"string"!=typeof t.message)return;if("Cancelled"===(lt(t.data)?t.data.code:void 0)&&!t.message.includes(Et))return;return new kt(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;lt(r)&&"number"==typeof r.code&&"string"==typeof r.message?n.reject(new kt(n.method,{code:r.code,message:r.message,data:r.data})):n.reject(new _t("Internal",`desktop engine sent a malformed reply to ${n.method}`))}#T(e,t){let n=void 0===this.#E?t:void 0;this.#E??=e;let r=n??new _t("Closed",this.#E);for(let e of[...this.#P.keys()]){let t=this.#C(e);void 0!==t?.cancelled&&(t.cancelled.cause=r),t?.reject(t.cancelled??r)}this.#S.onExit()}}var Ot=e=>"holdKeys"===e||"holdMouse"===e;var Et="input release also failed";var $t={id:"string",name:"string",x:"number",y:"number",width:"number",height:"number",scale:"number",pixelX:"number",pixelY:"number",pixelWidth:"number",pixelHeight:"number",isPrimary:"boolean"},St={id:"string",title:"string",app:"string",pid:"number?",x:"number",y:"number",width:"number",height:"number",focused:"boolean",elevated:"boolean?"},Pt={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"},zt={title:"string",enabled:"boolean",checked:"boolean",hasSubmenu:"boolean",shortcut:"string?"},It={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?"},Tt=e=>ct(e,$t),At=e=>ct(e,St),Ct=e=>ct(e,Pt)&&(void 0===e.actions||null===e.actions||ut(e.actions)),Rt=e=>ct(e,zt)&&ut(e.path),Nt=e=>ct(e,It)&&(null==e.region||ct(e.region,{x:"number",y:"number",width:"number",height:"number"})),jt=e=>Nt(e)&&"number"==typeof e.coordinateWidth&&"number"==typeof e.coordinateHeight&&null!=e.region,Mt=e=>Nt(e)&&"number"==typeof e.coordinateWidth&&"number"==typeof e.coordinateHeight&&ct(e,{ax:"string",nodeCount:"number",truncated:"boolean"}),Ut=e=>"object"==typeof e&&null!==e&&("inserted"===e.method||"keys"===e.method),Dt=e=>lt(e)&&"string"==typeof e.text,Lt=e=>Array.isArray(e)&&e.every(e=>ut(e)&&2===e.length);function Zt(e){return t=>Array.isArray(t)&&t.every(e)}function Ft(e){return t=>null===t||e(t)}function Jt(e,t,n){if(!n(t))throw new _t("Internal",`desktop engine sent a malformed ${e} result`);return t}async function qt(e,t,n){try{await e.call(t,n)}catch(e){if(e instanceof kt&&-32601===e.rpcCode)throw new Qe("unavailable",`${t} is unavailable in this desktop engine; update the engine for bounded holds`);throw e}}async function Vt(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=Jt(s,await e.call(s,a),void 0===r?Nt:jt);return Wt(e,l,n)}function Wt(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:c,scale:u,frameId:d}=t,p=t.coordinateWidth??s,h=t.coordinateHeight??a;return{target:t.target,frameId:d,width:s,height:a,sourceWidth:l,sourceHeight:c,coordinateWidth:p,coordinateHeight:h,...null==t.region?{}:{region:t.region},scale:u,...void 0===o?{}:{path:o}}}function Ht(e){if(!Number.isFinite(e)||e<0||e>100)throw new Qe("assertion","hold duration must be finite seconds in 0..=100")}function Bt(e={}){let{button:t,count:n,modifiers:r,delivery:i}=e;return{button:t,count:n,modifiers:r,deliveryMode:i}}function Kt(e){return"string"!=typeof e?e:e.split("+").map(e=>e.trim()).filter(e=>e.length>0)}function Gt(e,t,n,r){return e(t,async({call:e})=>{await e(n,r)})}class Xt{#R;#N;constructor(e,t,n){this.#R=t,this.#N=tt(e,n)}screenshot(e){return this.#N("screenshot",t=>Vt(t,this.#R,e))}zoom(e,t){return this.#N("zoom",n=>Vt(n,this.#R,t,e))}click(e,t,n){return Gt(this.#N,"click","click",{target:this.#R,x:e,y:t,opts:Bt(n)})}doubleClick(e,t,n){let r=Bt({...n,count:2});return Gt(this.#N,"doubleClick","click",{target:this.#R,x:e,y:t,opts:r})}move(e,t){return Gt(this.#N,"move","moveMouse",{target:this.#R,x:e,y:t})}drag(e,t){let n=e.map(([e,t])=>({x:e,y:t}));return Gt(this.#N,"drag","drag",{target:this.#R,path:n,opts:Bt(t)})}scroll(e,t,n={}){let{dx:r=0,dy:i=0}=n,o={target:this.#R,x:e,y:t,dx:r,dy:i,opts:Bt(n)};return Gt(this.#N,"scroll","scroll",o)}type(e,t){return Gt(this.#N,"type","typeText",{target:this.#R,text:e,opts:Bt(t)})}press(e,t){let n={target:this.#R,keys:Kt(e),opts:Bt(t)};return Gt(this.#N,"press","keyChord",n)}holdKeys(e,t){return this.#N("holdKeys",async n=>{if(Ht(t?.duration),!Array.isArray(e)||0===e.length)throw new Qe("assertion","held keys must not be empty");await qt(n,"holdKeys",{target:this.#R,keys:e,duration:t.duration,opts:Bt(t)})})}holdMouse(e,t,n){return this.#N("holdMouse",async r=>{Ht(n?.duration),await qt(r,"holdMouse",{target:this.#R,x:e,y:t,duration:n.duration,button:n.button,keys:n.keys,frameId:n.frameId,opts:Bt(n)})})}}class Yt extends Xt{id;app;title;pid;bounds;focused;#N;constructor(e,t){super(e,t.id,V),this.#N=tt(e,V),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 Gt(this.#N,"raise","raiseWindow",{windowId:this.id})}menu={items:e=>this.#N("menu.items",async({call:t})=>Jt("menus.items",await t("menus.items",{windowId:this.id,path:[...e??[]]}),Zt(Rt))),select:(e,t)=>Gt(this.#N,"menu.select","menus.select",{windowId:this.id,path:[...e],...void 0===t?.delivery?{}:{deliveryMode:t.delivery}})};ax(e){return this.#N("ax",async({call:t})=>Jt("ax.snapshot",await t("ax.snapshot",{target:this.id,opts:e}),Dt).text)}observe(e){return this.#N("observe",t=>async function(e,t,n={}){let r,{snapshot:i,output:o}=e.context,s={maxWidth:i.captureMaxWidth,maxHeight:i.captureMaxHeight,maxBytes:i.captureMaxBytes},{all:a,maxDepth:l,maxNodes:c}=n;try{r=await e.call("observe",{target:t,caps:s,ax:{all:a,maxDepth:l,maxNodes:c}})}catch(e){if(e instanceof kt&&-32601===e.rpcCode)throw new Qe("unavailable","observe is unavailable in this desktop engine; update the engine to use atomic observation");throw e}let u=Jt("observe",r,Mt),d=Wt(e,u,n);return!0!==n.silent&&o.text(u.ax),{...d,ax:u.ax,nodeCount:u.nodeCount,truncated:u.truncated}}(t,this.id,e))}find(e){return this.#N("find",async t=>Jt("ax.query",await t.call("ax.query",{target:this.id,query:e}),Zt(Ct)).map(e=>new en(t,e)))}ref(e){return this.#N("ref",t=>Qt(t,e))}}async function Qt(e,t){return new en(e,Jt("ax.node",await e.call("ax.node",{ref:t}),Ct))}class en{ref;role;nativeRole;title;description;enabled;focused;childCount;#N;constructor(e,t){this.#N=tt(e,W),this.ref=t.ref,this.role=t.role,this.nativeRole=t.nativeRole,this.title=t.title??void 0,this.description=t.description??void 0,this.enabled=t.enabled,this.focused=t.focused,this.childCount=t.childCount}#j(e,t,n){return this.#N(e,async({call:e})=>{await e(t,{ref:this.ref,...n})})}#M(e,t){return this.#N(e,async({call:e})=>t(Jt("ax.node",await e("ax.node",{ref:this.ref}),Ct)))}value(){return this.#M("value",e=>e.value??void 0)}setValue(e){return this.#j("setValue","ax.setValue",{value:e})}bounds(){return this.#M("bounds",({x:e,y:t,width:n,height:r})=>null==e||null==t||null==n||null==r?null:{x:e,y:t,width:n,height:r})}attributes(){return this.#N("attributes",async({call:e})=>Object.fromEntries(Jt("ax.attributes",await e("ax.attributes",{ref:this.ref}),Lt)))}actions(){return this.#M("actions",e=>e.actions??[])}perform(e){return this.#j("perform","ax.perform",{action:e})}press(){return this.#j("press","ax.perform",{action:"press"})}click(e){return this.#j("click","ax.click",{opts:Bt(e)})}type(e,t){return this.#N("type",async({call:n})=>Jt("ax.typeText",await n("ax.typeText",{ref:this.ref,text:e,opts:Bt(t)}),Ut))}focus(){return this.#j("focus","ax.focus",{})}parent(){return this.#N("parent",async e=>{let t=Jt("ax.parent",await e.call("ax.parent",{ref:this.ref}),Ft(Ct));return null===t?null:new en(e,t)})}children(){return this.#N("children",async e=>Jt("ax.children",await e.call("ax.children",{ref:this.ref}),Zt(Ct)).map(t=>new en(e,t)))}}function tn(e,t={}){let n=t.app?.toLocaleLowerCase(),r=t.title?.toLocaleLowerCase();return(!n||e.app.toLocaleLowerCase().includes(n))&&(!r||e.title.toLocaleLowerCase().includes(r))}function nn(e){let t=tt(e,J),n=async({call:e})=>Jt("windows",await e("windows",{}),Zt(At)),r=async(t,n)=>{let r=Jt(t,await e.call(t,n),Ft(Ct));return null===r?null:new en(e,r)},i=new Xt(e,"desktop",J);return{capabilities:()=>t("capabilities",async({call:e})=>{let t=Jt("capabilities",await e("capabilities",{}),pt);return{...t,cursorOverlay:t.cursorOverlay??!1}}),displays:()=>t("displays",async({call:e})=>Jt("displays",await e("displays",{}),Zt(Tt))),display:n=>t("display",async()=>{if("string"!=typeof n||0===n.length)throw new Qe("assertion","display requires an id, 'active', or 'all'");return Object.assign(new Xt(e,`display:${n}`,q),{id:n})}),windows:e=>t("windows",async t=>(await n(t)).filter(t=>tn(t,e))),window:r=>t("window",async t=>{let i=(await n(t)).filter(e=>"string"==typeof r?e.id===r:tn(e,r)),[o,...s]=i;if(void 0===o)throw new Qe("window",`no window matches ${JSON.stringify(r)}`);if(s.length>0){let e=i.map(e=>`${e.id} ${e.app} ${JSON.stringify(e.title)}`);throw new Qe("window",`multiple windows match ${JSON.stringify(r)}:\n${e.join("\n")}`)}return new Yt(e,o)}),focusedWindow:()=>t("focusedWindow",async t=>{let r=(await n(t)).find(e=>e.focused);return void 0===r?null:new Yt(e,r)}),screenshot:i.screenshot.bind(i),zoom:i.zoom.bind(i),click:i.click.bind(i),doubleClick:i.doubleClick.bind(i),move:i.move.bind(i),drag:i.drag.bind(i),scroll:i.scroll.bind(i),type:i.type.bind(i),press:i.press.bind(i),holdKeys:i.holdKeys.bind(i),holdMouse:i.holdMouse.bind(i),elementAt:(e,n)=>t("elementAt",()=>r("ax.elementAt",{target:"desktop",x:e,y:n})),focusedElement:()=>t("focusedElement",()=>r("ax.focused",{})),ref:e=>t("ref",t=>Qt(t,e)),clipboard:{read:()=>t("clipboard.read",async({call:e})=>Jt("clipboard.read",await e("clipboard.read",{}),Dt).text),write:e=>t("clipboard.write",async({call:t})=>{await t("clipboard.write",{text:e})})},control:an(e,t)}}var rn=5e3,on=3e3;function sn(e){return lt(e)&&"boolean"==typeof e.active}function an(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 Qe("assertion","control.acquire requires a non-empty reason");let o=Jt("control.state",await r("control.state",{}),sn);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()-rn);if(a<on)throw new Qe("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}:Jt("control.grant",await r("control.grant",{reason:i,confirmationId:nt()}),sn)}),release:()=>t("control.release",async({call:e})=>{await e("control.revoke",{})}),state:()=>t("control.state",async({call:e})=>Jt("control.state",await e("control.state",{}),sn))}}import{randomUUID as ln}from"node:crypto";import{format as cn}from"node:util";import un from"node:vm";function dn(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 pn(e,t){return async(n,r={})=>{if("number"==typeof n)return dn(n,e);if("function"!=typeof n)throw new Qe("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 Qe("wait",`wait(predicate) timed out after ${n} ms; the predicate never returned truthy`);await dn(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 hn="computer-run.js";function fn(e){return lt(e)&&"ERR_SCRIPT_EXECUTION_TIMEOUT"===e.code}function mn(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 gn(e,t){let{code:n,snapshot:r,timeoutMs:i}=e,o=ln(),s=new AbortController,{signal:a}=s,l=Date.now()+i,c=e=>s.abort(e),u=()=>new Qe("timeout",`computer run timed out after ${i} ms`),d=setTimeout(()=>c(u()),i),p=()=>c(new Qe("aborted","computer run was aborted"));e.signal?.addEventListener("abort",p,{once:!0}),e.signal?.aborted&&p();let h=[],f=t.service.onAudit(e=>h.push(function(e,t,n){let{action:r,target:i,delivery:o,durationMs:s,focusRestored:a,textLength:l,textSha256:c,keys:u}=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==c?{}:{textSha256:c},...null==u?{}:{keys:u}}}(e,r.sessionId,o))),m={signal:a,readOnly:r.readOnly,snapshot:r,output:new et,screenshots:[],deadline:l},g=new un.Script(""),y=()=>{if(!a.aborted)try{g.runInContext(_,{timeout:Math.max(1,l-Date.now())})}catch(e){c(fn(e)?u():e)}},v=e=>{let t=()=>setImmediate(y);return e.then(t,t),e},b=pn(a,i),w=(...e)=>m.output.text(cn(...e)),_=un.createContext({desktop:nn({context:m,call:(e,n)=>t.service.call(e,n,{signal:a}),resume:v,...void 0===t.confirmControl?{}:{confirmControl:t.confirmControl}}),wait:(e,t)=>v(b(e,t)),assert:(e,t)=>{if(!e)throw new Qe("assertion",t??"Assertion failed")},tool:new Proxy({},{get:(e,n)=>e=>(a.throwIfAborted(),v(t.executeTool(String(n),e,{signal:a})))}),console:{log:w,info:w,warn:w,error:w,debug:w}},{name:hn,microtaskMode:"afterEvaluate"});try{a.throwIfAborted();let e=new un.Script(`((run) => (run.catch(() => undefined), run))((async () => {\n${n}\n})())`,{filename:hn,lineOffset:-1}).runInContext(_,{timeout:i}),t=await new Promise((t,n)=>{a.addEventListener("abort",()=>n(a.reason),{once:!0}),a.throwIfAborted(),Promise.resolve(e).then(t,n),setImmediate(y)});return{displays:m.output.finish(),returnValue:mn(t),screenshots:[...m.screenshots],audit:[...h]}}catch(e){let n=fn(e)?u():e;throw t.service.revokeControl().catch(e=>t.service.reportError(e)),n}finally{clearTimeout(d),e.signal?.removeEventListener("abort",p),f(),a.aborted||s.abort(new Qe("ended","computer run has ended"))}}class yn extends Error{method;constructor(e,t){super(`desktop engine notification ${JSON.stringify(e)} ${t}`),this.name="DesktopNotificationError",this.method=e}}function vn(e,t){return e.add(t),()=>{e.delete(t)}}class bn{#U=new Set;#D=new Set;#L=new Set;onAudit(e){return vn(this.#U,e)}onStopPathChange(e){return vn(this.#D,e)}onError(e){return vn(this.#L,e)}emitError(e){for(let t of this.#L)t(e)}dispatch(e,t){let n=te.find(t=>t===e);void 0!==n?this.#Z(n,t):this.emitError(new yn(e,"is not part of the engine protocol"))}#Z(e,t){switch(e){case"audit":{let n=ht(t);if(void 0!==n)for(let e of this.#U)e(n);else this.emitError(new yn(e,"is malformed"));return}case"stopPath.changed":if(dt(t))for(let e of this.#D)e(t);else this.emitError(new yn(e,"is malformed"));return;case"engine.log":case"epoch.changed":return;default:!function(e){throw Error(`unhandled engine notification ${JSON.stringify(e)}`)}(e)}}}class wn{#F=0;#J=0;#q=0;#V=!1;get possiblyLive(){return this.#J>this.#q}get automaticLive(){return this.possiblyLive&&this.#V}async grant(e,t,n=!1){if(t)return e();this.#F+=1;let r=this.#F,i={possiblyLive:this.#J,automatic:this.#V};this.#J=r,this.#V=n;try{return await e()}catch(e){throw e instanceof kt&&this.#J===r&&(this.#J=i.possiblyLive,this.#V=i.automatic),e}}async revoke(e){let t=this.#F,n=await e();return this.#q=Math.max(this.#q,t),n}}function _n(e,t,n){return new Promise((r,i)=>{let o=setTimeout(()=>i(new _t("Timeout",n)),t);e.then(e=>{clearTimeout(o),r(e)},e=>{clearTimeout(o),i(e)})})}import{randomUUID as kn}from"node:crypto";var xn=new Set(["click","moveMouse","drag","scroll","typeText","keyChord","holdKeys","holdMouse"]);function On(e){return e instanceof kt&&null!==e.data&&"code"in e.data&&"ControlRequired"===e.data.code}function En(e,t){if(!0===t.signal?.aborted)throw new _t("Cancelled",`${e} was cancelled`)}class $n{#W;#H;constructor(e,t){this.#W=e,this.#H=t}async fence(e){this.#W.automaticLive&&!this.#H()&&await this.#B(e)}async send(e,t,n,r){let i=!1;for(;;){En(t,r);let o=this.#H();if(o||!this.#W.automaticLive)if(!o||this.#W.possiblyLive){try{return await e.rpc.request(t,n,r)}catch(e){if(!o||i||!On(e)||!0===r.signal?.aborted)throw e}i=!0,await this.#K(e,r)}else await this.#K(e,r);else await this.#B(e)}}#B(e){return this.#W.revoke(()=>e.rpc.request("control.revoke",{},{timeoutMs:2e3}))}async#K(e,t){let n={reason:"full access: the session's permission preset consents to desktop input",confirmationId:kn()},r=t.signal;await this.#W.grant(()=>e.rpc.request("control.grant",n,void 0===r?{}:{signal:r}),!1,!0)}}class Sn{#G;#X=new bn;#Y=Promise.resolve();#Q;#ee;#W=new wn;#te;#ne=!1;constructor(e={}){this.#G=e.createChild??vt(),this.#te=new $n(this.#W,e.fullAccess??(()=>!1)),this.#X.onStopPathChange(e=>{e.suspended&&(this.#ne=!0)})}onAudit(e){return this.#X.onAudit(e)}onStopPathChange(e){return this.#X.onStopPathChange(e)}onError(e){return this.#X.onError(e)}open(e){return this.#re(async()=>{let t={...e,showCursor:e.showCursor??!0};this.#ee={params:t,chord:this.#ee?.chord};let n=this.#Q;return!0===n?.rpc.alive?this.#ie(n,t):(void 0!==n&&this.#oe(n),(await this.#se(this.#ee)).capabilities)})}ensureStopPath(e){return this.#re(async()=>{let t=await this.#ae();if(t.armedChord===e)return this.#D(t,"stopPath.status",{});let n=await this.#D(t,"stopPath.start",{chord:e});return t.armedChord=e,void 0!==this.#ee&&(this.#ee.chord=e),n})}async call(e,t,n={}){let r=await this.#le();await this.#te.fence(r);let i=()=>r.rpc.request(e,t,n);return"control.grant"===e?this.#W.grant(i,!0===n.signal?.aborted):"control.revoke"===e?this.#W.revoke(i):function(e,t){if(!xn.has(e)||"object"!=typeof t||null===t)return!1;let n=Reflect.get(t,"target");return"string"==typeof n&&function(e){return"desktop"===e.replace(/[A-Z]/g,e=>e.toLowerCase())||e.startsWith("display:")}(n)}(e,t)?this.#te.send(r,e,t,n):i()}reportError(e){this.#X.emitError(e instanceof Error?e:Error(String(e)))}revokeControl(){let e=this.#Q;return void 0!==e&&e.rpc.alive&&this.#W.possiblyLive?this.#W.revoke(()=>e.rpc.request("control.revoke",{},{timeoutMs:2e3})).then(()=>{},e=>{if(!(e instanceof _t||e instanceof kt))throw e;this.#X.emitError(e)}):Promise.resolve()}async capabilities(){let e=await this.call("capabilities",{},{timeoutMs:1e4});if(!pt(e))throw Pn("capabilities");return{...e,cursorOverlay:e.cursorOverlay??!1}}async stopPathStatus(){return this.#D(await this.#le(),"stopPath.status",{})}async stop(){return this.#D(await this.#le(),"stopPath.stop",{source:"host-relay"})}async resume(){let e=await this.#le(),t=await this.#D(e,"stopPath.resume",{token:e.resumeToken});return t.suspended||(this.#ne=!1),t}close(){return this.#re(async()=>{this.#ee=void 0;let e=this.#Q;if(void 0===e)return;if(this.#oe(e),!e.rpc.alive)return;try{await _n((async()=>{e.rpc.cancelHolds(),await e.rpc.request("session.close",{}),e.rpc.end(),await e.rpc.exited})(),3e3,"Timed out closing desktop engine")}finally{e.rpc.kill()}})}#re(e){let t=this.#Y.then(e);return this.#Y=t.then(()=>{},()=>{}),t}#le(){let e=this.#Q;return!0===e?.rpc.alive?Promise.resolve(e):this.#re(()=>this.#ae())}async#ae(){let e=this.#Q;if(!0===e?.rpc.alive)return e;if(void 0!==e&&this.#oe(e),void 0===this.#ee)throw new _t("Closed","desktop session is not open");return(await this.#se(this.#ee)).connection}async#se(e){let t=new xt(await this.#G(),{onNotification:(e,t)=>this.#X.dispatch(e,t),onExit:()=>{this.#Q?.rpc===t&&this.#oe(this.#Q)}}),n={rpc:t,resumeToken:"",armedChord:void 0,heartbeat:void 0};try{let t=await _n(this.#ce(n,e),1e4,"Timed out starting desktop engine");return this.#Q=n,n.heartbeat=setInterval(()=>this.#ue(n),500),{connection:n,capabilities:t}}catch(e){throw t.kill(),e}}async#ce(e,t){let n=function(e){if(lt(e)&&"string"==typeof e.abi&&"string"==typeof e.protocolVersion)return{abi:e.abi,protocolVersion:e.protocolVersion}}(await e.rpc.request("engine.hello",{}));if(void 0===n)throw Pn("engine.hello");if(n.abi!==Q||n.protocolVersion!==Y)throw new ie(e.rpc.enginePath,n);let r=await this.#ie(e,t.params);return void 0!==t.chord&&(await this.#D(e,"stopPath.start",{chord:t.chord}),e.armedChord=t.chord),this.#ne&&await this.#D(e,"stopPath.stop",{source:"host-relay"}),r}async#ie(e,t){let n=function(e){if(lt(e)&&"string"==typeof e.resumeToken&&pt(e.capabilities))return{capabilities:{...e.capabilities,cursorOverlay:e.capabilities.cursorOverlay??!1},resumeToken:e.resumeToken}}(await e.rpc.request("session.open",t,{timeoutMs:1e4}));if(void 0===n)throw Pn("session.open");return e.resumeToken=n.resumeToken,n.capabilities}async#D(e,t,n){let r=await e.rpc.request(t,n);if(!dt(r))throw Pn(t);return r.suspended&&(this.#ne=!0),r}#ue(e){e.rpc.request("stopPath.heartbeat",{}).catch(e=>{if(!(e instanceof _t&&"Closed"===e.code)){if(!(e instanceof _t||e instanceof kt))throw e;this.#X.emitError(e)}})}#oe(e){clearInterval(e.heartbeat),this.#Q===e&&(this.#Q=void 0)}}function Pn(e){return new _t("Internal",`desktop engine sent a malformed ${e} result`)}var zn={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"},In={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",Cancelled:"COMPUTER_CANCELLED",Timeout:"COMPUTER_CANCELLED",timeout:"COMPUTER_CANCELLED",aborted:"COMPUTER_CANCELLED"};function Tn(e){return{code:"COMPUTER_LAUNCH_CONTEXT_REQUIRED",message:e.message,reason:e.reason}}function An(e,t,n,r){let i=e.startsWith("COMPUTER_")?e:In[e]??"COMPUTER_ERROR",o=function(e,t){let n=`Stop and wait for the user (stop chord: ${t}); only the user resumes, with /computer resume.`;switch(e){case"COMPUTER_COORD_INVALID":return"Capture a fresh screenshot and use coordinates within its frame.";case"COMPUTER_DISPLAY_STALE":return"Capture a fresh screenshot before acting; the display changed since the last screenshot.";case"COMPUTER_SUSPENDED":case"COMPUTER_SUPERVISOR_NOT_LIVE":case"COMPUTER_CANCELLED":return n;case"COMPUTER_PERMISSION_REQUIRED":return"Do not retry until the user says the grant is done and the app was relaunched.";case"COMPUTER_PERMISSION_DENIED":return"A permission rule denied this action; do not retry it.";case"COMPUTER_CURSOR_RESTORE_FAILED":case"COMPUTER_FOCUS_RESTORE_FAILED":return"Input may have completed, but the previous state was not restored. Ask the user to inspect the desktop before retrying.";case"COMPUTER_BACKGROUND_UNAVAILABLE":return"This window cannot take background input; use the computer tool's accessibility actions instead.";case"COMPUTER_CONTROL_REQUIRED":return"Call desktop.control.acquire({ reason }) in computer run code (computer.control.acquire in an eval kernel) and let the human confirm before acting in the foreground; do not retry this action until that returns { active: true }.";case"COMPUTER_INPUT_BUSY":return"Another session holds the foreground control grant; it is never stolen, so continue in the background or retry once that session releases it.";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.";default:return}}(i,n);return{code:i,message:`${i}: ${t}${void 0===o?"":` ${o}`}`,...r??{}}}import{Type as Cn}from"typebox";var Rn=Cn.Object({method:Cn.String({description:"desktop helper name, e.g. screenshot, window, click, clipboard.read"}),args:Cn.Optional(Cn.Array(Cn.Unknown(),{description:"positional helper arguments"}))},{additionalProperties:!1}),Nn=Cn.Number({minimum:1,maximum:600,description:"run: budget in seconds (default 60)"}),jn=[Cn.Object({action:Cn.Literal("call"),chain:Cn.Array(Rn,{description:"one desktop helper call, optionally followed by one call on the window/element it returns"})},{additionalProperties:!1}),Cn.Object({action:Cn.Literal("run"),code:Cn.String({description:"JavaScript async function body; `desktop`, `wait`, `assert`, `tool` in scope; `return` sets the value"}),read_only:Cn.Optional(Cn.Boolean({description:"true = inspection only: screenshots and AX reads, input/mutation blocked"})),timeout:Cn.Optional(Nn)},{additionalProperties:!1}),Cn.Object({action:Cn.Literal("capabilities")},{additionalProperties:!1}),Cn.Object({action:Cn.Literal("close")},{additionalProperties:!1})],Mn=Cn.Union([...jn]),Un=Cn.Object({action:Cn.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:Cn.Optional(Cn.Array(Rn,{description:"call (required): one desktop helper call, optionally followed by one call on the window/element it returns"})),code:Cn.Optional(Cn.String({description:"run (required): JavaScript async function body; `desktop`, `wait`, `assert`, `tool` in scope; `return` sets the value"})),read_only:Cn.Optional(Cn.Boolean({description:"run: true = inspection only: screenshots and AX reads, input/mutation blocked"})),timeout:Cn.Optional(Nn)},{additionalProperties:!1});import{Check as Dn}from"typebox/value";import{readFileSync as Ln}from"node:fs";import{dirname as Zn,join as Fn}from"node:path";import{fileURLToPath as Jn}from"node:url";var qn,Vn=["COMPUTER_PRELUDE_JAVASCRIPT","COMPUTER_PRELUDE_PYTHON","COMPUTER_DECLARATIONS","COMPUTER_DOCUMENTATION","COMPUTER_SAFETY"],Wn=Fn(Zn(Jn(import.meta.url)),"assets.generated.json");function Hn(){if(void 0===qn){let e=JSON.parse(Ln(Wn,"utf8"));qn=function(e){let t=e&&"object"==typeof e?e:void 0,n=Vn.filter(e=>"string"!=typeof t?.[e]);if(n.length>0)throw Error(`senpi-desktop-prelude asset JSON is malformed at ${Wn}: missing ${n.join(", ")}`);return e}(e)}return qn}var Bn={get javascript(){return Hn().COMPUTER_PRELUDE_JAVASCRIPT},get python(){return Hn().COMPUTER_PRELUDE_PYTHON},get declarations(){return Hn().COMPUTER_DECLARATIONS},get documentation(){return Hn().COMPUTER_DOCUMENTATION},get safety(){return Hn().COMPUTER_SAFETY},exports:["computer"],methodAllowlist:["actions","attributes","ax","bounds","capabilities","children","click","clipboard.read","clipboard.write","control.acquire","control.release","control.state","display","displays","doubleClick","drag","elementAt","find","focus","focusedElement","focusedWindow","holdKeys","holdMouse","move","observe","menu.items","menu.select","parent","perform","press","raise","ref","screenshot","scroll","setValue","type","value","window","windows","zoom"]},Kn={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:Bn.safety.split("\n").filter(e=>e.startsWith("- ")).map(e=>e.slice(2)),kernelPrelude:Bn,parameters:Un,executionMode:"sequential"},Gn=_(jn);function Xn(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 Yn(e){return"string"==typeof e?e:JSON.stringify(e,null,2)??String(e)}function Qn(e,t){return{content:[{type:"text",text:void 0===e?t:Yn(e)}],details:{value:e}}}async function er(e,t,n,r){let{handle:i,executeTool:o}=e;await i.activate(t);let s=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}}(i.settings(),t,n.readOnly),a=1e3*n.timeoutSeconds,l=e.confirmControl,c=await gn({code:n.code,snapshot:s,timeoutMs:a,...void 0===r?{}:{signal:r}},{service:i.service,executeTool:o,...void 0===l?{}:{confirmControl:(e,n,r)=>l({context:t,reason:e,signal:n,budgetMs:r})}}),u=[...c.displays],d=new Set(u.flatMap(e=>"text"===e.type&&""!==e.text?[e.text]:[]));return void 0!==c.returnValue&&u.push({type:"text",text:Xn(c.returnValue,d)}),0===u.length&&u.push({type:"text",text:"Done."}),{content:u,details:{value:c.returnValue,readOnly:n.readOnly,screenshots:c.screenshots,audit:c.audit}}}function tr(e){let{handle:t}=e,n=(t,n,r)=>er(e,t,n,r);return{...Kn,async execute(e,r,i,o,s){let a=function(e){if(Dn(Mn,e))return e;throw k(Gn,e,"computer")}(r);switch(a.action){case"call":{let e=X(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 nr(n(s,{code:r,readOnly:e,timeoutSeconds:60},i),t)}case"run":{let e=a.timeout??60;return nr(n(s,{code:a.code,readOnly:!0===a.read_only,timeoutSeconds:e},i),t)}case"capabilities":return nr((async()=>(await t.activate(s),Qn(await t.service.capabilities(),"capabilities unavailable")))(),t);case"close":return await t.close(),Qn(void 0,"Closed the desktop session.");default:return function(e){throw TypeError(`unhandled computer action ${JSON.stringify(e)}`)}(a)}}}}async function nr(e,t){try{return await e}catch(e){if(e instanceof Z){let t=Tn(e);return{content:[{type:"text",text:e.message}],details:{value:t,isError:!0},isError:!0}}if(!(e instanceof kt)||null===e.data||!("code"in e.data)||"PermissionDenied"!==e.data.code&&"ControlRequired"!==e.data.code&&"InputBusy"!==e.data.code&&"Suspended"!==e.data.code)throw e;let n=An(e.data.code,e.message,t.settings().stopHotkey,e.data.permission);return{content:[{type:"text",text:JSON.stringify(n,null,2)}],details:{value:n,isError:!0},isError:!0}}}function rr(e){let t=null;return{...zn,async execute(n,r,i,o,s){let a,l=e.handle.settings().stopHotkey;try{a=function(e){if(O(A,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(I,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=An(e.code,e.reason,l);return{content:[{type:"text",text:t.message}],details:{value:t,isError:!0},isError:!0}}let c,u=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),p=function(e,t){return`const actions = ${JSON.stringify(e)};\nlet bounds = ${JSON.stringify(t)};\nconst steps = [];\nconst outside = (x, y) => bounds !== null && (x < 0 || y < 0 || x >= bounds.width || y >= bounds.height);\nconst shoot = async () => { const shot = await desktop.screenshot(); bounds = { width: shot.width, height: shot.height }; };\nfor (const [index, a] of actions.entries()) {\n\tconst points = a.action === "drag" ? [[a.x, a.y], [a.to_x, a.to_y]] : "x" in a ? [[a.x, a.y]] : [];\n\tconst off = points.find(([x, y]) => outside(x, y));\n\tif (off !== undefined) {\n\t\tconst message = a.action + " coordinates (" + off[0] + "," + off[1] + ") are outside the latest screenshot bounds " + bounds.width + "x" + bounds.height + ".";\n\t\tsteps.push({ index, action: a.action, status: "error", code: "COMPUTER_COORD_INVALID", message });\n\t\treturn { steps, bounds, failedIndex: index };\n\t}\n\ttry {\n\t\tconst button = a.button === undefined ? {} : { button: a.button };\n\t\tswitch (a.action) {\n\t\t\tcase "screenshot": await shoot(); break;\n\t\t\tcase "click": await desktop.click(a.x, a.y, button); break;\n\t\t\tcase "double_click": await desktop.doubleClick(a.x, a.y, button); break;\n\t\t\tcase "move": await desktop.move(a.x, a.y); break;\n\t\t\tcase "drag": await desktop.drag([[a.x, a.y], [a.to_x, a.to_y]], button); break;\n\t\t\tcase "scroll": await desktop.scroll(a.x, a.y, { dx: a.scroll_x, dy: a.scroll_y }); break;\n\t\t\tcase "type": await desktop.type(a.text); break;\n\t\t\tcase "keypress": await desktop.press(a.keys); break;\n\t\t\tcase "wait": await wait(a.ms); break;\n\t\t}\n\t\tif (a.include_screenshot === true && a.action !== "screenshot") await shoot();\n\t\tsteps.push({ index, action: a.action, status: "success" });\n\t} catch (error) {\n\t\tconst code = error?.data?.code ?? error?.reason ?? error?.name ?? "Error";\n\t\tsteps.push({ index, action: a.action, status: "error", code, message: String(error?.message ?? error), permission: error?.data?.permission });\n\t\treturn { steps, bounds, failedIndex: index };\n\t}\n}\nreturn { steps, bounds, failedIndex: null };`}(function(e){return"batch"===e.action?e.actions:[e]}(a),t);try{c=await er(e,s,{code:p,readOnly:d,timeoutSeconds:u},i)}catch(e){if(!(e instanceof Error))throw e;if(e instanceof Z){let t=Tn(e);return{content:[{type:"text",text:t.message}],details:{value:t,isError:!0},isError:!0}}let t=e instanceof kt&&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=An(String(n),e.message,l,t?.permission);return{content:[{type:"text",text:r.message}],details:{value:r,isError:!0},isError:!0}}let h=c.details.value;if("object"!=typeof(f=h)||null===f||!Array.isArray(Reflect.get(f,"steps")))return c;var f;t=h.bounds;let m=c.content.filter(e=>"image"===e.type),g=null===h.failedIndex?void 0:h.steps[h.failedIndex];if(void 0===g){let e=`${h.steps.length} action(s) done: ${h.steps.map(e=>e.action).join(", ")}.`;return{...c,content:[...m,{type:"text",text:e}]}}let y=An(g.code??"Error",g.message??"action failed",l,g.permission),v=`Action ${g.index+1} (${g.action}) failed. ${void 0===y.permission?y.message:JSON.stringify(y)}`;return{content:[...m,{type:"text",text:v}],details:{...c.details,value:{...h,failure:y},isError:!0},isError:!0}}}}import{Type as ir}from"typebox";import{Check as or,Errors as sr}from"typebox/value";ir.Object({enabled:ir.Optional(ir.Boolean({description:"Register the computer tool (experimental; default: host supported)"})),showCursor:ir.Optional(ir.Boolean({default:!0,description:"Show the display-only virtual cursor on macOS"})),display:ir.Optional(ir.String({description:"`active` (default) follows the focused monitor; `all` composites every display; otherwise a display id"})),maxWidth:ir.Optional(ir.Integer({minimum:1,default:3840})),maxHeight:ir.Optional(ir.Integer({minimum:1,default:2400})),screenshotMaxBytes:ir.Optional(ir.Integer({minimum:1,default:5e6})),stopHotkey:ir.Optional(ir.String({minLength:1,description:"Stop chord, e.g. ctrl+alt+shift+escape"})),allowHostRelayOnlyStop:ir.Optional(ir.Boolean({default:!1})),macosCanary:ir.Optional(ir.Union([ir.Literal("session"),ir.Literal("off")],{default:"session"})),auditLog:ir.Optional(ir.Object({enabled:ir.Optional(ir.Boolean({default:!0}))},{additionalProperties:!1})),screenshotGc:ir.Optional(ir.Object({enabled:ir.Optional(ir.Boolean({default:!0})),staleMs:ir.Optional(ir.Integer({minimum:0,default:432e5})),scanIntervalMs:ir.Optional(ir.Integer({minimum:0,default:18e5}))},{additionalProperties:!1})),enginePath:ir.Optional(ir.String({minLength:1,description:"Override the located engine binary"})),cuaAdapter:ir.Optional(ir.Boolean({default:!1,description:"Also register computer_actions (OpenAI computer-use actions)"}))},{additionalProperties:!1});var ar=(e,t)=>{let n=setTimeout(e,t);return()=>clearTimeout(n)};import{readFileSync as lr}from"node:fs";import{dirname as cr,join as ur}from"node:path";import{accessSync as dr,constants as pr,existsSync as hr}from"node:fs";import{homedir as fr}from"node:os";import{join as mr}from"node:path";function gr(e,t,n,r=e=>Ie(e,n)){let i={host:t,attemptedPaths:[e]};if(!hr(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:yr(i,t,`${e}: not executable (expected a .exe file)`);try{return void dr(e,pr.X_OK)}catch(n){if(!(n instanceof Error&&"code"in n))throw n;return yr(i,t,`${e}: not executable (chmod +x)`)}}function yr(e,t,n){return{...e,code:"native-unavailable",message:`No senpi-desktop-engine binary is available for ${t}.`,cause:n}}function vr(e,t,n,r={}){let i=r.platform??process.platform,o=Oe(i,r.arch,r.libc);if(void 0!==e){let t=gr(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=Pe(s);if(null!==a.path){let e=Se(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=Ge({host:o,version:n,cacheDir:mr(t.HOME??fr(),".omo","cache","senpi-desktop-engine")});if(null!==e.path)return{path:e.path,source:"cache"}}return null===ve(o)?{diagnostic:a.diagnostic}:{notInstalled:a.diagnostic}}function br(e,t){let n;try{n=JSON.parse(lr(ur(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 wr(e){let t=e.OMO_PACKAGE_DIR?.trim();if(t){let e=br(t,["omo"]);if(void 0!==e)return e}let n=e.OMO_BIN?.trim();return n?br(cr(cr(n)),["omo-ai"]):void 0}function _r(e=process.env,t){return n=>{if(void 0!==n)return function(e){let t=Oe(),n=gr(e,t,process.platform);return void 0!==n?()=>{throw new yt(n)}:vt(e)}(n);let r=wr(e);return void 0!==r?function(e){let t=e.acquire??Xe,n=e.spawnEngine??bt;return async()=>{let r=await Ye({version:e.version,host:e.host??Oe()},n,t);if(null===r.path)throw new yt(r.diagnostic);return r.value}}({version:r}):void 0===t?vt():()=>{let e=Pe(t);if(null===e.path)throw new yt(e.diagnostic);return vt(e.path)()}}}function kr(e,t,n={}){let r=wr(t),i=vr(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=ve(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 xr={"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 Or 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:xr[e],action:"Run /computer status to see the engine path and what is wrong with it."}}}function Er(e){return e instanceof yt?e.diagnostic.code:e instanceof ie?"abi-mismatch":e instanceof Z?e.code:void 0}class $r extends Sn{#de="not started";#pe;#he;constructor(e={}){super(e),this.#pe=e.onError,this.#he=e.onPermissionRequired,this.onError(e=>this.#fe(e))}get engineState(){return this.#de}async open(e){try{let t=await super.open(e);return this.#de="ready",t}catch(e){if(!(e instanceof Error))throw e;if(this.#fe(e),e instanceof Z)throw e;let t=Er(e);if(void 0===t)throw e;throw this.#de=t,new Or(t,e)}}async call(e,t,n={}){return this.#me(super.call(e,t,n))}ensureStopPath(e){return this.#me(super.ensureStopPath(e))}stopPathStatus(){return this.#me(super.stopPathStatus())}stop(){return this.#me(super.stop())}resume(){return this.#me(super.resume())}async#me(e){try{let t=await e;return"not started"!==this.#de&&"launch-context-unavailable"!==this.#de||(this.#de="ready"),t}catch(e){if(!(e instanceof Error))throw e;throw this.#fe(e),e}}#fe(e){let t=Er(e);void 0!==t&&(this.#de=t),e instanceof kt&&null!==e.data&&"code"in e.data&&"PermissionDenied"===e.data.code&&null!=e.data.permission&&this.#he?.(e.data.permission),this.#pe?.(e)}}import{spawn as Sr}from"node:child_process";import{createInterface as Pr}from"node:readline";function zr(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 Ir(e,t="|"){return e.map(e=>Yr(e)).join(t)}function Tr(e,t){return"bigint"==typeof t?t.toString():t}class Ar{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 Cr(e){return new Ar(e)}function Rr(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Nr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function jr(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Mr(e){return jr(e._zod.def)??e._zod.def.shape}function Ur(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return Nr(this,t,e),e},enumerable:!0,configurable:!0})}function Dr(e,t,n){t in e?Nr(e,t,n):e[t]=n}function Lr(e,t,n,r){let i=Mr(t);for(let o of n){let n=Object.getOwnPropertyDescriptor(i,o);n.enumerable&&(n.get?Ur(e,o,()=>{let e=t._zod.def.shape[o];return r?r(e,o):e}):Dr(e,o,r?r(n.value,o):n.value))}}function Zr(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Fr(e){return JSON.stringify(e)}var Jr="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function qr(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var Vr=Cr(()=>{if(Ii.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Wr(e){if(!1===qr(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!==qr(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function Hr(e){return Wr(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var Br=new Set(["string","number","symbol"]);function Kr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Gr(e,t,n){let r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function Xr(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 Yr(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}var Qr={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]},ei={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function ti(e,t){let n=Mr(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 ni(e,t){let n={};return Lr(n,e,Reflect.ownKeys(Mr(e))),function(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?Ur(e,n,()=>t[n]):Dr(e,n,r.value))}}(n,t),n}function ri(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(ti(t,n)):void 0,s={};return Lr(s,t,Reflect.ownKeys(Mr(t)),e&&((t,n)=>o&&!o.has(n)?t:new e({type:"optional",innerType:t}))),Gr(t,Zr(t._zod.def,{shape:s,checks:[]}))}function ii(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 oi(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 si(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function ai(e){return"string"==typeof e?e:e?.message}function li(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function ci(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:ai(e.inst?._zod.def?.error?.(e))??ai(o?.(e))??ai(t?.error?.(e))??ai(n.customError?.(e))??ai(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 ui=/[\uD800-\uDBFF]/;function di(e){let t=e.length;if(!ui.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 pi(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function hi(...e){let[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}function fi(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function mi(e,t,n){return fi(e,t,n,!1)}function gi(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return fi(this,n,r(this))},set(e){fi(this,n,e)}})}return t}function yi(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return null==this?n:fi(this,t,n.bind(this))},set(e){fi(this,t,e)}})}var vi,bi=!1,wi={configurable:!0,get(){bi=!0}};function _i(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&vi!==e._zod?vi=void 0:(vi=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,wi);let e=bi;bi=!1;try{let r=n(this);return bi?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),bi=bi||e,r}catch(n){throw delete this[t],bi=bi||e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function ki(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 xi;function Oi(e){let t=()=>e;return t["~constantCatch"]=!0,t}var Ei={value:void 0,enumerable:!1},$i="captureStackTrace"in Error?Error:null;function Si(e,t,n,r){function i(e){this.def=e,this.constr=u,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{Ei.value=new i(r);try{Object.defineProperty(n,"_zod",Ei)}finally{Ei.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}):yi(e,n,r.value)}}(i,o))}let a=u.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 c extends l{}function u(e){let t=r?.Parent?function(e){let t=$i;if(t){let n=t.stackTraceLimit;if("number"==typeof n){try{t.stackTraceLimit=0}catch{return $i=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}(c):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(c,"name",{value:e}),Object.defineProperty(u,"init",{value:a}),Object.defineProperty(u,Symbol.hasInstance,{value:t=>!!(r?.Parent&&t instanceof r.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(u,"name",{value:e}),u}class Pi extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class zi extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(xi=globalThis).__zod_globalConfig??(xi.__zod_globalConfig={});var Ii=globalThis.__zod_globalConfig;function Ti(e){return e&&Object.assign(Ii,e),Ii}var Ai={get:function(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Tr,2)),e.message},set:function(e){this._zod.message=e},enumerable:!0,configurable:!0},Ci={value:void 0,enumerable:!1},Ri=new WeakSet([Object.prototype,Error.prototype]),Ni=(e,t)=>{e.name="$ZodError",Ci.value=t,Object.defineProperty(e,"issues",Ci),Ci.value=void 0,Object.defineProperty(e,"message",Ai);let n=Object.getPrototypeOf(e);Ri.has(n)||(Ri.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})}}))},ji=Si("$ZodError",Ni);Si("$ZodError",Ni,void 0,{Parent:Error});function Mi(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 Ui(e,t){return{callee:t?.callee??e,Err:t?.Err}}var Di=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 Pi;if(a.issues.length){let n=new(o?.Err??e)(a.issues.map(e=>ci(e,s,Ti())));throw Jr(n,o?.callee??t),n}return a.value};return t},Li=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=>ci(e,s,Ti())));throw Jr(n,o?.callee??t),n}return a.value};return t},Zi=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 Pi;return o.issues.length?Fi(e,o.issues,i):{success:!0,data:o.value}};function Fi(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>ci(e,n,Ti()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}var Ji=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?Fi(e,o.issues,i):{success:!0,data:o.value}},qi=Symbol.for("zod.compile.invalid"),Vi=Symbol.for("zod.compile.fallback"),Wi=(e,t,n)=>{let r=e._zod.bag.validator;if(void 0!==r){if(r(t)!==qi)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[Vi]=!0,r=o({value:t,issues:[]},i)):r=e._zod.run({value:t,issues:[]},i);if(r instanceof Promise)throw new Pi;return 0===r.issues.length}(e,t,n)};var Hi=/^[cC][0-9a-z]{6,}$/,Bi=/^[0-9a-z]+$/,Ki=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Gi=/^[0-9a-vA-V]{20}$/,Xi=/^[A-Za-z0-9]{27}$/,Yi=/^[a-zA-Z0-9_-]{21}$/;var Qi=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,eo=/^([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})$/,to=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)$/,no=/^(?:[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 ro=/^(?:(?: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])$/,io=/^(([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}|:))$/,oo=/^((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])$/,so=/^(([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])$/,ao=/^https?$/,lo=/^\+[1-9]\d{6,14}$/,co="(?:(?:\\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 uo=new RegExp(`^${co}$`);function po(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 ho=/^[\s\S]{0,}$/,fo=/^-?\d+(?:\.\d+)?$/,mo=/^(?:true|false)$/i,go=/^[^A-Z]*$/,yo=/^[^a-z]*$/,vo=Si("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),bo=e=>{let t=e.value;return!(n=t,null==n||void 0===t.length);var n},wo={number:"number",bigint:"bigint",object:"date"},_o=Si("$ZodCheckLessThan",(e,t)=>{vo.init(e,t);let n=wo[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:wo[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})}}),ko=Si("$ZodCheckGreaterThan",(e,t)=>{vo.init(e,t);let n=wo[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:wo[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})}}),xo=Si("$ZodCheckMultipleOf",(e,t)=>{vo.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})}}),Oo=Si("$ZodCheckNumberFormat",(e,t)=>{vo.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[i,o]=Qr[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})}}),Eo=Si("$ZodCheckMaxLength",(e,t)=>{var n;vo.init(e,t),(n=e._zod.def).when??(n.when=bo),e._zod.check=n=>{let r=n.value,i=r.length;if(("string"==typeof r&&i>t.maximum?di(r):i)<=t.maximum)return;let o=pi(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),$o=Si("$ZodCheckMinLength",(e,t)=>{var n;vo.init(e,t),(n=e._zod.def).when??(n.when=bo),e._zod.check=n=>{let r=n.value,i=r.length;if(("string"==typeof r&&i>=t.minimum&&i<2*t.minimum?di(r):i)>=t.minimum)return;let o=pi(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),So=Si("$ZodCheckLengthEquals",(e,t)=>{var n;vo.init(e,t),(n=e._zod.def).when??(n.when=bo),e._zod.check=n=>{let r=n.value,i=r.length,o="string"==typeof r&&i>=t.length&&i<=2*t.length?di(r):i;if(o===t.length)return;let s=pi(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})}}),Po=Si("$ZodCheckStringFormat",(e,t)=>{var n,r;vo.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=()=>{})}),zo=Si("$ZodCheckRegex",(e,t)=>{Po.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})}}),Io=Si("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=go),Po.init(e,t)}),To=Si("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=yo),Po.init(e,t)}),Ao=Si("$ZodCheckIncludes",(e,t)=>{vo.init(e,t);let n=Kr(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})}}),Co=Si("$ZodCheckStartsWith",(e,t)=>{vo.init(e,t);let n=new RegExp(`^${Kr(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})}}),Ro=Si("$ZodCheckEndsWith",(e,t)=>{vo.init(e,t);let n=new RegExp(`.*${Kr(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})}}),No=Si("$ZodCheckOverwrite",(e,t)=>{vo.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class jo{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 Mo={major:4,minor:6,patch:5},Uo=Si("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Mo;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=ii(t);for(let s of n){if(s._zod.def.when){if(oi(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 Pi;if(i||a instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await a,t.issues.length!==n&&(li(t.issues,n,e),o||(o=ii(t,n)))});else{if(t.issues.length===n)continue;li(t.issues,n,e),o||(o=ii(t,n))}}return i?i.then(()=>t):t},n=(n,r,o)=>{if(ii(n))return n.aborted=!0,n;let s=t(r,i,o);if(s instanceof Promise){if(!1===o.async)throw new Pi;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 Pi;return s.then(e=>t(e,i,o))}return t(s,i,o)}}},{get"~standard"(){return mi(this,"~standard",Lo(this))},set"~standard"(e){fi(this,"~standard",e)}}),Do=(e,t)=>e.issues.length?{issues:e.issues.map(e=>ci(e,t,Ti()))}:{value:e.value};function Lo(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return Do(r,n)}catch(e){}return async function(e,t){let n={async:!0};return Do(await e._zod.run({value:t,issues:[]},n),n)}(e,t)},vendor:"zod",version:1}}var Zo=Si("$ZodString",(e,t)=>{Uo.init(e,t),e._zod.pattern=t.pattern??ho,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}}),Fo=Si("$ZodStringFormat",(e,t)=>{Po.init(e,t),Zo.init(e,t)}),Jo=Si("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=eo),Fo.init(e,t)}),qo=Si("$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=to(e))}else t.pattern??(t.pattern=to());Fo.init(e,t)}),Vo=Si("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=no),Fo.init(e,t)});function Wo(e){try{return typeof URL<"u"&&"function"==typeof URL.canParse?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function Ho(e,t){return"normalize"in t||"hostname"in t||"protocol"in t?function(e,t){if(!t.normalize&&t.protocol?.source===ao.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):Wo(e)||2}var Bo=/[\t\n\r]/g;function Ko(e){return e.replace(Bo,"")}var Go=Si("$ZodURL",(e,t)=>{Fo.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=Ho(r,t);return 1===i?void n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort}):2===i?void n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort}):!0===i?void(n.value=Ko(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:Ko(r)))}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Xo=Si("$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")),Fo.init(e,t)}),Yo=Si("$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?Yi:(n=t.length,new RegExp(`^[a-zA-Z0-9_-]{${n}}$`))),Fo.init(e,t)}),Qo=Si("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Hi),Fo.init(e,t)}),es=Si("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Bi),Fo.init(e,t)}),ts=Si("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ki),Fo.init(e,t)}),ns=Si("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Gi),Fo.init(e,t)}),rs=Si("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Xi),Fo.init(e,t)}),is=Si("$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=`${po({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${po({precision:e.precision})}`:n;return new RegExp(`^${co}T(?:${r})$`)}(t)),Fo.init(e,t)}),os=Si("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=uo),Fo.init(e,t)}),ss=Si("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${po(t)}$`)),Fo.init(e,t)}),as=Si("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Qi),Fo.init(e,t)}),ls=Si("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ro),Fo.init(e,t)}),cs=/^[0-9a-fA-F:.]+$/;function us(e){return!!cs.test(e)&&Wo(`http://[${e}]`)}var ds=Si("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=io),Fo.init(e,t),e._zod.check=n=>{us(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),ps=Si("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oo),Fo.init(e,t)});var hs=Si("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=so),Fo.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)&&us(n)})(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function fs(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 ms=/^[0-9a-zA-Z+/]*={0,2}$/,gs=Si("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ms),Fo.init(e,t),e._zod.check=n=>{fs(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),ys=/^[A-Za-z0-9_-]*$/;var vs=Si("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ys),Fo.init(e,t),e._zod.check=n=>{(function(e){if(!ys.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return fs(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})}}),bs=Si("$ZodE164",(e,t)=>{t.pattern??(t.pattern=lo),Fo.init(e,t)});var ws=Si("$ZodJWT",(e,t)=>{Fo.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})}}),_s=Si("$ZodNumber",(e,t)=>{Uo.init(e,t),e._zod.pattern=fo,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}}),ks=Si("$ZodNumberFormat",(e,t)=>{Oo.init(e,t),_s.init(e,t)}),xs=Si("$ZodBoolean",(e,t)=>{Uo.init(e,t),e._zod.pattern=mo,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}}),Os=Si("$ZodUnknown",(e,t)=>{Uo.init(e,t),e._zod.parse=e=>e}),Es=Si("$ZodNever",(e,t)=>{Uo.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function $s(e,t,n){e.issues.length&&t.issues.push(...si(n,e.issues)),t.value[n]=e.value}var Ss=Si("$ZodArray",(e,t)=>{Uo.init(e,t);let n=Ii.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=>$s(t,r,e)));else if($s(l,r,e),a&&0!==l.issues.length&&ii(l))break}return s.length?Promise.all(s).then(()=>r):r}});function Ps(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(...si(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 zs=[];function Is(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:zs,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 Ts(e,t,n,r,i,o,s){let a=[],l=i.keySet,c=i.catchall._zod,u=c.def.type,{optin:d,optout:p}=c,h=0;for(let i in t){if(s&&n.issues.length!==h){if(ii(n,h))break;h=n.issues.length}if(l.has(i))continue;if("__proto__"===i){"never"===u&&a.push(i);continue}if("never"===u){a.push(i);continue}let o=c.run({value:t[i],issues:[]},r);o instanceof Promise?e.push(o.then(e=>Ps(e,n,i,t,d,p))):Ps(o,n,i,t,d,p)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:o,continue:!0}),e.length?Promise.all(e).then(()=>n):n}var As=Si("$ZodObject",(e,t)=>{Uo.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=Cr(()=>Is(t));_i(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)||Nr(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=qr,a=t.catchall,l=Ii.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 c=[],u=o.shape,d=n?.abortEarly,p=t.issues.length;for(let e of o.allKeys){if(d&&t.issues.length!==p){if(ii(t,p))break;p=t.issues.length}if("__proto__"===e)continue;let i=u[e],o=i._zod.optin,s=i._zod.optout,a=i._zod.run({value:r[e],issues:[]},n);a instanceof Promise?c.push(a.then(n=>Ps(n,t,e,r,o,s))):Ps(a,t,e,r,o,s)}return a?Ts(c,r,t,n,i.value,e,!0===d):c.length?Promise.all(c).then(()=>t):t}}),Cs=Si("$ZodObjectJIT",(e,t)=>{As.init(e,t);let n,r,i=e._zod.parse,o=Cr(()=>Is(t)),s=Ii.memoizer,a=qr,l=!Ii.jitless,c=l&&Vr.value,u=t.catchall;e._zod.parse=(d,p)=>{r??(r=o.value);let h=d.value;return a(h)?l&&c&&!1===p?.async&&!0!==p.jitless?(n||(n=(t=>{let n=o.value,r=n.symbolKeys,i=new jo(["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 c=Object.create(null),u=0;for(let e of n.allKeys)c[e]="key_"+u++;i.write(s?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let e of n.allKeys){if("__proto__"===e)continue;let n=c[e],o="symbol"==typeof e?`syms[${r.indexOf(e)}]`:Fr(e),s=`${o} in input`,u=t[e],d=u?._zod?.optin,p=void 0!==d,h="optional"===u?._zod?.optout;if(i.write(`const ${n} = ${a(o)};`),p&&h){let e="optional"===d?`${n}_present`:`${n}.value !== undefined || ${n}_present`;i.write(`\n const ${n}_present = ${s};\n if (!${n}.issues.length || ${n}_present) {\n if (${n}.issues.length) {${l(n,o)}\n }\n\n if (${e}) {\n newResult[${o}] = ${n}.value;\n }\n }\n\n `)}else p?(i.write(`\n if (${n}.issues.length) {${l(n,o)}\n }\n `),"defaulted"===d?i.write(`newResult[${o}] = ${n}.value;`):i.write(`\n if (${n}.value !== undefined || ${s}) {\n newResult[${o}] = ${n}.value;\n }\n `)):i.write(`\n const ${n}_present = ${s};\n if (${n}.issues.length) {${l(n,o)}\n }\n if (!${n}_present && !${n}.issues.length) {\n payload.issues.push({\n code: "invalid_type",\n expected: "nonoptional",\n input: undefined,\n path: [${o}]\n });\n if (ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }\n }\n\n if (${n}_present) {\n newResult[${o}] = ${n}.value;\n }\n\n `)}return i.write("payload.value = newResult;"),i.write("return payload;"),i.compile()})(t.shape)),d=n(d,p),u?Ts([],h,d,p,r,e,!0===p?.abortEarly):d):i(d,p):(d.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),d)}});function Rs(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=>!ii(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=>ci(e,r,Ti())))}),t)}var Ns=Si("$ZodUnion",(e,t)=>{Uo.init(e,t),_i(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),_i(e,"optout",e=>e.def.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),_i(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)))}),_i(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=>Rr(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=>Rs(t,r,e,i)):Rs(s,r,e,i)}}),js=Si("$ZodIntersection",(e,t)=>{Uo.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])=>Us(e,t,n)):Us(e,i,o)}});function Ms(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(Wr(e)&&Wr(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=Ms(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=Ms(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 Us(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=Ms(t.value,n.value);if(!l.valid){if(ii(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(l.mergeErrorPath)}`)}return e.value=l.data,e}var Ds=Si("$ZodEnum",(e,t)=>{Uo.init(e,t);let n=zr(t.entries),r=new Set(n);e._zod.values=r,_i(e,"pattern",e=>{let t=zr(e.def.entries).filter(e=>Br.has(typeof e));return new RegExp(t.length?`^(${t.map(e=>Kr(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}}),Ls=Si("$ZodLiteral",(e,t)=>{Uo.init(e,t);let n=new Set(t.values);e._zod.values=n,_i(e,"pattern",e=>{let t=e.def.values;return new RegExp(t.length?`^(${t.map(e=>"string"==typeof e?Kr(e):e?Kr(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}}),Zs=Si("$ZodTransform",(e,t)=>{Uo.init(e,t),e._zod.optin="optional",Ii.memoizer?.guard(e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new zi(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 Pi;return n.value=i,n}});function Fs(e,t){return e.value=t.issues.length?void 0:t.value,e}var Js=Si("$ZodOptional",(e,t)=>{Uo.init(e,t),_i(e,"optin",e=>"defaulted"===e.def.innerType._zod.optin?"defaulted":"optional"),e._zod.optout="optional",_i(e,"values",e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),_i(e,"pattern",e=>{let t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${Rr(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=>Fs(e,t)):Fs(e,r)}return t.innerType._zod.run(e,n)}}),qs=Si("$ZodExactOptional",(e,t)=>{Js.init(e,t),_i(e,"values",e=>e.def.innerType._zod.values),_i(e,"pattern",e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Vs=Si("$ZodNullable",(e,t)=>{Uo.init(e,t),_i(e,"optin",e=>e.def.innerType._zod.optin),_i(e,"optout",e=>e.def.innerType._zod.optout),_i(e,"pattern",e=>{let t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${Rr(t.source)}|null)$`):void 0}),_i(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)}),Ws=Si("$ZodDefault",(e,t)=>{Uo.init(e,t),e._zod.optin="defaulted",_i(e,"values",e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Hs(e,t)):Hs(r,t)}});function Hs(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var Bs=Si("$ZodPrefault",(e,t)=>{Uo.init(e,t),e._zod.optin="defaulted",_i(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))}),Ks=Si("$ZodNonOptional",(e,t)=>{Uo.init(e,t),_i(e,"values",e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Gs(t,e)):Gs(i,e)}});function Gs(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function Xs(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>ci(e,r,Ti()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var Ys=Si("$ZodCatch",(e,t)=>{Uo.init(e,t),_i(e,"optin",e=>"defaulted"===e.def.innerType._zod.optin?"defaulted":"optional"),_i(e,"optout",e=>e.def.innerType._zod.optout),_i(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=>Xs(e,r,t,n)):Xs(e,r,t,n)}}),Qs=Si("$ZodPipe",(e,t)=>{Uo.init(e,t),_i(e,"values",e=>e.def.in._zod.values),_i(e,"optin",e=>e.def.in._zod.optin),_i(e,"optout",e=>e.def.out._zod.optout),_i(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=>ea(e,t.in,n)):ea(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>ea(e,t.out,n)):ea(r,t.out,n)}});function ea(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 ta=Si("$ZodReadonly",(e,t)=>{Uo.init(e,t),_i(e,"propValues",e=>e.def.innerType._zod.propValues),_i(e,"values",e=>e.def.innerType._zod.values),_i(e,"optin",e=>e.def.innerType?._zod?.optin),_i(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(na):na(r)}});function na(e){return e.memo||(e.value=Object.freeze(e.value)),e}var ra=Si("$ZodCustom",(e,t)=>{vo.init(e,t),Uo.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=>ia(t,n,r,e));ia(i,n,r,e)}});function ia(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(hi(e))}}class oa extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}var sa="~memo",aa=[];function la(e){return null!==e&&"object"==typeof e}function ca(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var ua=new WeakMap;function da(e,t,n){let r=ua.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=da(e,t,n);r>i&&(i=r)}},s=e=>{e>i&&(i=e)},a=e._zod.def;switch(a.type){case"object":{let e=jr(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?da(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?da(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&&ua.set(e,2===t);return t}(e,i)}var pa,ha=[],fa={alloc(e,t,n){let r=pa;if(!r)return n;pa=void 0;let i={value:n,issues:null};return r.set(t.value,i),ha.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[sa]?.backEdges;return void 0!==n&&la(t)&&n.has(t)}(n,e.value))throw new oa;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=da(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 c=a.value;if(!la(c))return t(a,l);let u,d=l[sa];d||(d={buckets:new WeakMap,backEdges:void 0},l[sa]=d),r===l?u=i:(u=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=u);let p=u.get(c);if(p)return a.value=p.value,p.issues?p.issues.length&&a.issues.push(...ca(p.issues)):(a.memo=!0,d.backEdges??(d.backEdges=new WeakSet),d.backEdges.add(p.value)),a;pa=u;let h=ha.length,f=t(a,l);pa=void 0;let m=ha.length>h?ha.pop():void 0;return f instanceof Promise?f.then(e=>(m&&(m.issues=e.issues.length?ca(e.issues):aa),e)):(m&&(m.issues=f.issues.length?ca(f.issues):aa),f)};e._zod.parse=s,e._zod.run===t&&(e._zod.run=s)})}};var ma,ga=()=>{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 ${Yr(e.values[0])}`:`Invalid option: expected one of ${Ir(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":""}: ${Ir(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 ya{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)}}(ma=globalThis).__zod_globalRegistry??(ma.__zod_globalRegistry=new ya);var va=globalThis.__zod_globalRegistry;function ba(e){return e.checks&&(e.checks=[...e.checks]),e}function wa(e,t){return new _o({check:"less_than",...Xr(t),value:e,inclusive:!1})}function _a(e,t){return new _o({check:"less_than",...Xr(t),value:e,inclusive:!0})}function ka(e,t){return new ko({check:"greater_than",...Xr(t),value:e,inclusive:!1})}function xa(e,t){return new ko({check:"greater_than",...Xr(t),value:e,inclusive:!0})}function Oa(e,t){return new xo({check:"multiple_of",...Xr(t),value:e})}function Ea(e,t){return new Eo({check:"max_length",...Xr(t),maximum:e})}function $a(e,t){return new $o({check:"min_length",...Xr(t),minimum:e})}function Sa(e,t){return new So({check:"length_equals",...Xr(t),length:e})}function Pa(e){return new No({check:"overwrite",tx:e})}function za(e,t){let n=function(e,t){let n=new vo({check:"custom",...Xr(t)});return n._zod.check=e,n}(t=>(t.addIssue=e=>{if("string"==typeof e)t.issues.push(hi(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(hi(r))}},e(t.value,t)),t);return n}function Ia(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Nr(e,t,n[t]);return e}function Ta(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??va,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 Aa(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 Ca(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),Ca(o,t,r),t.seen.get(o).isParent=!0)}let l=t.metadataRegistry.get(e);return l&&Ia(s.schema,l),"input"===t.io&&Ja(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 Ra(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Na(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}/${Ra(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+Ra(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 ja(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;ja(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 Ma=new Set(["type","properties","required","additionalProperties"]),Ua=["oneOf","anyOf"];function Da(e){let t=e.additionalProperties;return void 0===t||!1===t||"object"!=typeof t||null===t?null:Object.keys(t).length?t:null}function La(e){let t=[];for(let n of e){if("object"!=typeof n||"object"!==n.type)return null;for(let e in n)if(!Ma.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]??Da(n);null!=t&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Nr(n,r,1===e.length?e[0]:La(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=Da(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 Za(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of Ma)if(t in e)return;let n=t.filter(e=>Ua.some(t=>Array.isArray(e[t]))),r=null;if(n.length){let e=n[0],i=Ua.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=>La([...o,e]));if(s.some(e=>!e))return;r={[i]:s}}else r=La(t);r&&(delete e.allOf,Ia(e,r))}function Fa(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?Ia(i,a):(i.allOf=i.allOf??[],i.allOf.push(a)),Ia(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())ja(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)??[])Za(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)}Ia(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,Nr(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:qa(t,"input",e.processors),output:qa(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw Error("Error converting schema to JSON.")}}function Ja(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 Ja(r.element,n);if("set"===r.type)return Ja(r.valueType,n);if("lazy"===r.type)return Ja(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 Ja(r.innerType,n);if("intersection"===r.type)return Ja(r.left,n)||Ja(r.right,n);if("record"===r.type||"map"===r.type)return Ja(r.keyType,n)||Ja(r.valueType,n);if("pipe"===r.type)return!!e._zod.traits.has("$ZodCodec")||(Ja(r.in,n)||Ja(r.out,n));if("object"===r.type){for(let e in r.shape)if(Ja(r.shape[e],n))return!0;return!1}if("union"===r.type){for(let e of r.options)if(Ja(e,n))return!0;return!1}if("tuple"===r.type){for(let e of r.items)if(Ja(e,n))return!0;return!(!r.rest||!Ja(r.rest,n))}return!1}var qa=(e,t,n={})=>r=>{let{libraryOptions:i,target:o}=r??{},s=Ta({...i??{},target:o,io:t,processors:n});return Ca(e,s),Na(s,e),Fa(s,e)},Va=(e,t,n)=>{(void 0===e[t]||n>e[t])&&(e[t]=n)},Wa=(e,t,n)=>{(void 0===e[t]||n<e[t])&&(e[t]=n)},Ha=(e,t)=>{Va(e,"minimum",t),Wa(e,"maximum",t)},Ba=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},Ka=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Ga=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},Xa=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Ya=(e,t)=>Va(e,"minimum",t.minimum),Qa=(e,t)=>Wa(e,"maximum",t.maximum),el=e=>(t,n)=>{Xa(t,n.format);let[r,i]=e[n.format];Va(t,"minimum",r),Wa(t,"maximum",i)},tl={greater_than:(e,t)=>Va(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Wa(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Ba(e,t.value),number_format:el(Qr),bigint_format:el(ei),min_length:Ya,max_length:Qa,length_equals:(e,t)=>Ha(e,t.length),min_size:Ya,max_size:Qa,size_equals:(e,t)=>Ha(e,t.size),string_format:(e,t)=>{Xa(e,t.format),t.pattern&&Ka(e,t.pattern),"base64"!==t.format&&"base64url"!==t.format||(e.contentEncoding=t.format),(t.local||-1===t.precision)&&(e.laxFormat=!0)},mime_type:(e,t)=>Ga(e,t.mime)};function nl(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let e of r)tl[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;void 0!==i.minimum&&Va(t,"minimum",i.minimum),void 0!==i.exclusiveMinimum&&Va(t,"exclusiveMinimum",i.exclusiveMinimum),void 0!==i.maximum&&Wa(t,"maximum",i.maximum),void 0!==i.exclusiveMaximum&&Wa(t,"exclusiveMaximum",i.exclusiveMaximum),void 0!==i.multipleOf&&Ba(t,i.multipleOf),void 0!==i.format&&(t.format??(t.format=i.format),i.format.includes("int")&&(t.isInt=!0)),i.mime&&Ga(t,i.mime);for(let e of i.patterns??[])Ka(t,e);return t}var rl={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},il=new Map([[ms,/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/],[ys,/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/]]),ol=e=>il.get(e)??e;function sl(e){let t=e._zod.def;return"pipe"===t.type&&t.in._zod.traits.has("$ZodTransform")?sl(t.out):"catch"===t.type?sl(t.innerType):e._zod.optin}var al=Symbol();function ll(e,t,n,r,i){let o=!1,s=JSON.stringify(e,(e,t)=>"bigint"!=typeof t?t:(o=!0,null));return o?(Aa(t,n,r,i,"BigInt defaults cannot be represented in JSON Schema"),al):JSON.parse(s)}var cl=(e,t,n,r)=>{let i=e._zod.def;Ca(i.innerType,t,r),t.seen.get(e).ref=i.innerType},ul=new WeakSet([Object.prototype,Error.prototype]);function dl(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 pl,hl=Si("ZodError",(e,t)=>{ji.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);ul.has(n)||(ul.add(n),dl(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)),dl(n,"flatten",e=>t=>function(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?Mi(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}(e,t)),dl(n,"addIssue",e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Tr,2)}),dl(n,"addIssues",e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Tr,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return 0===this.issues.length}}))},void 0,{Parent:Error}),fl=Di(hl),ml=Li(hl),gl=Zi(hl),yl=Ji(hl),vl=(e=>{let t=Di(e),n=(e,r,i,o)=>{let s=i?{...i,direction:"backward"}:{direction:"backward"};return t(e,r,s,Ui(n,o))};return n})(hl),bl=(e=>{let t=Di(e),n=(e,r,i,o)=>t(e,r,i,Ui(n,o));return n})(hl),wl=(e=>{let t=Li(e),n=async(e,r,i,o)=>{let s=i?{...i,direction:"backward"}:{direction:"backward"};return await t(e,r,s,Ui(n,o))};return n})(hl),_l=(e=>{let t=Li(e),n=async(e,r,i,o)=>await t(e,r,i,Ui(n,o));return n})(hl),kl=(pl=hl,(e,t,n)=>{let r=n?{...n,direction:"backward"}:{direction:"backward"};return Zi(pl)(e,t,r)}),xl=(e=>(t,n,r)=>Zi(e)(t,n,r))(hl),Ol=(e=>async(t,n,r)=>{let i=r?{...r,direction:"backward"}:{direction:"backward"};return Ji(e)(t,n,i)})(hl),El=(e=>async(t,n,r)=>Ji(e)(t,n,r))(hl);function $l(){Ii.localeError||Ti({localeError:ga()})}function Sl(){Ii.memoizer||Ti({memoizer:fa})}var Pl=Si("ZodType",(e,t)=>($l(),Uo.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Zr(t,{checks:[...t.checks??[],...e.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Gr(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(function(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Xr(n)})}(Rc,e,t)}(e,t))},superRefine(e,t){return this.check(function(e,t){return za(e,t)}(e,t))},overwrite(e){return this.check(Pa(e))},optional(){return xc(this)},exactOptional(){return new Oc({type:"optional",innerType:this})},nullable(){return $c(this)},nullish(){return xc($c(this))},nonoptional(e){return function(e,t){return new zc({type:"nonoptional",innerType:e,...Xr(t)})}(this,e)},array(){return pc(this)},or(e){return gc([this,e])},and(e){return new yc({type:"intersection",left:this,right:e})},transform(e){return Ac(this,new _c({type:"transform",transform:e}))},default(e){return t=e,new Sc({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():Hr(t)}});var t},prefault(e){return t=e,new Pc({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():Hr(t)}});var t},catch(e){return new Ic({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:Oi(t)});var t},pipe(e){return Ac(this,e)},readonly(){return new Cc({type:"readonly",innerType:this})},describe(e){let t=this.clone();return va.add(t,{description:e}),t},meta(...e){if(0===e.length)return va.get(this);let t=this.clone();return va.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 mi(this,"~standard",{...Lo(this),jsonSchema:{input:qa(this,"input"),output:qa(this,"output")}})},set"~standard"(e){fi(this,"~standard",e)},parse:function e(t,n){return fl(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await ml(this,t,n,{callee:e})},safeParse(e,t){return gl(this,e,t)},async safeParseAsync(e,t){return yl(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){fi(this,"spa",e)},validate(e,t){return Wi(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 vl(this,t,n,{callee:e})},decode:function e(t,n){return bl(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await wl(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await _l(this,t,n,{callee:e})},safeEncode(e,t){return kl(this,e,t)},safeDecode(e,t){return xl(this,e,t)},async safeEncodeAsync(e,t){return Ol(this,e,t)},async safeDecodeAsync(e,t){return El(this,e,t)},toJSONSchema(e){return((e,t={})=>n=>{let r=Ta({...n,processors:t});return Ca(e,r),Na(r,e),Fa(r,e)})(this,{})(e)},get description(){return va.get(this)?.description},get _def(){return this._zod.def}}),zl=Si("_ZodString",(e,t)=>{Zo.init(e,t),Pl.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:c}=nl(e);if("number"==typeof i&&(r.minLength=i),"number"==typeof o&&(r.maxLength=o),s&&(r.format=rl[s]??s,""===r.format&&delete r.format,("time"===s||c)&&delete r.format),l&&(r.contentEncoding=l),a&&a.size>0){let e=[...a].map(ol);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)},gi({format:e=>nl(e).format??null,minLength:e=>nl(e).minimum??null,maxLength:e=>nl(e).maximum??null},{regex(...e){return this.check(function(e,t){return new zo({check:"string_format",format:"regex",...Xr(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new Ao({check:"string_format",format:"includes",...Xr(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new Co({check:"string_format",format:"starts_with",...Xr(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new Ro({check:"string_format",format:"ends_with",...Xr(t),suffix:e})}(...e))},min(...e){return this.check($a(...e))},max(...e){return this.check(Ea(...e))},length(...e){return this.check(Sa(...e))},nonempty(...e){return this.check($a(1,...e))},lowercase(e){return this.check(function(e){return new Io({check:"string_format",format:"lowercase",...Xr(e)})}(e))},uppercase(e){return this.check(function(e){return new To({check:"string_format",format:"uppercase",...Xr(e)})}(e))},trim(){return this.check(Pa(e=>e.trim()))},normalize(...e){return this.check(function(e){return Pa(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(Pa(e=>e.toLowerCase()))},toUpperCase(){return this.check(Pa(e=>e.toUpperCase()))},slugify(){return this.check(Pa(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}})),Il=Si("ZodString",(e,t)=>{Zo.init(e,t),zl.init(e,t)},{email(e){return this.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Xr(t)})}(Ml,e))},url(e){return this.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Xr(t)})}(Ll,e))},jwt(e){return this.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Xr(t)})}(tc,e))},emoji(e){return this.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Xr(t)})}(Zl,e))},guid(e){return this.check(function(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Xr(t)})}(Ul,e))},uuid(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Xr(t)})}(Dl,e))},uuidv4(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Xr(t)})}(Dl,e))},uuidv6(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Xr(t)})}(Dl,e))},uuidv7(e){return this.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Xr(t)})}(Dl,e))},nanoid(e){return this.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Xr(t)})}(Fl,e))},cuid(e){return this.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Xr(t)})}(Jl,e))},cuid2(e){return this.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Xr(t)})}(ql,e))},ulid(e){return this.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Xr(t)})}(Vl,e))},base64(e){return this.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Xr(t)})}(Yl,e))},base64url(e){return this.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Xr(t)})}(Ql,e))},xid(e){return this.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Xr(t)})}(Wl,e))},ksuid(e){return this.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Xr(t)})}(Hl,e))},ipv4(e){return this.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Xr(t)})}(Bl,e))},ipv6(e){return this.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Xr(t)})}(Kl,e))},cidrv4(e){return this.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Xr(t)})}(Gl,e))},cidrv6(e){return this.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Xr(t)})}(Xl,e))},e164(e){return this.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Xr(t)})}(ec,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,...Xr(t)})}(Cl,e))},date(e){return this.check(function(e,t){return new e({type:"string",format:"date",check:"string_format",...Xr(t)})}(Rl,e))},time(e){return this.check(function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Xr(t)})}(Nl,e))},duration(e){return this.check(function(e,t){return new e({type:"string",format:"duration",check:"string_format",...Xr(t)})}(jl,e))}});function Tl(e){return function(e,t){return new e(ba({type:"string",...Xr(t)}))}(Il,e)}var Al=Si("ZodStringFormat",(e,t)=>{Fo.init(e,t),zl.init(e,t)}),Cl=Si("ZodISODateTime",(e,t)=>{is.init(e,t),Al.init(e,t)}),Rl=Si("ZodISODate",(e,t)=>{os.init(e,t),Al.init(e,t)}),Nl=Si("ZodISOTime",(e,t)=>{ss.init(e,t),Al.init(e,t)}),jl=Si("ZodISODuration",(e,t)=>{as.init(e,t),Al.init(e,t)}),Ml=Si("ZodEmail",(e,t)=>{Vo.init(e,t),Al.init(e,t)}),Ul=Si("ZodGUID",(e,t)=>{Jo.init(e,t),Al.init(e,t)}),Dl=Si("ZodUUID",(e,t)=>{qo.init(e,t),Al.init(e,t)}),Ll=Si("ZodURL",(e,t)=>{Go.init(e,t),Al.init(e,t)}),Zl=Si("ZodEmoji",(e,t)=>{Xo.init(e,t),Al.init(e,t)}),Fl=Si("ZodNanoID",(e,t)=>{Yo.init(e,t),Al.init(e,t)}),Jl=Si("ZodCUID",(e,t)=>{Qo.init(e,t),Al.init(e,t)}),ql=Si("ZodCUID2",(e,t)=>{es.init(e,t),Al.init(e,t)}),Vl=Si("ZodULID",(e,t)=>{ts.init(e,t),Al.init(e,t)}),Wl=Si("ZodXID",(e,t)=>{ns.init(e,t),Al.init(e,t)}),Hl=Si("ZodKSUID",(e,t)=>{rs.init(e,t),Al.init(e,t)}),Bl=Si("ZodIPv4",(e,t)=>{ls.init(e,t),Al.init(e,t)}),Kl=Si("ZodIPv6",(e,t)=>{ds.init(e,t),Al.init(e,t)}),Gl=Si("ZodCIDRv4",(e,t)=>{ps.init(e,t),Al.init(e,t)}),Xl=Si("ZodCIDRv6",(e,t)=>{hs.init(e,t),Al.init(e,t)}),Yl=Si("ZodBase64",(e,t)=>{gs.init(e,t),Al.init(e,t)}),Ql=Si("ZodBase64URL",(e,t)=>{vs.init(e,t),Al.init(e,t)}),ec=Si("ZodE164",(e,t)=>{bs.init(e,t),Al.init(e,t)}),tc=Si("ZodJWT",(e,t)=>{ws.init(e,t),Al.init(e,t)}),nc=Si("ZodNumber",(e,t)=>{_s.init(e,t),Pl.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:c,isInt:u}=nl(e);i.type=u?"integer":"number";let d="number"==typeof c&&c>=(o??Number.NEGATIVE_INFINITY),p="number"==typeof l&&l<=(s??Number.POSITIVE_INFINITY),h="draft-04"===t.target||"openapi-3.0"===t.target;if(d?h?(i.minimum=c,i.exclusiveMinimum=!0):i.exclusiveMinimum=c:"number"==typeof o&&(i.minimum=o),p?h?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:"number"==typeof s&&(i.maximum=s),a){let n=new Set;for(let o of a)Number.isFinite(o)&&0!==o?n.add(Math.abs(o)):Aa(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},gi({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=nl(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=nl(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:n}=nl(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>nl(e).format??null},{gt(e,t){return this.check(ka(e,t))},gte(e,t){return this.check(xa(e,t))},min(e,t){return this.check(xa(e,t))},lt(e,t){return this.check(wa(e,t))},lte(e,t){return this.check(_a(e,t))},max(e,t){return this.check(_a(e,t))},int(e){return this.check(ic(e))},safe(e){return this.check(ic(e))},positive(e){return this.check(ka(0,e))},nonnegative(e){return this.check(xa(0,e))},negative(e){return this.check(wa(0,e))},nonpositive(e){return this.check(_a(0,e))},multipleOf(e,t){return this.check(Oa(e,t))},step(e,t){return this.check(Oa(e,t))},finite(){return this}}));var rc=Si("ZodNumberFormat",(e,t)=>{ks.init(e,t),nc.init(e,t)});function ic(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Xr(t)})}(rc,e)}var oc=Si("ZodBoolean",(e,t)=>{xs.init(e,t),Pl.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function sc(e){return function(e,t){return new e({type:"boolean",...Xr(t)})}(oc,e)}var ac=Si("ZodUnknown",(e,t)=>{Os.init(e,t),Pl.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function lc(){return new ac({type:"unknown"})}var cc=Si("ZodNever",(e,t)=>{Es.init(e,t),Pl.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function uc(e){return function(e,t){return new e({type:"never",...Xr(t)})}(cc,e)}var dc=Si("ZodArray",(e,t)=>{Sl(),Ss.init(e,t),Pl.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=n,o=e._zod.def,{minimum:s,maximum:a}=nl(e);"number"==typeof s&&(i.minItems=s),"number"==typeof a&&(i.maxItems=a),i.type="array",i.items=Ca(o.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element},{min(e,t){return this.check($a(e,t))},nonempty(e){return this.check($a(1,e))},max(e,t){return this.check(Ea(e,t))},length(e,t){return this.check(Sa(e,t))},unwrap(){return this.element}});function pc(e,t){return function(e,t,n){return new e({type:"array",element:t,...Xr(n)})}(dc,e,t)}var hc=Si("ZodObject",(e,t)=>{Sl(),Cs.init(e,t),Pl.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&&Aa(e,t,i,r,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(let e in s)Nr(i.properties,e,Ca(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===sl(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=Ca(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(i.additionalProperties=!1)})(e,t,n,r),ki(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 vc({type:"enum",entries:n,...Xr(t)})}(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(Zr(this._zod.def,{catchall:e}))},passthrough(){return this.clone(Zr(this._zod.def,{catchall:lc()}))},loose(){return this.clone(Zr(this._zod.def,{catchall:lc()}))},strict(){return this.clone(Zr(this._zod.def,{catchall:uc()}))},strip(){return this.clone(Zr(this._zod.def,{catchall:void 0}))},extend(e){return function(e,t){if(!Wr(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let n=Mr(e);for(let e of Reflect.ownKeys(t))if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Gr(e,Zr(e._zod.def,{shape:ni(e,t)}))}(this,e)},safeExtend(e){return function(e,t){if(!Wr(t))throw Error("Invalid input to safeExtend: expected a plain object");return Gr(e,Zr(e._zod.def,{shape:ni(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 Lr(n,e,Reflect.ownKeys(Mr(e))),Lr(n,t,Reflect.ownKeys(Mr(t))),Gr(e,Zr(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 Lr(i,e,ti(e,t)),Gr(e,Zr(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(ti(e,t)),o={};return Lr(o,e,Reflect.ownKeys(Mr(e)).filter(e=>!i.has(e))),Gr(e,Zr(n,{shape:o,checks:[]}))}(this,e)},partial(...e){return ri(kc,this,e[0])},exactPartial(...e){return ri(Oc,this,e[0],"exactPartial")},required(...e){return function(e,t,n){let r=n?new Set(ti(t,n)):void 0,i={};return Lr(i,t,Reflect.ownKeys(Mr(t)),(t,n)=>r&&!r.has(n)?t:new e({type:"nonoptional",innerType:t})),Gr(t,Zr(t._zod.def,{shape:i}))}(zc,this,e[0])}});function fc(e,t){let n={type:"object",shape:e??{},...Xr(t)};return new hc(n)}var mc=Si("ZodUnion",(e,t)=>{Ns.init(e,t),Pl.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)=>Ca(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 gc(e,t){return new mc({type:"union",options:e,...Xr(t)})}var yc=Si("ZodIntersection",(e,t)=>{js.init(e,t),Pl.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def,o=Ca(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=Ca(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 vc=Si("ZodEnum",(e,t)=>{Ds.init(e,t),Pl.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{let r=zr(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 vc({...t,checks:[],...Xr(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 vc({...t,checks:[],...Xr(r),entries:i})}});var bc=Si("ZodLiteral",(e,t)=>{Ls.init(e,t),Pl.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(Aa(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if("bigint"==typeof s){if(Aa(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 wc(e,t){return new bc({type:"literal",values:Array.isArray(e)?e:[e],...Xr(t)})}var _c=Si("ZodTransform",(e,t)=>{Sl(),Zs.init(e,t),Pl.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{Aa(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 zi(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(hi(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(hi(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});var kc=Si("ZodOptional",(e,t)=>{Js.init(e,t),Pl.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cl(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function xc(e){return new kc({type:"optional",innerType:e})}var Oc=Si("ZodExactOptional",(e,t)=>{qs.init(e,t),Pl.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cl(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var Ec=Si("ZodNullable",(e,t)=>{Vs.init(e,t),Pl.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def,o=Ca(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 $c(e){return new Ec({type:"nullable",innerType:e})}var Sc=Si("ZodDefault",(e,t)=>{Ws.init(e,t),Pl.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;Ca(i.innerType,t,r),t.seen.get(e).ref=i.innerType;let o=ll(i.defaultValue,e,t,n,r);o!==al&&(n.default=o)})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});var Pc=Si("ZodPrefault",(e,t)=>{Bs.init(e,t),Pl.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;if(Ca(i.innerType,t,r),t.seen.get(e).ref=i.innerType,"input"!==t.io)return;let o=ll(i.defaultValue,e,t,n,r);o!==al&&(n._prefault=o)})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var zc=Si("ZodNonOptional",(e,t)=>{Ks.init(e,t),Pl.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;Ca(i.innerType,t,r),t.seen.get(e).ref=i.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var Ic=Si("ZodCatch",(e,t)=>{Ys.init(e,t),Pl.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i,o=e._zod.def;Ca(o.innerType,t,r),t.seen.get(e).ref=o.innerType;try{i=o.catchValue(void 0)}catch{return void Aa(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 Tc=Si("ZodPipe",(e,t)=>{Qs.init(e,t),Pl.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;Ca(s,t,r),t.seen.get(e).ref=s})(e,t,0,r),e.in=t.in,e.out=t.out});function Ac(e,t){return new Tc({type:"pipe",in:e,out:t})}var Cc=Si("ZodReadonly",(e,t)=>{ta.init(e,t),Pl.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{let i=e._zod.def;Ca(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 Rc=Si("ZodCustom",(e,t)=>{ra.init(e,t),Pl.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{Aa(e,t,n,r,"Custom types cannot be represented in JSON Schema")})(e,t,n,r)});var Nc,jc=fc({protocolVersion:Tl(),engineVersion:Tl(),buildSha:Tl(),abi:Tl()}),Mc=fc({backend:Tl(),displayServer:Tl().nullable().optional(),capture:sc(),input:sc(),ax:sc(),backgroundWindowInput:sc(),cursorOverlay:sc().default(!1),deliveryModes:pc(Tl()),capturePermission:Tl(),inputPermission:Tl(),axPermission:Tl(),displayCount:function(e,t){return new e(ba({type:"number",checks:[],...Xr(t)}))}(nc,Nc).int().nonnegative(),focusGuard:sc(),stopPath:Tl(),stopReason:Tl().nullable().optional(),integrityLevel:Tl().nullable().optional(),screenLocked:sc(),displayAsleep:sc().default(!1)}),Uc=fc({id:gc([wc(1),wc(2)]),result:lc().optional(),error:lc().optional()});var Dc=(e,t,n)=>Sr(e,[...t],{stdio:"pipe",windowsHide:!0,detached:!0,env:n});function Lc(e,t,n,r=Dc){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())},c=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),u.close(),i.stdin.destroy(),i.stdout.destroy(),i.stderr.destroy(),i.unref(),void 0!==i.pid)if("win32"===process.platform){let e=Sr("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 u=Pr({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=Uc.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=jc.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!==Y)return{ok:!1,code:"abi-mismatch",message:`desktop engine ABI mismatch at ${n}: expected abi ${Q} protocol ${Y}, engine reported abi ${r.data.abi} protocol ${r.data.protocolVersion}`};let i=Mc.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(c);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 Zc(e,t,n={}){let r=vr(e,t,wr(t),n);if(!("path"in r))return"OS permissions: unknown until first use (no usable installed engine)";let i=await Lc(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 Fc(e){let t=e.engineChild??_r(),n=new $r({createChild:t(e.settings.enginePath),onError:t=>e.onEngineError(function(e){return e instanceof yt?e.diagnostic.code:e instanceof ie?"abi-mismatch":e instanceof kt?null!==e.data&&"code"in e.data?e.data.code:"other":e instanceof _t?e.code:"other"}(t)),onPermissionRequired:e.onPermissionRequired,...void 0===e.fullAccess?{}:{fullAccess:e.fullAccess}}),r=new v({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??ar;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 c;e.signal.addEventListener("abort",a,{once:!0}),Promise.resolve(r("Allow foreground computer control?",(c=e.reason,`${c}\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:tr(i),computerActionsTool:rr(i),describeEngineSource:kr,describeEnginePermissions:Zc}}export{Fc as createComputerUseRuntime};