@hallohuman/hightea 0.1.31 → 0.1.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +26 -20
- package/dist/chunk-3emak1d3.js +2 -0
- package/dist/chunk-3w7svm2r.js +2 -0
- package/dist/chunk-4gpw7vjp.js +139 -0
- package/dist/{chunk-5s85pw9m.js → chunk-88mhcx5q.js} +1 -1
- package/dist/chunk-9fxpgay8.js +9 -0
- package/dist/chunk-a1vwy98c.js +1 -0
- package/dist/chunk-axj8ef03.js +1 -0
- package/dist/chunk-dw3tmpqv.js +1 -0
- package/dist/chunk-e9s05rg6.js +4 -0
- package/dist/chunk-evg5apz3.js +2 -0
- package/dist/chunk-jaf9mk6s.js +2 -0
- package/dist/{chunk-r9yjtfhp.js → chunk-kjkww5cr.js} +4 -4
- package/dist/chunk-kq5y08g7.js +5 -0
- package/dist/chunk-ntj1fcak.js +1 -0
- package/dist/chunk-p1142ccr.js +1 -0
- package/dist/chunk-q669464j.js +13 -0
- package/dist/chunk-tay0pyz4.js +58 -0
- package/dist/chunk-vzkbknwq.js +5 -0
- package/dist/chunk-ym5anbc7.js +5 -0
- package/dist/plugin/plugin.json +4 -1
- package/dist/plugin/plugin.mjs +36 -36
- package/package.json +1 -1
- package/dist/chunk-19pwmgzg.js +0 -5
- package/dist/chunk-5zb06f9b.js +0 -2
- package/dist/chunk-69dva4cx.js +0 -58
- package/dist/chunk-8rbp82rh.js +0 -139
- package/dist/chunk-8x5daqht.js +0 -1
- package/dist/chunk-9pv1nvfv.js +0 -5
- package/dist/chunk-db8mr7mp.js +0 -1
- package/dist/chunk-dkzzzkex.js +0 -13
- package/dist/chunk-f04t1q6v.js +0 -2
- package/dist/chunk-gcqhggbh.js +0 -1
- package/dist/chunk-jdzvh3gk.js +0 -1
- package/dist/chunk-p616vcdm.js +0 -4
- package/dist/chunk-xj3c5jgm.js +0 -5
- package/dist/chunk-xy8j3npr.js +0 -1
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{_,A,l,a,d,u,p,w}from"./chunk-tay0pyz4.js";import{r}from"./chunk-evg5apz3.js";import{readdir as ue,readFile as q,realpath as Te,rm as hn}from"node:fs/promises";import{createRequire as xt}from"node:module";import{homedir as Ft,hostname as Kt}from"node:os";import{basename as ie,dirname as L,isAbsolute as In,join as J,resolve as jt}from"node:path";import{fromEnvRef as Gt,isRecord as U,readJsonObject as On,readSecret as Bt,secretRef as Mt,writeJsonAtomic as Ae}from"@ahpd/sdk";import{fileVault as Vt}from"@ahpd/server/dist/vault.js";import{createHash as $e,randomBytes as En}from"node:crypto";import{constants as ne}from"node:fs";import{link as An,lstat as he,mkdir as Ue,mkdtemp as Hn,open as Pe,realpath as Rn,rm as kn}from"node:fs/promises";import{dirname as ae,join as M}from"node:path";import{isDeepStrictEqual as Je}from"node:util";import{fileVault as Le}from"@ahpd/server/dist/vault.js";function v(e){throw Error(e)}function xe(e){return e!==null&&typeof e==="object"&&"code"in e&&typeof e.code==="string"?e.code:void 0}async function Y(e){await Ue(e,{mode:448}).catch((s)=>{if(xe(s)!=="EEXIST")v("HOST_JOIN_CUSTODY_IO")});let t=await he(e);if(!t.isDirectory()||t.uid!==process.getuid?.()||(t.mode&63)!==0)v("HOST_JOIN_UNSAFE_PATH")}async function bn(e){let t=await Pe(e,ne.O_RDONLY|ne.O_DIRECTORY|ne.O_NOFOLLOW);try{await t.sync()}finally{await t.close()}}async function Z(e){let t=await Pe(e,ne.O_RDONLY|ne.O_NOFOLLOW);try{await t.sync()}finally{await t.close()}for(let s=ae(e);;s=ae(s))if(await bn(s),s===ae(s))break}function pe(e){if(typeof e.origin!=="string"||typeof e.workspaceSlug!=="string"||typeof e.code!=="string"||typeof e.pluginVersion!=="string"||typeof e.ahpdVersion!=="string")v("HOST_JOIN_INVALID_INTENT");let t;try{t=new URL(e.origin)}catch{return v("HOST_JOIN_INVALID_INTENT")}let s=l(e.code);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/"||!s||!e.workspaceSlug||/[\s/\\?#]/u.test(e.workspaceSlug)||!e.pluginVersion||!e.ahpdVersion)v("HOST_JOIN_INVALID_INTENT");if(e.name!==void 0&&(typeof e.name!=="string"||e.name.trim()===""||e.name.length>64||[...e.name].some((y)=>{let f=y.codePointAt(0)??0;return f<32||f===127})))v("HOST_JOIN_INVALID_INTENT");if(e.app!==void 0&&!A(e.app))v("HOST_JOIN_INVALID_INTENT");if(e.hostId!==void 0&&(typeof e.hostId!=="string"||!/^[A-Za-z0-9_.:-]{1,128}$/u.test(e.hostId)))v("HOST_JOIN_INVALID_INTENT");if(e.ownerConfiguration===null&&e.app===void 0)v("HOST_JOIN_INVALID_INTENT");let c;try{c=e.ownerConfiguration===null?null:JSON.parse(JSON.stringify(e.ownerConfiguration))}catch{return v("HOST_JOIN_INVALID_INTENT")}if(c!==null&&(typeof c!=="object"||!Je(c,e.ownerConfiguration)))v("HOST_JOIN_INVALID_INTENT");return{...e,origin:t.origin,code:s,ownerConfiguration:c}}async function Fe(e,t){let s=pe(t),c=await je(e),y=M(c,"hightea"),f=M(y,"claims"),I=$e("sha256").update(JSON.stringify([s.origin,s.workspaceSlug,s.code])).digest("hex"),O=M(f,I),S=M(O,"ahpd");try{for(let T of[y,f,O,S])await Y(T);let E=M(S,"vault.json"),h=await Hn(M(S,".claim-"));try{let T=M(h,"vault.json"),b=Le({file:T});await b.set("host:hightea",`Bearer ${En(32).toString("base64url")}`),await b.set("host:hightea-join",JSON.stringify({schema:1,...s}));try{await An(T,E)}catch(D){if(xe(D)!=="EEXIST")v("HOST_JOIN_CUSTODY_PUBLICATION_FAILED")}let{authorization:H,credentialHash:k,intent:F}=await Ge(E);if(F.origin!==s.origin||F.workspaceSlug!==s.workspaceSlug||F.code!==s.code||F.app!==s.app||F.hostId!==s.hostId||!Je(F.ownerConfiguration,s.ownerConfiguration))v("HOST_JOIN_CLAIM_CONFLICT");return await Z(E),{home:O,vaultFile:E,authorization:H,credentialHash:k,intent:F}}finally{await kn(h,{recursive:!0})}}catch(E){if(E instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(E.message))throw E;return v("HOST_JOIN_CUSTODY_IO")}}async function Ke(e,t,s){let c=pe(s);if(c.hostId===void 0)v("HOST_JOIN_INVALID_INTENT");try{let y=await je(e),f=M(y,"hightea"),I=M(f,"claims");if(ae(t)!==I)v("HOST_JOIN_NO_CLAIM_FOR_HOST");let O=M(t,"ahpd");for(let h of[f,I,t,O])await Y(h);let S=M(O,"vault.json"),E=await Ge(S);if(E.intent.origin!==c.origin||E.intent.workspaceSlug!==c.workspaceSlug||E.intent.hostId!==void 0&&c.hostId!==E.intent.hostId)v("HOST_JOIN_CLAIM_CONFLICT");return await Z(S),{home:t,vaultFile:S,authorization:E.authorization,credentialHash:E.credentialHash,intent:c}}catch(y){if(y instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(y.message))throw y;return v("HOST_JOIN_NO_CLAIM_FOR_HOST")}}async function je(e){try{await Ue(e,{recursive:!0,mode:448});let t=await he(e);if(!t.isDirectory()||t.uid!==process.getuid?.()||(t.mode&18)!==0)v("HOST_JOIN_UNSAFE_PATH");return await Rn(e)}catch{return v("HOST_JOIN_UNSAFE_PATH")}}async function Ge(e){let t=await he(e);if(!t.isFile()||t.uid!==process.getuid?.()||(t.mode&511)!==384)v("HOST_JOIN_UNSAFE_PATH");let s=Le({file:e}),c=await s.get("host:hightea"),y=await s.get("host:hightea-join");if(!c||!/^Bearer [A-Za-z0-9_-]{43}$/u.test(c)||!y)v("HOST_JOIN_CLAIM_CORRUPT");let f;try{f=JSON.parse(y)}catch{return v("HOST_JOIN_CLAIM_CORRUPT")}if(!f||typeof f!=="object"||!("schema"in f)||f.schema!==1)v("HOST_JOIN_CLAIM_CORRUPT");let I;try{I=pe(f)}catch{return v("HOST_JOIN_CLAIM_CORRUPT")}return{authorization:c,credentialHash:`sha256:${$e("sha256").update(c.slice(7),"utf8").digest("hex")}`,intent:I}}import{link as vn,lstat as Cn,mkdtemp as Dn,rm as $n}from"node:fs/promises";import{join as te}from"node:path";import{isDeepStrictEqual as Un}from"node:util";import{isRecordSlug as Pn,readJsonObject as Jn,writeJsonAtomic as Be}from"@ahpd/sdk";async function Me(e,t){return We(e,te(e.home,"ahpd"),"config.json",t)}async function Ve(e,t){if(!Pn(t.id))throw Error("HOST_JOIN_CONFIG_CONFLICT");let s=te(e.home,"ahpd","agents");await Y(s),await We(e,s,`${t.id}.json`,{...t})}async function We(e,t,s,c){let y=te(t,s),f;try{if(JSON.stringify(c).includes(e.authorization))throw Error("HOST_JOIN_CONFIG_SECRET");f=await Dn(te(t,".config-"));let I=te(f,"config.json");Be(I,c,{mode:384});try{await vn(I,y)}catch(h){if(!h||typeof h!=="object"||!("code"in h)||h.code!=="EEXIST")throw Error("HOST_JOIN_CONFIG_PUBLICATION_FAILED")}let O=await Cn(y);if(!O.isFile()||O.uid!==process.getuid?.()||(O.mode&511)!==384)throw Error("HOST_JOIN_UNSAFE_PATH");let S=Jn(y);if(!S.ok)throw Error("HOST_JOIN_CONFIG_CORRUPT");let E={};for(let[h,T]of Object.entries(c)){let b=h==="unattendedAutoApprove"&&T===!1||h==="pluginMarketplaces"&&Array.isArray(T)&&T.length===0;if(s==="config.json"&&b&&!Object.hasOwn(S.value,h)){E[h]=T;continue}if(!Un(S.value[h],T))throw Error("HOST_JOIN_CONFIG_CONFLICT")}if(Object.keys(E).length>0)Be(y,{...S.value,...E},{mode:384});return await Z(y),y}catch(I){if(I instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(I.message))throw I;throw Error("HOST_JOIN_CONFIG_IO")}finally{if(f!==void 0)await $n(f,{recursive:!0})}}import{isRecord as W}from"@ahpd/sdk";class re extends Error{kind;status;serverCode;constructor(e,t,s){super(e);this.kind=e;this.status=t;this.serverCode=s}}function Ln(e,t){if(e===401||e===403)return"HOST_JOIN_NOT_AUTHORIZED";if(t==="AGENT_HOST_CONFLICT"||t==="HOST_REGISTRATION_CONFLICT")return"HOST_JOIN_AGENT_BOUND";if(t==="HOST_REGISTRATION_UNSETTLED")return"HOST_JOIN_UNSETTLED";return"HOST_JOIN_REJECTED"}async function ze(e){await Z(e.vaultFile);let t=e.intent,s=new Request(`${t.origin}/api/ws/${encodeURIComponent(t.workspaceSlug)}/join/${encodeURIComponent(t.code)}`,{method:"POST",redirect:"error",headers:{"content-type":"application/json"},signal:AbortSignal.timeout(1e4),body:JSON.stringify({credentialHash:e.credentialHash,pluginVersion:t.pluginVersion,ahpdVersion:t.ahpdVersion,...t.name===void 0?{}:{name:t.name},...t.app===void 0?{}:{app:t.app},...t.hostId===void 0?{}:{hostId:t.hostId}})}),c;try{c=await fetch(s)}catch{throw Error("HOST_JOIN_NETWORK_UNKNOWN")}if(c.status===410){let f;try{f=await c.json()}catch{}if(W(f)&&W(f.error)&&f.error.code==="HOST_REGISTRATION_CANCELLED")throw Error("HOST_JOIN_CANCELLED");throw Error("HOST_JOIN_LINK_UNAVAILABLE")}if(c.status>=500){let f;try{f=await c.json()}catch{}let I=W(f)&&W(f.error)&&_(f.error.code)?f.error.code:void 0;if(I==="HOST_REGISTRATION_UNSETTLED")throw new re("HOST_JOIN_UNSETTLED",c.status,I);throw Error("HOST_JOIN_REMOTE_UNAVAILABLE")}if(!c.ok){let f;try{f=await c.json()}catch{}let I=W(f)&&W(f.error)&&_(f.error.code)?f.error.code:void 0;throw new re(Ln(c.status,I),c.status,I)}let y;try{y=await c.json()}catch{throw Error("HOST_JOIN_RECEIPT_INVALID")}if(!W(y)||typeof y.workspaceId!=="string"||!/^ws_[A-Za-z0-9_-]{1,64}$/u.test(y.workspaceId)||typeof y.hostId!=="string"||!/^[A-Za-z0-9_.:-]{1,128}$/u.test(y.hostId)||y.state!=="pending"&&y.state!=="registered"||y.agentMemberId!==void 0&&(typeof y.agentMemberId!=="string"||!/^[A-Za-z0-9_.:-]{1,128}$/u.test(y.agentMemberId)))throw Error("HOST_JOIN_RECEIPT_INVALID");return{workspaceId:y.workspaceId,hostId:y.hostId,state:y.state,...y.agentMemberId===void 0?{}:{agentMemberId:y.agentMemberId}}}import{access as xn,stat as me}from"node:fs/promises";import{constants as Fn}from"node:fs";import{delimiter as Kn,dirname as Ye,isAbsolute as jn,join as Gn}from"node:path";import{fileURLToPath as Bn}from"node:url";import{fromEnvRef as Mn,isRecord as V,isRecordSlug as Vn,readJsonObject as Wn,scopeOf as zn,secretPaths as Yn,secretRef as Zn}from"@ahpd/sdk";import{checkManifest as Xn,checkStandalone as qn,readManifest as Qn,readStandalone as et,resolvePlugin as nt}from"@ahpd/server/dist/plugins.js";function P(e="HOST_JOIN_OWNER_RESOURCE"){throw Error(e)}function Ze(e){let t=Mn(e);if(t!==void 0){if(!process.env[t])P();return!0}let s=Zn(e);if(s===void 0)return!1;return zn(s),!0}async function tt(e){let t=jn(e)?[e]:(process.env.PATH??"").split(Kn).map((s)=>Gn(s,e));for(let s of t)try{if(await xn(s,Fn.X_OK),(await me(s)).isFile())return}catch{}P()}async function oe(e){let t=Wn(e);if(!t.ok)P("HOST_JOIN_OWNER_INPUT");let s=t.value;if(!Array.isArray(s.agents)||s.agents.length===0||!Array.isArray(s.plugins)||s.plugins.length===0||!Array.isArray(s.records))P();let c=new Set,y=new Set,f=[];try{for(let h of s.plugins){let T=typeof h==="string"?{source:h}:h;if(!V(T)||typeof T.source!=="string"||T.enabled===!1)P();let H=nt(T,{cwd:Ye(e),configDir:Ye(e)});if(!H.path||!(await me(H.path)).isFile())P();let k=H.manifestPath?et(H.manifestPath):H.packageDir?Qn(H.packageDir):void 0;if(!k||k.problem||(k.standalone?qn(k):Xn(k,H.packageDir)))P();if(k.name==="@ahpd/bot"||k.name==="bot")P("HOST_JOIN_OWNER_BOT");for(let D of k.contracts?.engines??[])c.add(D);for(let D of k.contracts?.agents??[])y.add(D);if(T.options!==void 0&&!V(T.options))P();let F=V(T.options)?T.options:{};for(let D of Yn(k.optionsSchema??{},F)){let K=F;for(let G of D.split("."))K=V(K)?K[G]:void 0;if(K!==void 0&&!Ze(K))P("HOST_JOIN_OWNER_SECRET")}f.push({...T,source:H.manifestPath??H.packageDir??H.path})}let I=[],O=new Set(y);for(let h of s.records){if(!V(h)||typeof h.id!=="string"||!Vn(h.id)||O.has(h.id)||typeof h.engine!=="string"||!c.has(h.engine)||typeof h.owner!=="string"||typeof h.name!=="string"||!V(h.config)||h.mode!==void 0&&h.mode!=="enabled")P();if(h.model!==void 0&&(typeof h.model!=="string"||h.model.trim()===""))P();if(h.engine==="acp"&&typeof h.config.command!=="string")P();if(h.config.command!==void 0){if(typeof h.config.command!=="string"||!h.config.command)P();await tt(h.config.command)}if(h.config.env!==void 0){if(!V(h.config.env))P();for(let T of Object.values(h.config.env))if(!Ze(T))P("HOST_JOIN_OWNER_SECRET")}O.add(h.id),I.push(h)}let S=[],E=new Set;for(let h of s.agents){if(!Array.isArray(h)||h.length!==2||typeof h[0]!=="string"||!h[0]||E.has(h[0])||!V(h[1])||typeof h[1].provider!=="string"||!O.has(h[1].provider)||typeof h[1].workingDirectory!=="string")P();let T=new URL(h[1].workingDirectory);if(T.protocol!=="file:"||T.hostname||!(await me(Bn(T))).isDirectory())P();if(h[1].settings!==void 0&&!V(h[1].settings))P();E.add(h[0]),S.push([h[0],{provider:h[1].provider,workingDirectory:T.href,...h[1].settings===void 0?{}:{settings:h[1].settings}}])}return{agents:S,plugins:f,records:I}}catch(I){if(I instanceof Error&&/^HOST_JOIN_OWNER_[A-Z_]+$/u.test(I.message))throw I;return P()}}import{constants as rt}from"node:fs";import{access as ot,mkdir as it,stat as st,writeFile as at}from"node:fs/promises";import{createRequire as dt}from"node:module";import{dirname as qe,resolve as Qe}from"node:path";import{pathToFileURL as ct}from"node:url";class de extends Error{file;entry;constructor(e,t){super("HOST_JOIN_OWNER_CONFIG_NEEDS_AGENT");this.file=e;this.entry=t}}function lt(){try{return qe(dt(import.meta.url).resolve("@ahpd/agent-acp/package.json"))}catch{throw Error("HOST_JOIN_AGENT_PLUGIN_MISSING")}}function en(e,t,s){return[t,{provider:e.id,workingDirectory:ct(Qe(s)).href}]}function ut(e,t,s){return JSON.stringify(en(e,t,s))}function gt(e,t){let[s,c]=en(e.app,e.agentMemberId,e.workingDirectory);return`${JSON.stringify({plugins:[t],records:[{id:e.app.id,engine:"acp",owner:"host",name:e.app.name,config:{command:e.app.command}}],agents:[[s,c]]},null,2)}
|
|
2
|
+
`}async function nn(e){let t=Qe(e.file);if(await ot(t,rt.F_OK).then(()=>!0,()=>!1))return Xe(t,e);await it(qe(t),{recursive:!0,mode:448});try{await at(t,gt(e,lt()),{flag:"wx",mode:384})}catch(c){if(c!==null&&typeof c==="object"&&"code"in c&&c.code==="EEXIST")return Xe(t,e);throw Error("HOST_JOIN_OWNER_FILE_IO")}let s=await st(t);if(!s.isFile()||s.uid!==process.getuid?.()||(s.mode&511)!==384)throw Error("HOST_JOIN_UNSAFE_PATH");return oe(t)}async function Xe(e,t){let s=await oe(e);if(s.agents.some(([c])=>c===t.agentMemberId))return s;throw new de(e,ut(t.app,t.agentMemberId,t.workingDirectory))}import{access as Wt}from"node:fs/promises";import{constants as zt}from"node:fs";import{createHash as ft}from"node:crypto";import{lstat as tn,mkdir as ht,mkdtemp as pt,readFile as we,rename as mt,rm as yt,writeFile as ye}from"node:fs/promises";import{isAbsolute as rn,join as j,normalize as ce}from"node:path";var wt="hightea-pipe",Ie="bundle.json";function Oe(e){return j(e,"hightea","plugins")}async function on(e){let t;try{t=await we(j(e,"plugin.json"))}catch{throw Error("HOST_JOIN_PLUGIN_BUNDLE")}let s;try{s=JSON.parse(t.toString("utf8"))}catch{throw Error("HOST_JOIN_PLUGIN_BUNDLE")}let c=typeof s==="object"&&s!==null&&"main"in s?s.main:void 0,y=typeof s==="object"&&s!==null&&"id"in s?s.id:void 0,f=typeof s==="object"&&s!==null&&"version"in s?s.version:void 0;if(y!==wt||typeof f!=="string"||typeof c!=="string"||rn(c)||ce(c).startsWith("..")||ce(c).includes("/")||["plugin.json",Ie].includes(ce(c)))throw Error("HOST_JOIN_PLUGIN_BUNDLE");let I;try{I=await we(j(e,c))}catch{throw Error("HOST_JOIN_PLUGIN_BUNDLE")}return{manifestBytes:t,version:f,main:ce(c),mainBytes:I,sha256:_t(t,I)}}function _t(e,t){return ft("sha256").update(e).update("\x00").update(t).digest("hex")}async function le(e){let t=j(e,".."),s;try{s=JSON.parse(await we(j(t,Ie),"utf8"))}catch(y){return{ok:!1,reason:sn(y)?"missing":"corrupt"}}let c;try{c=await on(t)}catch{return{ok:!1,reason:"corrupt"}}if(typeof s!=="object"||s===null||!("version"in s)||!("sha256"in s)||typeof s.version!=="string"||s.sha256!==c.sha256)return{ok:!1,reason:"corrupt"};return{ok:!0,bundle:{manifest:e,version:s.version,sha256:c.sha256}}}async function Se(e,t,s){if(!rn(e)||!/^[0-9A-Za-z.+-]+$/u.test(s))throw Error("HOST_JOIN_UNSAFE_PATH");let c=await on(t);if(c.version!==s)throw Error("HOST_JOIN_PLUGIN_BUNDLE");try{await ht(e,{recursive:!0,mode:448});let S=await tn(e);if(!S.isDirectory()||S.uid!==process.getuid?.()||(S.mode&18)!==0)throw Error("unsafe")}catch{throw Error("HOST_JOIN_UNSAFE_PATH")}let y=Oe(e);for(let S of[j(e,"hightea"),y])await Y(S);let f=j(y,s),I=j(f,"plugin.json");if(!await It(f)){let S=await pt(j(y,`.${s}-`));try{await ye(j(S,"plugin.json"),c.manifestBytes,{mode:384}),await ye(j(S,c.main),c.mainBytes,{mode:384}),await ye(j(S,Ie),`${JSON.stringify({version:s,sha256:c.sha256})}
|
|
3
|
+
`,{mode:384});try{await mt(S,f)}catch(E){if(!_e(E,"EEXIST")&&!_e(E,"ENOTEMPTY"))throw Error("HOST_JOIN_CONFIG_IO")}}finally{await yt(S,{recursive:!0,force:!0})}}let O=await le(I);if(!O.ok||O.bundle.sha256!==c.sha256||O.bundle.version!==s)throw Error("HOST_JOIN_PLUGIN_BUNDLE_CONFLICT");return O.bundle}async function It(e){try{return await tn(e),!0}catch(t){if(sn(t))return!1;throw Error("HOST_JOIN_UNSAFE_PATH")}}function sn(e){return _e(e,"ENOENT")}function _e(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}import{createPrivateKey as kt,createPublicKey as bt,generateKeyPairSync as vt,sign as po}from"node:crypto";import{appendFile as yo,chmod as Ct,readFile as an,rename as Dt,writeFile as $t}from"node:fs/promises";import{join as dn}from"node:path";var io=Buffer.from("302a300506032b6570032100","hex");import{createHash as St}from"node:crypto";import{existsSync as Tt,readFileSync as Nt}from"node:fs";import{join as Et}from"node:path";var At="trusted-keys.json",m=/^(?=.{1,64}$)[A-Za-z0-9][A-Za-z0-9._-]*(?: [A-Za-z0-9._-]+)*$/u,Ht=/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/u,Rt=(e)=>Buffer.from(e).toString("base64url");function o(e){if(!Ht.test(e))return{error:"TRUST_KEY_INVALID: the public key must be 43 base64url characters (a raw 32-byte Ed25519 key), as the browser's Members page shows it"};return{keyId:Rt(St("sha256").update(Buffer.from(e,"base64url")).digest())}}function g(e){let t=Et(e,At);if(!Tt(t))return{state:"missing",file:t};let s;try{s=JSON.parse(Nt(t,"utf8"))}catch(y){throw Error(`TRUST_FILE_UNREADABLE: ${t} is not JSON (${y.message})`)}let c=s;if(typeof s!=="object"||s===null||c.v!==1||!Array.isArray(c.keys))throw Error(`TRUST_FILE_UNREADABLE: ${t} is not a version 1 list of trusted keys`);for(let y of c.keys){let f=y,I=typeof f.publicKey==="string"?o(f.publicKey):void 0;if(typeof f.name!=="string"||!m.test(f.name)||I===void 0||"error"in I||f.keyId!==I.keyId||typeof f.addedAt!=="string")throw Error(`TRUST_FILE_UNREADABLE: ${t} holds an entry that is not a valid trusted key: ${JSON.stringify(y)}`)}return{state:"read",file:t,keys:c.keys}}var cn="host-signing-key";async function ln(e){try{await an(dn(e,cn))}catch(t){if(t.code==="ENOENT")return{state:"missing"}}try{return{state:"ok",key:await Ut(e)}}catch(t){return{state:"unreadable",reason:t instanceof Error?t.message:String(t)}}}async function Ut(e,t=()=>Date.now()){let s=dn(e,cn),c;try{c=await an(s,"utf8")}catch(O){if(O.code!=="ENOENT")throw Error(`HOST_KEY_UNREADABLE: ${s} exists but cannot be read (${String(O)}); it is never regenerated, fix or remove it by hand`)}if(c===void 0){let O=vt("ed25519").privateKey.export({format:"pem",type:"pkcs8"}).toString(),S=`${s}.${String(process.pid)}.tmp`;await $t(S,O,{mode:384,flag:"wx"}),await Ct(S,384),await Dt(S,s),c=O}let y;try{if(y=kt({key:c,format:"pem"}),y.asymmetricKeyType!=="ed25519")throw Error(`a ${String(y.asymmetricKeyType)} key, not Ed25519`)}catch(O){throw Error(`HOST_KEY_UNREADABLE: ${s} is not an Ed25519 PKCS8 key (${String(O)}); it is never regenerated, fix or remove it by hand`)}let f=bt(y).export({format:"jwk"}).x,I=f===void 0?{error:"no public key"}:o(f);if("error"in I)throw Error(`HOST_KEY_UNREADABLE: ${s}: ${I.error}`);return{privateKey:y,trusted:{name:"this-host",keyId:I.keyId,publicKey:f,addedAt:new Date(t()).toISOString()}}}import{createServer as Pt}from"node:net";var un="hightea";function gn(e){return`http://127.0.0.1:${String(e)}/mcp`}function Jt(e){let t=2166136261;for(let s of new TextEncoder().encode(e))t^=s,t=Math.imul(t,16777619)>>>0;return 40000+t%20000}async function fn(e){let t=Jt(e);for(let s=0;s<200;s+=1){let c=40000+(t-40000+s)%20000;if(await Lt(c))return c}throw Error(`HOST_TOOLS_PORT_UNAVAILABLE: every port from ${String(t)} to ${String(t+199)} on 127.0.0.1 is taken`)}async function Lt(e){let t=Pt();return await new Promise((s)=>{t.once("error",()=>{s(!1)}),t.listen(e,"127.0.0.1",()=>{t.close(()=>{s(!0)})})})}var Yt="hightea host join --origin https://your-deployment --workspace SLUG --code CODE --owner-config /absolute/owner.json",Zt=(e)=>[...e].some((t)=>{let s=t.codePointAt(0)??0;return s<32||s===127});function Xt(e=Kt()){let t=e.trim();return t===""||t.length>64||Zt(t)?void 0:t}var qt="https://hightea.ai/docs/host#owner";class He extends Error{file;constructor(e){super("HOST_JOIN_OWNER_CONFIG_MISSING");this.file=e}}var Qt=(e)=>`no owner config at ${e}: write one listing the plugins, agent records and agents this computer runs — `+`the three fields with an example of each are at ${qt} — then run the same command again. Nothing was redeemed and nothing was written.`,er=(e,t)=>`the owner config at ${e} does not map the agent this computer just created. Add this pair to its "agents" array — `+`${t} — then run the same command again; the registration is pending and resumes.`;class Re extends Error{appName;install;constructor(e,t){super("HOST_JOIN_APP_MISSING");this.appName=e;this.install=t}}var nr=(e)=>`${e.appName} is not on this computer: install it with \`${e.install}\`, then run the same command again. Nothing was redeemed and nothing was written.`,Q={HOST_JOIN_USAGE:`Expected: ${Yt}`,HOST_JOIN_INPUT:"Command input could not be read. Use --help for the supported options.",HOST_JOIN_INVALID_INTENT:"Use an HTTPS deployment origin, workspace slug and valid join code.",HOST_JOIN_OWNER_INPUT:"The --owner-config file must exist and contain a JSON object; its contents were not printed.",HOST_JOIN_OWNER_RESOURCE:"Check the explicit agent mappings, provider plugins, working directories, executables and referenced credentials in --owner-config. No code was redeemed.",HOST_JOIN_OWNER_SECRET:"Replace inline provider secrets with existing ahpd fromEnv or SecretRef values; the referenced resource must be available locally.",HOST_JOIN_OWNER_BOT:"@ahpd/bot is not allowed on a member host (bots run on the server); remove it from this owner's plugin list",HOST_JOIN_UNSAFE_PATH:"The selected configuration path must be owned by this user and private; symlinks and shared files are not used.",HOST_JOIN_CLAIM_CONFLICT:"This claim already holds different deployment or owner settings. Keep its vault and use the original settings to resume.",HOST_JOIN_CLAIM_CORRUPT:"The selected claim vault is invalid. Keep it for recovery; joining will not replace its credential.",HOST_JOIN_NO_CLAIM_FOR_HOST:"This computer holds no claim for that host. Join without --host to register this computer as a new host; --host only extends a host this computer already holds, reusing its credential.",HOST_JOIN_NETWORK_UNKNOWN:"The registration result is unknown. Keep this claim and rerun the same command to recover its receipt.",HOST_JOIN_REMOTE_UNAVAILABLE:"The deployment could not complete registration. Keep this claim and rerun the same command later.",HOST_JOIN_CANCELLED:"The owner cancelled this host registration. Keep the existing claim; request a new join code for another registration.",HOST_JOIN_LINK_UNAVAILABLE:"This join code is expired or unavailable. Keep the existing claim; request a new code if registration was not completed.",HOST_JOIN_REJECTED:"The deployment rejected registration. Check the deployment and workspace; the selected credential was retained.",HOST_JOIN_NOT_AUTHORIZED:"The deployment refused this account for that workspace or agent. Join with the account that owns the agents in --owner-config; the selected credential was retained.",HOST_JOIN_AGENT_BOUND:"The deployment refused this registration; the server code on this line says which case it is. AGENT_HOST_CONFLICT: an agent in --owner-config already belongs to another active host — revoke that host, then mint a new code. HOST_REGISTRATION_CONFLICT: this code was already redeemed by a different host registration — join with the claim that computer already holds, or mint a new code. Never revoke a host on the strength of this line alone; the selected credential was retained.",HOST_JOIN_UNSETTLED:"The workspace did not answer this registration within a minute. The code is unspent and this claim is intact; wait a minute, then run the same command again.",HOST_JOIN_RECEIPT_INVALID:"The deployment returned an invalid registration receipt. Keep this claim and retry against the correct deployment.",HOST_JOIN_CONFIG_CONFLICT:"Existing host configuration has different bindings or required settings. It was preserved; reconcile it with the original claim before retrying.",HOST_JOIN_CONFIG_CORRUPT:"Existing host configuration is invalid JSON. It was preserved for local repair; rerun after repairing it.",HOST_JOIN_CLAIM_VERSION:"This join code's claim was started by another hightea version. Finish it with that version, or request a new join code; nothing was redeemed or written.",HOST_JOIN_PLUGIN_BUNDLE:"This installation's host plugin is missing or unreadable. Reinstall @hallohuman/hightea; no configuration was written.",HOST_JOIN_PLUGIN_BUNDLE_CONFLICT:"The installed host plugin for this version differs from this installation's copy. It was preserved; reinstall the same version or repair that directory. No configuration was written.",HOST_JOIN_AGENT_PLUGIN_MISSING:"This installation cannot find @ahpd/agent-acp, the plugin that runs agent apps. Reinstall @hallohuman/hightea; nothing was redeemed.",HOST_JOIN_APPS_ROW_MISSING:"This installation's app list and the daemon's rows disagree. Reinstall @hallohuman/hightea; nothing was redeemed.",HOST_JOIN_OWNER_FILE_IO:"The owner config could not be written. No existing file was replaced; check the folder's permissions and retry."};function z(e,t){let s=process.env[e]||J(Ft(),t);if(!In(s))throw Error("HOST_JOIN_UNSAFE_PATH");return s}function tr(){let e=xt(import.meta.url).resolve("@ahpd/server/package.json");return{node:process.execPath,main:J(L(e),"dist","main.js")}}var Ne=(e)=>`'${e.replaceAll("'","'\\''")}'`;function se(e,t=tr()){return`XDG_CONFIG_HOME=${Ne(e)} ${Ne(t.node)} ${Ne(t.main)} start`}var rr={JOIN_LINK_INVALID:"the join code is no longer valid",JOIN_LINK_NOT_FOUND:"no such join code in that workspace",ROLE_NOT_ALLOWED:"the join code does not allow this role",NOT_A_MEMBER:"the signed-in account is not a member of that workspace",FORBIDDEN:"an agent in --owner-config belongs to another account",HOST_REGISTRATION_CANCELLED:"the owner cancelled this registration",HOST_REGISTRATION_CONFLICT:"this code was redeemed for a different host registration; a computer that already has a host joins with the claim it already holds",AGENT_HOST_CONFLICT:"an agent already belongs to another active host; revoke that host, then mint a new code",HOST_REGISTRATION_MISSING:"the pending registration is gone",HOST_REGISTRATION_UNSETTLED:"the workspace has not answered the registration within a minute; run the same command again",INVALID_REQUEST:"the deployment did not accept this request's shape",BAD_ORIGIN:"the request came from another site",UNAUTHENTICATED:"the request carried no signed-in account",WORKSPACE_NOT_FOUND:"no such workspace for this account",PEOPLE_LIMIT:"that workspace is at its beta limit of people",AGENTS_LIMIT:"that workspace is at its beta limit of agents"},or={HOST_JOIN_NOT_AUTHORIZED:3,HOST_JOIN_AGENT_BOUND:4,HOST_JOIN_REJECTED:1,HOST_JOIN_UNSETTLED:2};function ir(e){let t=e.serverCode===void 0?"":` The deployment says ${rr[e.serverCode]}.`;return`${e.kind}: ${Q[e.kind]}${t} (HTTP ${e.status}, server code ${e.serverCode??"unrecognised"})`}async function N(e,t){try{let{origin:s,workspace:c,code:y,ownerConfig:f}=e;if(!s||!c||!y||!f)throw Error("HOST_JOIN_USAGE");let I=jt(f),O=await Wt(I,zt.F_OK).then(()=>!0,()=>!1);if(!O&&e.ownerConfigIsDefault!==!0)throw Error("HOST_JOIN_OWNER_INPUT");if(!O&&e.app===void 0)throw new He(I);let S=e.app===void 0?void 0:p(e.app);if(S!==void 0&&!await w(S))throw new Re(S.name,u(S));let E=O?await oe(I):null,h=z("XDG_CONFIG_HOME",".config"),T=z("XDG_DATA_HOME",J(".local","share")),b=Xt(),H={origin:s,workspaceSlug:c,code:y,pluginVersion:t.version,ahpdVersion:"0.15.0-rc.4",ownerConfiguration:E,...b===void 0?{}:{name:b},...e.app===void 0?{}:{app:e.app},...e.hostId===void 0?{}:{hostId:e.hostId}},k;if(e.hostId===void 0)k=await Fe(h,H);else{let B=await n(e.hostId);if("error"in B)throw Error("HOST_JOIN_NO_CLAIM_FOR_HOST");k=await Ke(h,B.claim,H)}if(k.intent.pluginVersion!==t.version)throw Error("HOST_JOIN_CLAIM_VERSION");let F=Vt({file:k.vaultFile}),D=async(B)=>{let Ce=Mt(B),De=Gt(B);if(De!==void 0){if(!process.env[De])throw Error("HOST_JOIN_OWNER_RESOURCE")}else if(Ce!==void 0)try{await Bt(F,Ce)}catch{throw Error("HOST_JOIN_OWNER_RESOURCE")}else if(Array.isArray(B))for(let fe of B)await D(fe);else if(U(B))for(let fe of Object.values(B))await D(fe)};if(E!==null)await D(E);let K=await Se(T,t.directory,t.version),G=await ze(k);if(G.state==="pending")return console.log("Host registration pending. Run the same command again to resume."),2;let ee=S===void 0?E:await nn({file:I,app:S,agentMemberId:_r(G.agentMemberId),workingDirectory:e.workingDirectory??process.cwd()});if(ee===null)throw Error("HOST_JOIN_OWNER_INPUT");if(S!==void 0)await D(ee);for(let B of ee.records)await Ve(k,B);let be=new URL(`/gateway/${encodeURIComponent(G.workspaceId)}/host`,k.intent.origin);be.protocol="wss:";let ve=await fn(k.home);return await Me(k,{host:"127.0.0.1",updateCheck:!1,httpApi:!1,modelApi:!1,mcpTools:"none",unattendedAutoApprove:!1,pluginMarketplaces:[],mcpServers:{[un]:{type:"http",url:gn(ve)}},plugins:[...ee.plugins,{source:K.manifest,grants:[...Sn],options:{cloudUrl:be.href,workspaceId:G.workspaceId,agents:ee.agents,mcpUrl:new URL(`/w/${encodeURIComponent(G.workspaceId)}`,k.intent.origin).href,hostToolsPort:ve,headers:{[a]:G.hostId,authorization:{$secret:"host:hightea"}}}}]}),console.log(`Host registered; local configuration saved. Start it with: ${se(k.home)}`),0}catch(s){if(s instanceof re)return console.error(ir(s)),or[s.kind];if(s instanceof He)return console.error(Qt(s.file)),1;if(s instanceof de)return console.error(er(s.file,s.entry)),1;if(s instanceof Re)return console.error(nr(s)),1;let c=s instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(s.message)?s.message:"HOST_JOIN_INPUT";return console.error(`${c}: ${Q[c]??"Local claim storage could not be safely published or flushed. Keep the existing files, check filesystem access and retry; no replacement credential was selected."}`),1}}function ge(e){return U(e)&&U(e.options)&&typeof(e.options.workspaceId??e.options.houseId)==="string"&&U(e.options.headers)&&typeof(e.options.headers[a]??e.options.headers[d])==="string"}async function ke(e){let t=J(e,"ahpd","config.json"),s;try{s=await q(t,"utf8")}catch(E){return typeof E==="object"&&E!==null&&"code"in E&&E.code==="ENOENT"?{claim:e,state:"pending"}:{claim:e,state:"unreadable",config:t}}let c;try{c=JSON.parse(s)}catch{return{claim:e,state:"unreadable",config:t}}let f=(U(c)&&Array.isArray(c.plugins)?c.plugins:[]).find(ge);if(f===void 0||typeof f.source!=="string"||!U(f.options)||!U(f.options.headers))return{claim:e,state:"unreadable",config:t};let I=f.source,O=await le(I),S=!O.ok?O.reason:O.bundle.version===ie(L(I))?"ok":"wrong-version";return{claim:e,state:"joined",config:t,start:se(e),pluginBundle:I,bundle:S,...O.ok?{pluginVersion:O.bundle.version}:{},workspaceId:String(f.options.workspaceId??f.options.houseId),hostId:String(f.options.headers[a]??f.options.headers[d]),...typeof f.options.cloudUrl==="string"?{gateway:f.options.cloudUrl}:{},signingKey:await ar(L(t)),...await sr(L(t))}}async function sr(e){let t=await Tn(e);if(t===void 0||t instanceof Error)return{};return{heldBundle:{from:t.from,toVersion:t.toVersion,connected:await Nn(e)===t.toVersion}}}async function ar(e){let t=await ln(e);if(t.state==="ok")return{state:"ok",keyId:t.key.trusted.keyId,publicKey:t.key.trusted.publicKey};return t}function dr(e){if(e===void 0||e.state==="missing")return"(made on this host's first start)";if(e.state==="unreadable")return`unreadable: ${e.reason}`;return`${e.keyId} public ${e.publicKey} (another machine trusts it with: hightea host trust add <name> ${e.publicKey})`}function cr(e,t){if(e===void 0)return"";return e===t?`, version ${e}`:`, version ${e}; this CLI is ${t}`}async function R(e){let t;try{t=J(z("XDG_CONFIG_HOME",".config"),"hightea","claims")}catch{return console.error(`HOST_STATUS_UNSAFE_PATH: ${Q.HOST_JOIN_UNSAFE_PATH}`),1}let s=[];try{s=(await ue(t)).filter((f)=>!f.startsWith(".")).sort()}catch(f){if(!(typeof f==="object"&&f!==null&&("code"in f)&&f.code==="ENOENT"))return console.error(`HOST_STATUS_UNREADABLE: cannot list ${t}`),1}let c=await Promise.all(s.map((f)=>ke(J(t,f))));if(e.json)console.log(JSON.stringify({version:e.version,claims:t,hosts:c},null,2));else for(let f of c)if(f.state==="pending")console.log(`pending ${f.claim} (registration not finished; rerun the same join command)`);else if(f.state==="unreadable")console.log(`unreadable ${f.config}`);else console.log([`joined workspace ${f.workspaceId} host ${f.hostId}`,` gateway ${f.gateway??"(none)"}`,` config ${f.config}`,` start ${f.start}`,` plugin ${f.pluginBundle} (${f.bundle}${cr(f.pluginVersion,e.version)})`,` key ${dr(f.signingKey)}`,...f.heldBundle===void 0?[]:[` held ${f.heldBundle.from} until this host connects at ${f.heldBundle.toVersion}${f.heldBundle.connected?" (it has; the next `hightea host update` removes it)":""}`]].join(`
|
|
4
|
+
`));let y=c.filter((f)=>f.state==="joined"&&f.bundle!=="ok");for(let f of y){let I=f.bundle==="missing"?"is missing":f.bundle==="corrupt"?"does not match its recorded hash":`records version ${f.pluginVersion}, not the version its directory names`,O=f.bundle==="wrong-version"?"Restore the bundle that directory name records, or re-join with a new code to install this CLI's bundle.":"Re-join with a new code to install this version's bundle.";console.error(`HOST_STATUS_PLUGIN_BUNDLE: the plugin bundle ${f.pluginBundle} ${I}; the host cannot load it. ${O}`)}if(y.length>0)return 2;if(c.some((f)=>f.state==="unreadable"))return console.error("HOST_STATUS_CONFIG_UNREADABLE: a saved host configuration could not be read; it was left unchanged."),1;if(!c.some((f)=>f.state==="joined"))return console.error(`HOST_STATUS_NONE: no joined host under ${t}.`),1;return 0}var Sn=["session:write","session:state","session:list","chat:turns","agent:list"],Ee=["service:watch","service:logs","service:put","service:remove","service:start","service:stop","service:restart","service:accept"],pn=["services:list","services:get","services:put","services:delete","services:control"],lr=/(^|[\\/])(@hallohuman[\\/]hightea-services|@ahpd[\\/](services|deploy)|packages[\\/](services|deploy)|(services|deploy)[\\/]plugin)([\\/]|$)/u;function ur(e){if(!U(e)||typeof e.source!=="string"||!U(e.options))return!1;if(lr.test(e.source))return!0;return Array.isArray(e.options.files)&&typeof e.options.socket==="string"}function gr(e){if(ie(e)!=="ahpd")return;let t=L(e);if(ie(t)!=="xdg-config")return;let s=ie(L(t));return s===""||s==="."||s==="/"?void 0:s}async function fr(e){let t;try{t=JSON.parse(await q(e.config,"utf8"))}catch{return}let s=U(t)&&Array.isArray(t.plugins)?t.plugins:[],c=s.find(ge),y=s.some(ur),f=c!==void 0&&U(c.options)&&U(c.options.headers)?String(c.options.headers[a]??c.options.headers[d]??""):"",I=gr(e.configDir),O=f||e.hostIds[0]||(y?I:void 0);if(O===void 0||O==="")return;let S=c!==void 0&&U(c.options)?String(c.options.workspaceId??c.options.houseId??""):"",E=c!==void 0&&U(c.options)&&typeof c.options.cloudUrl==="string"?c.options.cloudUrl:void 0,h=[...new Set([O,...e.hostIds,...I===void 0?[]:[I]])].filter((T)=>T!=="");return{row:e,names:h,hasServices:y,host:{claim:L(e.configDir),configDir:e.configDir,config:e.config,workspaceId:S,hostId:O,...E===void 0?{}:{gateway:E}}}}function mn(e,t){let s=t.filter((y)=>y.names.includes(e.hostId));if(s.length>1)return{error:`SERVICE_HOST_AMBIGUOUS: ${String(s.length)} running ahpd processes serve ${e.hostId} (${s.map((y)=>`${String(y.row.pid)} at ${y.row.configDir}`).join(", ")}); stop the extras or name one with --config-dir`};let c=s[0];if(c===void 0)return e;return{...e,claim:c.host.claim,configDir:c.host.configDir,config:c.host.config,...c.host.workspaceId!==""?{workspaceId:c.host.workspaceId}:{},...c.host.gateway!==void 0?{gateway:c.host.gateway}:{}}}async function n(e,t){let s;try{s=J(z("XDG_CONFIG_HOME",".config"),"hightea","claims")}catch{return{error:`SERVICE_UNSAFE_PATH: ${Q.HOST_JOIN_UNSAFE_PATH}`}}let c=[];try{c=(await ue(s)).filter((h)=>!h.startsWith(".")).sort()}catch(h){if(!(typeof h==="object"&&h!==null&&("code"in h)&&h.code==="ENOENT"))return{error:`SERVICE_HOST_UNREADABLE: cannot list ${s}`}}let y=await Promise.all(c.map((h)=>ke(J(s,h)))),f=y.filter((h)=>h.state==="joined"),I=t?.runningAhpds!==void 0?await t.runningAhpds():[],O=(await Promise.all(I.map(fr))).filter((h)=>h!==void 0),S=e?.trim();if(S!==void 0&&S!==""){let h=f.find((H)=>H.hostId===S);if(h!==void 0)return mn(yn(h),O);let T=O.filter((H)=>H.names.includes(S));if(T.length>1)return{error:`SERVICE_HOST_AMBIGUOUS: ${String(T.length)} running ahpd processes serve ${S} (${T.map((H)=>`${String(H.row.pid)} at ${H.row.configDir}`).join(", ")}); stop the extras or name one with --config-dir`};if(T.length===1)return T[0].host;let b=[...new Set([...f.map((H)=>H.hostId),...O.map((H)=>H.host.hostId)])];return{error:`SERVICE_HOST_UNKNOWN: no joined host ${S} on this machine (joined here: ${b.join(", ")||"none"})`}}if(f.length===1)return mn(yn(f[0]),O);if(f.length>1)return{error:`SERVICE_HOST_AMBIGUOUS: this machine holds ${f.length} joined hosts (${f.map((h)=>h.hostId).join(", ")}); name one with --host <id>`};if(O.length>0){let h=O.filter((b)=>b.hasServices),T=h.length>0?h:O;if(T.length===1)return T[0].host;return{error:`SERVICE_HOST_AMBIGUOUS: this machine holds ${T.length} joined hosts (${T.map((b)=>b.host.hostId).join(", ")}); name one with --host <id>`}}let E=y.find((h)=>h.state==="unreadable");return{error:E===void 0?`SERVICE_NO_HOST: no joined host under ${s}; join this machine with \`hightea host join\` first`:`SERVICE_HOST_UNREADABLE: ${E.config} could not be read; it was left unchanged`}}function yn(e){let t=e.config;return{claim:e.claim,configDir:L(t),config:t,workspaceId:e.workspaceId,hostId:e.hostId,...e.gateway===void 0?{}:{gateway:e.gateway}}}async function i(e="/proc"){let t;try{t=await ue(e)}catch{return[]}let s=[],c=new Set;for(let y of t){if(!/^\d+$/u.test(y))continue;let f;try{f=(await q(J(e,y,"cmdline"),"utf8")).split("\x00").filter((k)=>k!=="")}catch{continue}let I=f.indexOf("--config-file"),O=I<0?void 0:f[I+1];if(O===void 0||!In(O)||c.has(O))continue;c.add(O);let S=L(O),E=(k)=>{let F=f.indexOf(k),D=F<0?void 0:f[F+1];return D===void 0||D===""?void 0:D},h=E("--port"),T=h!==void 0&&/^\d{1,5}$/u.test(h)?Number(h):void 0,b=E("--connection-token-file"),H=E("--host")??"127.0.0.1";s.push({pid:Number(y),config:O,configDir:S,hostIds:await hr(O),host:H,...T===void 0?{}:{port:T},...b===void 0?{}:{connectionTokenFile:b}})}return s}async function hr(e){let t;try{t=JSON.parse(await q(e,"utf8"))}catch{return[]}if(!U(t)||!Array.isArray(t.plugins))return[];let s=new Set;for(let c of t.plugins){if(!U(c)||!U(c.options)||!U(c.options.headers))continue;let y=c.options.headers[a]??c.options.headers[d];if(typeof y==="string"&&y!=="")s.add(y)}return[...s]}async function x(e){try{r(e.caller,"grant")}catch(H){return console.error(`${H.message}; nothing was changed`),1}let t=await n(e.host);if("error"in t)return console.error(t.error),1;let s=On(t.config);if(!s.ok)return console.error(`SERVICE_CONFIG_UNREADABLE: ${t.config} could not be read as a JSON object; it was left unchanged`),1;let c=Array.isArray(s.value.plugins)?s.value.plugins:[],y=c.findIndex(ge),f=c[y];if(f===void 0)return console.error(`SERVICE_CONFIG_UNREADABLE: ${t.config} holds no Hightea plugin entry; it was left unchanged`),1;if(f.grants!==void 0&&!(Array.isArray(f.grants)&&f.grants.every((H)=>typeof H==="string")))return console.error(`SERVICE_CONFIG_UNREADABLE: the Hightea plugin entry's grants in ${t.config} are not a list of grants; it was left unchanged`),1;let I=f.grants??[],O=[...Ee,...pn],S=pn,E=I.filter((H)=>!S.includes(H)),h=e.enable?[...E,...Ee.filter((H)=>!E.includes(H))]:I.filter((H)=>!O.includes(H)),T=`Hightea managing this machine's services (host ${t.hostId})`;if(h.length===I.length&&h.every((H,k)=>H===I[k]))return console.log(`${T} is already ${e.enable?"enabled":"disabled"}; ${t.config} was left unchanged.`),0;let b=c.slice();b[y]={...f,grants:h};try{Ae(t.config,{...s.value,plugins:b},{mode:384})}catch(H){return console.error(`SERVICE_CONFIG_UNWRITABLE: ${t.config}: ${H.message}`),1}return console.log(`${T} is now ${e.enable?"enabled":"disabled"}: ${e.enable?"added":"removed"} ${Ee.join(", ")} in ${t.config}.`),console.log(`It takes effect when this host's ahpd next loads its configuration; restart it with: ${se(t.claim)}`),0}function wn(e){let t=/^(\d+)\.(\d+)\.(\d+)(-dev\.[0-9a-f]{8})?$/u.exec(e);return t===null?void 0:[Number(t[1]),Number(t[2]),Number(t[3]),t[4]===void 0?1:0]}function pr(e,t){for(let s=0;s<4;s++)if(e[s]!==t[s])return e[s]-t[s];return 0}var X="pipe-update.json",mr="pipe-connected.json";async function Tn(e){let t;try{t=await q(J(e,X),"utf8")}catch(c){return U(c)&&c.code==="ENOENT"?void 0:Error(`cannot read ${J(e,X)}`)}let s;try{s=JSON.parse(t)}catch{return Error(`${J(e,X)} is not JSON`)}if(!U(s)||typeof s.from!=="string"||typeof s.to!=="string"||typeof s.fromVersion!=="string"||typeof s.toVersion!=="string"||typeof s.at!=="string")return Error(`${J(e,X)} is not an update record`);return{from:s.from,to:s.to,fromVersion:s.fromVersion,toVersion:s.toVersion,at:s.at}}async function Nn(e){try{let t=JSON.parse(await q(J(e,mr),"utf8"));return U(t)&&typeof t.version==="string"?t.version:void 0}catch{return}}async function yr(){let e;try{e=J(z("XDG_CONFIG_HOME",".config"),"hightea","claims")}catch{return{error:`HOST_UPDATE_UNSAFE_PATH: ${Q.HOST_JOIN_UNSAFE_PATH}`}}let t;try{t=(await ue(e)).filter((s)=>!s.startsWith(".")).sort()}catch{return{error:`HOST_UPDATE_HOST_UNREADABLE: cannot list ${e}`}}return{claims:e,entries:await Promise.all(t.map((s)=>ke(J(e,s))))}}async function wr(e,t){let s,c;try{s=await Te(L(e.from))}catch{return{refused:"it cannot be resolved"}}try{c=await Te(Oe(z("XDG_DATA_HOME",J(".local","share"))))}catch{return{refused:"the plugin bundles root cannot be resolved"}}if(L(s)!==c)return{refused:`it is not directly under the plugin bundles root ${c}`};if(ie(s)!==e.fromVersion)return{refused:`it is not the bundle directory of version ${e.fromVersion}`};for(let y of t){if(y.pluginBundle===void 0)continue;let f;try{f=await Te(L(y.pluginBundle))}catch{continue}if(f===s)return{refused:`${y.config} names it now`}}return{directory:s}}async function _n(e){let t=await Tn(e.configDir);if(t===void 0)return;if(t instanceof Error){console.error(`HOST_UPDATE_RECORD_UNREADABLE: ${t.message}; no bundle was removed`);return}if(await Nn(e.configDir)!==t.toVersion){console.log(`Keeping the previous plugin bundle ${L(t.from)} until this host connects at ${t.toVersion}; restart it with: ${se(e.claim)}`);return}let c=await yr();if("error"in c){console.error(`${c.error}; the previous bundle ${L(t.from)} was kept`);return}let y=c.entries.filter((I)=>I.pluginBundle===t.from||I.state==="unreadable");if(y.length>0){console.log(`Keeping the previous plugin bundle ${L(t.from)}: ${y.map((I)=>I.state==="unreadable"?`${I.config} (unreadable)`:I.config).join(", ")} may still name it.`);return}let f=await wr(t,c.entries);if("refused"in f){console.error(`HOST_UPDATE_PRUNE_REFUSED: ${L(t.from)}: ${f.refused}; nothing was removed`);return}try{await hn(f.directory,{recursive:!0,force:!0}),await hn(J(e.configDir,X),{force:!0})}catch(I){console.error(`HOST_UPDATE_PRUNE_FAILED: ${L(t.from)}: ${I.message}`);return}console.log(`Removed the previous plugin bundle ${L(t.from)} (${t.fromVersion}); this host has connected at ${t.toVersion}.`)}async function C(e,t){let s=await n(e.host);if("error"in s)return console.error(s.error.replace(/^SERVICE_/u,"HOST_UPDATE_")),1;let c=On(s.config);if(!c.ok)return console.error(`HOST_UPDATE_CONFIG_UNREADABLE: ${s.config} could not be read as a JSON object; it was left unchanged`),1;let y=Array.isArray(c.value.plugins)?c.value.plugins:[],f=y.findIndex(ge),I=y[f];if(I===void 0||typeof I.source!=="string")return console.error(`HOST_UPDATE_CONFIG_UNREADABLE: ${s.config} holds no Hightea plugin entry with a source; it was left unchanged`),1;let O=await le(I.source);if(!O.ok)return console.error(`HOST_UPDATE_BUNDLE_UNREADABLE: the installed plugin bundle ${I.source} is ${O.reason}; nothing changed. \`hightea host status\` names the repair.`),1;let S=O.bundle.version,E=wn(S),h=wn(t.version);if(E===void 0||h===void 0)return console.error(`HOST_UPDATE_VERSION_UNREADABLE: cannot order the installed bundle ${S} against this CLI's ${t.version} (each must be x.y.z or x.y.z-dev.<hash8>); nothing changed`),1;let T=pr(h,E)||(t.version===S?0:1);if(T<0)return console.error(`HOST_UPDATE_DOWNGRADE: host ${s.hostId} runs plugin bundle ${S}, newer than this CLI's ${t.version}; nothing changed. Update the CLI instead.`),1;if(T===0)return console.log(`Host ${s.hostId} already runs plugin bundle ${S}; ${s.config} was left unchanged.`),await _n(s),0;await _n(s);let b;try{b=await Se(z("XDG_DATA_HOME",J(".local","share")),t.directory,t.version)}catch(K){let G=K instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(K.message)?K.message:"HOST_JOIN_CONFIG_IO";return console.error(`${G.replace(/^HOST_JOIN_/u,"HOST_UPDATE_")}: ${Q[G]??"the new bundle could not be installed"} ${s.config} was left unchanged.`),1}let H={from:I.source,to:b.manifest,fromVersion:S,toVersion:b.version,at:new Date().toISOString()},k=y.slice(),F=Array.isArray(I.grants)?I.grants.filter((K)=>typeof K==="string"):[],D=Sn.filter((K)=>!F.includes(K));k[f]={...I,source:b.manifest,...D.length===0?{}:{grants:[...F,...D]}};try{Ae(J(s.configDir,X),H,{mode:384}),Ae(s.config,{...c.value,plugins:k},{mode:384})}catch(K){return console.error(`HOST_UPDATE_CONFIG_UNWRITABLE: ${s.config}: ${K.message}`),1}return console.log(`Host ${s.hostId} now loads plugin bundle ${b.version} (was ${S}), same host id and credentials; ${s.config} changed only its source${D.length===0?"":` and added the missing ${D.join(", ")} grants`}.`),console.log(`The previous bundle ${L(I.source)} is kept until the host connects at ${b.version}. Restart it with: ${se(s.claim)}`),0}function _r(e){if(e===void 0||e==="")throw Error("HOST_JOIN_RECEIPT_INVALID");return e}
|
|
5
|
+
export{m,o,g,N,R,n,i,x,C};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{L,u,p,w,D,P}from"./chunk-tay0pyz4.js";export{L as agentAppsOnPath,w as appInstalled,p as describedApp,u as installLineOf,D as isShippedApp,P as noAgentAppsLine};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./chunk-tay0pyz4.js";import{o,n}from"./chunk-kq5y08g7.js";import{h}from"./chunk-3w7svm2r.js";import{r}from"./chunk-evg5apz3.js";var P='That code is not waiting here. It may have expired, or already have been used. On the browser, press "Approve this browser" again for a new code.';async function O(e){let{createInterface:s}=await import("node:readline/promises"),t=s({input:process.stdin,output:process.stderr});try{return/^y(es)?$/iu.test((await t.question(e)).trim())}finally{t.close()}}function l(e){return typeof e==="string"?e:""}async function R(e){try{let s=await e.json();return typeof s==="object"&&s!==null?s:null}catch{return null}}function N(e,s){let t=e?.error;if(typeof t==="object"&&t!==null){let a=t,m=l(a.code),d=l(a.message);if(m!==""&&d!=="")return`${m}: ${d}`;if(d!=="")return d}return`the deployment answered ${String(s)}`}async function H(e,s={localHost:(t)=>n(t),trust:(t)=>h(t),confirm:O,fetch:(t,a)=>fetch(t,a)}){try{r(e.caller,"key-trust")}catch(i){return console.error(`${i.message}; nothing was approved`),1}let t=await s.localHost(e.host);if("error"in t)return console.error(t.error.replace(/^SERVICE_/u,"APPROVE_")),1;let a=(e.origin??t.gateway??"").trim().replace(/\/+$/u,"");if(a==="")return console.error(`APPROVE_ORIGIN_UNKNOWN: this machine's claim for host ${t.hostId} records no deployment address; name it with --origin <url> and the workspace with --workspace <slug>; nothing was approved`),1;let m=(e.workspace??t.workspaceId).trim();if(m==="")return console.error("APPROVE_WORKSPACE_UNKNOWN: no workspace slug to ask about; name it with --workspace <slug>; nothing was approved"),1;let d=e.code.trim();if(d==="")return console.error("APPROVE_CODE_MISSING: give the code the browser shows, e.g. `hightea approve 7QK4-2M8X`; nothing was approved"),1;let A=`${a}/api/ws/${encodeURIComponent(m)}/browser-approval/${encodeURIComponent(d)}`,u;try{u=await s.fetch(A,{headers:{accept:"application/json"},redirect:"error"})}catch(i){return console.error(`APPROVE_UNREACHABLE: could not reach ${a} (${i.message}); nothing was approved`),1}if(u.status===404)return console.error(P),1;let c=await R(u);if(c===null)return console.error(`APPROVE_ANSWER_INVALID: ${a} answered ${String(u.status)} without a JSON body; nothing was approved`),1;if(u.status!==200)return console.error(`APPROVE_REFUSED: ${N(c,u.status)}; nothing was approved`),1;let y=l(c.state);if(y==="approved")return console.error(P),1;if(y!=="pending")return console.error(`APPROVE_ANSWER_INVALID: ${a} answered a state this command does not know (${JSON.stringify(y)}); nothing was approved`),1;let p=l(c.browser).trim(),k=l(c.check).trim(),v=l(c.publicKey),w=l(c.personName).trim(),E=l(c.expiresAt),b=o(v);if(p===""||k===""||"error"in b)return console.error("APPROVE_ANSWER_INVALID: the deployment's answer names no browser and check characters, or carries no usable public key; nothing was approved"),1;let g=e.json===!0?(i)=>console.error(i):(i)=>console.log(i);if(g("Approve this browser?"),g(""),g(` ${p}`),g(` Check that your browser shows ${k}.`),g(w===""?" For: the person who asked on that browser":` For: ${w}, to ask this computer's agents`),g(""),!await s.confirm("Type y to approve, anything else to cancel: "))return console.error("Nothing was approved. The code is still waiting until it expires."),1;if(await s.trust({action:"add",caller:e.caller,name:p,publicKey:v,quiet:!0,...w===""?{}:{personName:w},...e.host===void 0?{}:{host:e.host},...e.configDir===void 0?{}:{configDir:e.configDir}})!==0)return console.error("Nothing was approved on the browser side; the code is still waiting."),1;let I=`${A}/approved`,f;try{f=await s.fetch(I,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({keyFingerprint:b.keyId}),redirect:"error"})}catch(i){return console.error(`APPROVE_NOT_MARKED: this computer now trusts ${p}, but ${a} could not be told (${i.message}). The browser keeps waiting; press "Approve this browser" again for a new code.`),1}if(f.status!==204)return console.error(`APPROVE_NOT_MARKED: this computer now trusts ${p}, but the deployment did not mark the code spent (${N(await R(f),f.status)}). The browser keeps waiting; press "Approve this browser" again for a new code.`),1;if(e.json===!0)return console.log(JSON.stringify({approved:!0,browser:p,keyId:b.keyId,personName:w===""?null:w,expiresAt:E})),0;return console.log(`Approved. ${p} can ask this computer's agents from now on.`),console.log(`Remove it later: hightea browsers remove "${p}"`),0}export{H as hostApprove};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import"./chunk-kjkww5cr.js";import{t,e}from"./chunk-vzkbknwq.js";import{existsSync as M,mkdirSync as C,readFileSync as x}from"node:fs";import{userInfo as B}from"node:os";import{dirname as D,isAbsolute as P,join as L,resolve as q}from"node:path";var T=`hightea service list (--host HOST --origin URL --workspace SLUG | --local [--host HOST] [--config-dir DIR]) [--json]
|
|
2
|
+
`+`hightea service add|change NAME [--command CMD] [--cwd DIR] [--patch JSON] (--host … | --local [--host HOST] [--config-dir DIR])
|
|
3
|
+
`+`hightea service remove|start|stop|restart NAME (--host … | --local [--host HOST] [--config-dir DIR])
|
|
4
|
+
`+`hightea service logs NAME [--limit N] [--end N] (--host … | --local [--host HOST] [--config-dir DIR])
|
|
5
|
+
`+`hightea service acknowledge (--host … | --local [--host HOST] [--config-dir DIR])
|
|
6
|
+
`+`hightea service backup --host HOST --origin URL --workspace SLUG [--json]
|
|
7
|
+
hightea service restore [NAME...] --from OLD_HOST (--host NEW_HOST | --local [--host HOST] [--config-dir DIR]) --origin URL --workspace SLUG [--yes] [--json]
|
|
8
|
+
hightea service enable|disable [--host HOST] (run on the machine)`,_=(n)=>typeof n==="object"&&n!==null&&!Array.isArray(n)&&typeof n.ok==="boolean"?n:void 0;function U(n,o){let r=encodeURIComponent((n.host??"").trim()),l=async(c,i,s,f)=>{let u=await e(n,o,{method:c,path:`/hosts/${r}/services${i}`,what:s,label:"SERVICE",...f===void 0?{}:{body:f}});if("error"in u){let m=_(u.body?.answer);return m===void 0?u:{answer:m}}let h=_(u.answer.answer);return h===void 0?{exit:1,error:`SERVICE_ANSWER_INVALID: ${s} answered without the host's answer: ${JSON.stringify(u.answer).slice(0,300)}`}:{answer:h}},a=(c)=>`/${encodeURIComponent(c)}`;return{machine:(n.host??"").trim(),list:()=>l("GET","","list"),put:(c)=>l("PUT",a(String(c.service.name)),"put",c),remove:(c)=>l("DELETE",a(c.name),"remove",{ifVersion:c.ifVersion}),control:(c,i)=>l("POST",`${a(c)}/${i}`,i),logs:(c)=>{let i=new URLSearchParams;if(c.end!==void 0)i.set("end",String(c.end));if(c.limit!==void 0)i.set("limit",String(c.limit));let s=i.size===0?"":`?${i}`;return l("GET",`${a(c.name)}/logs${s}`,"logs")},acknowledge:(c)=>l("POST","/acknowledge","acknowledge",c)}}var W=/(^|[\\/])(@ahpd[\\/]deploy|packages[\\/]deploy|(services|deploy)[\\/]plugin)([\\/]|$)/u;function V(n){if(!P(n)||!n.endsWith("/plugin.json"))return;try{let o=JSON.parse(x(n,"utf8"));return typeof o?.id==="string"?o.id:void 0}catch{return}}async function X(n,o=B().username){let r=L(n,"config.json"),l;try{l=JSON.parse(x(r,"utf8"))}catch{return}let a=l?.plugins,c=(Array.isArray(a)?a:[]).filter((g)=>g!==null&&typeof g==="object"&&typeof g.source==="string"),i=c.filter((g)=>V(g.source)==="services"),s=c.filter((g)=>{if(V(g.source)!=="deploy"&&!W.test(g.source))return!1;let y=g.options;return y!==null&&typeof y==="object"&&(("files"in y)||("socket"in y))}),f=i.length>0?i:s;if(f.length===0)return;if(f.length>1)return`${r} has ${f.length} services plugin entries; keep one`;let{acknowledge:u,acknowledgeFiles:h,changesAt:m,controlService:v,listServices:w,machineOf:S,putService:d,removeService:k,serviceLogs:I}=await import("@hallohuman/hightea-services"),O=f[0].options,A=S(n,O!==null&&typeof O==="object"?O:{});if(typeof A==="string")return A;let{machine:p,stateFile:E}=A;try{C(D(E),{recursive:!0,mode:448}),C(D(p.changeLog),{recursive:!0,mode:448})}catch(g){return`cannot make the services directory for ${p.changeLog}: ${g.message}`}let R={principal:`local:${o}`,remote:!1},N=(g)=>{let y=g;if(y.ok&&(!("changed"in y)||y.changed===!0)&&typeof y.file==="string"&&typeof y.ifVersion==="string")u(E,y.file,y.ifVersion);return g};return{machine:p,caller:R,list:()=>w(p),put:async(g)=>N(await d(p,R,g)),remove:async(g)=>N(await k(p,R,g)),control:(g,y)=>v(p,R,{name:g,verb:y}),logs:(g)=>I(p,R,g),acknowledge:(g)=>h(p,R,g,(y,F)=>u(E,y,F)),changes:(g={},y)=>m(p,g,y)}}async function H(n,o={}){let r;if(n.configDir!==void 0&&n.configDir.trim()!==""){if(!P(n.configDir))return{error:`SERVICE_CONFIG_DIR_INVALID: --config-dir needs an absolute path; ${JSON.stringify(n.configDir)} is not one`};let s=q(n.configDir);if(!M(L(s,"config.json")))return{error:`SERVICE_CONFIG_DIR_INVALID: ${s} holds no config.json; name the directory holding this host's ahpd configuration (in a hab-managed host that is its xdg-config/ahpd)`};r=s}else{let{localHost:s,runningAhpds:f}=await import("./chunk-axj8ef03.js"),h=await(o.localHost??((m)=>s(m,{runningAhpds:o.runningAhpds??f})))(n.host);if("error"in h)return h;r=h.configDir}let{localServices:l,LOG_LINES_MAX:a}=await import("@hallohuman/hightea-services"),c=l(r);if(typeof c==="string"&&c.includes("has no services plugin entry")){let s=await X(r);if(s!==void 0)c=s}if(typeof c==="string")return{error:`SERVICE_NOT_CONFIGURED: ${c}`};let i=(s)=>({answer:s});return{machine:c.machine.name,list:async()=>i(c.list()),put:async(s)=>i(await c.put(s)),remove:async(s)=>i(await c.remove(s)),control:async(s,f)=>i(await c.control(s,f)),logs:async(s)=>i(await c.logs({name:s.name,endOffset:s.end??0,limit:Math.min(s.limit??100,a)})),acknowledge:async(s)=>i(await c.acknowledge(s))}}async function oe(n,o,r=t(),l={}){let a=!n.local;if(a&&((n.host??"").trim()===""||n.workspace.trim()===""))return r.err(`SERVICE_INPUT: name the host with --host and --workspace, or act on this machine with --local.
|
|
9
|
+
${T}`),1;let c=o.command!=="list"&&o.command!=="acknowledge",i=o.name?.trim()??"";if(c&&i==="")return r.err(`SERVICE_INPUT: ${o.command} names one service.
|
|
10
|
+
${T}`),1;let s=a?U(n,r):await(l.local??H)(n);if("error"in s)return r.err(s.error),1;let f=(u,h)=>{if("error"in u)return r.err(u.error),u.exit;let m=u.answer;if(!m.ok){if(r.err(`${String(m.code??"SERVICE_REFUSED")}: ${String(m.message??"the machine refused")}`),typeof m.diff==="string"&&m.diff!=="")r.err(m.diff);if(n.json)r.out(JSON.stringify(m));return 1}if(n.json)r.out(JSON.stringify(m));else h(m);return 0};switch(o.command){case"list":return f(await s.list(),(u)=>r.out(G(u,s.machine)));case"start":case"stop":case"restart":return f(await s.control(i,o.command),()=>r.out(`${o.command}: ${i} on ${s.machine}`));case"logs":{let u=j(o.end,0),h=j(o.limit,1);if(u===null||h===null)return r.err("SERVICE_INPUT: --end and --limit are whole numbers of lines; --limit is at least 1"),1;let m=await s.logs({name:i,...u===void 0?{}:{end:u},...h===void 0?{}:{limit:h}});return f(m,(v)=>{r.out(`raw output from ${i} on ${s.machine}:`);for(let w of Array.isArray(v.lines)?v.lines:[])r.out(String(w))})}case"acknowledge":case"add":case"change":case"remove":{let u=await s.list();if("error"in u)return r.err(u.error),u.exit;if(!u.answer.ok)return f(u,()=>{});let h=String(u.answer.ifVersion??""),v=(Array.isArray(u.answer.services)?u.answer.services:[]).some((d)=>d.name===i);if(o.command==="acknowledge"){let d=u.answer.hashes??{};return f(await s.acknowledge({hashes:d}),()=>r.out(`acknowledged ${Object.keys(d).join(", ")||"no files"} on ${s.machine} as they are now`))}if(o.command==="remove")return f(await s.remove({name:i,ifVersion:h}),()=>r.out(`removed ${i} on ${s.machine}`));if(o.command==="add"&&v)return r.err(`SERVICE_EXISTS: ${i} is already a service on ${s.machine}; use \`hightea service change\``),1;if(o.command==="change"&&!v)return r.err(`SERVICE_NOT_FOUND: ${i} is not a service on ${s.machine}; use \`hightea service add\``),1;let w=z(i,o.fields??{});if(typeof w==="string")return r.err(`SERVICE_INPUT: ${w}`),1;let S=K(u.answer.capabilities,w,s.machine);if(S!==void 0)return r.err(`SERVICE_UNSUPPORTED: ${S} Nothing was sent.`),1;if(o.command==="add"&&w.command===void 0)return r.err("SERVICE_INPUT: a new service needs --command"),1;return f(await s.put({service:w,ifVersion:h}),(d)=>r.out(d.changed===!1?`${i} on ${s.machine} already reads so; nothing was written`:`${o.command==="add"?"added":"changed"} ${i} on ${s.machine}`))}}}function z(n,o){let r={};if(o.patch!==void 0){try{r=JSON.parse(o.patch)}catch{return"--patch is a JSON object of service fields"}if(typeof r!=="object"||r===null||Array.isArray(r))return"--patch is a JSON object of service fields";if(r.name!==void 0&&r.name!==n)return"--patch names another service"}return{...r,name:n,...o.command===void 0?{}:{command:o.command},...o.cwd===void 0?{}:{cwd:o.cwd}}}function K(n,o,r){if(typeof n!=="object"||n===null)return;let{fields:l,schedule:a}=n;if(Array.isArray(l)){let i=Object.keys(o).filter((s)=>!l.includes(s));if(i.length>0)return`${r}'s driver does not take ${i.join(", ")}; it takes ${l.join(", ")}.`}let c=o.schedule;if(Array.isArray(a)&&typeof c==="object"&&c!==null){let s=Object.keys(c).filter((f)=>f==="cron"||f==="interval").filter((f)=>!a.includes(f));if(s.length>0)return`${r}'s driver does not take ${s.map((f)=>`schedule.${f}`).join(", ")}; it takes ${a.map((f)=>`schedule.${String(f)}`).join(", ")}.`}return}function j(n,o){if(n===void 0)return;return/^\d{1,7}$/u.test(n.trim())&&Number(n)>=o?Number(n):null}function G(n,o){let r=Array.isArray(n.services)?n.services:[],l=Array.isArray(n.readOnly)?n.readOnly:[],a=r.map((i)=>{let s=Array.isArray(i.plainEnv)&&i.plainEnv.length>0?` (plain env: ${i.plainEnv.join("; ")})`:"";return`${String(i.name)} ${String(i.command??"")}${s}`});for(let i of l)a.push(`${String(i.name)} read-only: ${String(i.reason)}`);if(a.length===0)a.push(`no services on ${o} (${String(n.file??"its file")})`);let c=Y(n);if(c.length>0){a.push(`drift on ${o} (${c.length}), shown only; nothing was repaired:`);for(let i of c)a.push(` ${i.level}: ${i.text}`)}return a.join(`
|
|
11
|
+
`)}function Y(n){let o=(l)=>(Array.isArray(l)?l:[]).filter((a)=>b(a)&&typeof a.text==="string").map((a)=>({level:typeof a.level==="string"?a.level:"warning",text:String(a.text)})),r=Array.isArray(n.rows)?n.rows:[];return[...o(n.alerts),...r.flatMap((l)=>b(l)?o(l.alerts):[])]}var b=(n)=>typeof n==="object"&&n!==null&&!Array.isArray(n);async function J(n,o,r){let l=await e(n,o,{method:"GET",path:`/hosts/${encodeURIComponent(r)}/services/backup`,what:"backup",label:"SERVICE"});if("error"in l)return l;let a=l.answer.backup;if(!b(a)||typeof a.label!=="string"||!b(a.listing)||!Array.isArray(a.lines))return{exit:1,error:`SERVICE_ANSWER_INVALID: backup answered without a backup: ${JSON.stringify(l.answer).slice(0,300)}`};return{backup:a}}function Q(n){if(n.unreadable===!0)return`unreadable line at ${String(n.offset)} (${String(n.bytes)} bytes)`;if(n.boundary===!0)return`--- ${String(n.message)} ---`;let o=b(n.refused)?` refused ${String(n.refused.code)}`:"",r=typeof n.name==="string"&&n.name!==""?` ${n.name}`:"";return`${String(n.at??"")} ${String(n.principal??"")} ${String(n.op??"")}${r}${o}`}async function se(n,o=t()){let r=(n.host??"").trim();if(r===""||n.workspace.trim()===""||n.local)return o.err(`SERVICE_INPUT: name the host with --host and --workspace; a backup is read from Hightea, never --local.
|
|
12
|
+
${T}`),1;let l=await J(n,o,r);if("error"in l)return o.err(l.error),l.exit;let{backup:a}=l;if(n.json)return o.out(JSON.stringify(a)),0;let c=a.hostStatus==="revoked"?`revoked ${a.revokedAt??""}`.trim():a.connected?"connected":"offline";if(o.out(`${r} (${c}): ${a.label}`),typeof a.reason==="string")o.out(`last pull: ${a.reason}`);o.out(G({ok:!0,...a.listing},r)),o.out(a.lines.length===0?"no changes backed up":`changes, oldest first (${a.lines.length}):`);for(let{line:i}of a.lines)o.out(` ${Q(i)}`);return 0}function Z(){return{...t(),confirm:async(n)=>{let{createInterface:o}=await import("node:readline/promises"),r=o({input:process.stdin,output:process.stderr});try{return/^y(es)?$/iu.test((await r.question(n)).trim())}finally{r.close()}}}}async function ie(n,o,r=Z(),l={}){let a=o.from.trim(),c=(n.host??"").trim();if(a===""||n.workspace.trim()===""||!n.local&&c==="")return r.err(`SERVICE_INPUT: restore names the old host with --from, the workspace with --workspace, and the new host with --host or --local.
|
|
13
|
+
${T}`),1;let i=await J(n,r,a);if("error"in i)return r.err(i.error),i.exit;let{backup:s}=i,f=Array.isArray(s.listing.services)?s.listing.services.filter(b):[],u=o.names.filter((d)=>!f.some((k)=>k.name===d));if(u.length>0)return r.err(`SERVICE_NOT_IN_BACKUP: ${u.join(", ")} ${u.length===1?"is":"are"} not in ${a}'s backup (${s.label}); it holds ${f.map((d)=>String(d.name)).join(", ")||"no services"}`),1;let h=o.names.length===0?f:f.filter((d)=>o.names.includes(String(d.name)));if(h.length===0)return r.err(`SERVICE_NOTHING_TO_RESTORE: ${a}'s backup (${s.label}) holds no services`),1;let m=n.local?await(l.local??H)(n):U(n,r);if("error"in m)return r.err(m.error),1;let v=(d)=>b(d.env)?Object.entries(d.env).map(([k,I])=>`${k} (${String(b(I)?I.$secret:I)})`):[],w=(d)=>Array.isArray(d.plainEnv)?d.plainEnv.map(String):[];r.err(`restore from ${a} (${s.label}) to ${m.machine}, create only:`);for(let d of h){r.err(` ${String(d.name)} ${String(d.command??"")}`);let k=v(d);if(k.length>0)r.err(` secrets to enter again on ${m.machine}: ${k.join(", ")}`)}if(!o.yes&&!await r.confirm(`create ${h.length} service${h.length===1?"":"s"} on ${m.machine}? [y/N] `))return r.err("SERVICE_RESTORE_DECLINED: nothing was sent"),1;let S=[];for(let d of h){let{plainEnv:k,...I}=d,O=String(d.name),A=v(d),p=w(d),E=await m.put({service:I,ifVersion:"absent"});if("error"in E){let[R="SERVICE_FAILED",...N]=E.error.split(": ");S.push({name:O,outcome:"failed",code:R,message:N.join(": "),secrets:A,plainEnv:p})}else if(!E.answer.ok)S.push({name:O,outcome:"refused",code:String(E.answer.code??"SERVICE_REFUSED"),message:String(E.answer.message??""),secrets:A,plainEnv:p});else S.push({name:O,outcome:"created",secrets:A,plainEnv:p})}if(n.json)r.out(JSON.stringify({from:a,to:m.machine,label:s.label,results:S}));else for(let d of S){if(r.out(d.outcome==="created"?`created ${d.name}`:`${d.outcome} ${d.name}: ${d.code}: ${d.message}`),d.outcome==="created"&&d.secrets.length>0)r.out(` secrets to enter again: ${d.secrets.join(", ")}`);if(d.outcome==="created"&&d.plainEnv.length>0)r.out(` plain values never backed up: ${d.plainEnv.join("; ")}`)}return S.every((d)=>d.outcome==="created")?0:1}export{se as serviceBackupCommand,oe as serviceCommand,ie as serviceRestore};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import{constants as yp}from"node:fs";import{access as Ep,stat as Sp}from"node:fs/promises";import{delimiter as Tp,isAbsolute as wp,join as Ap}from"node:path";import{installLine as Wc,knownAgents as Hc}from"@ahpd/sdk";function De(e){let t=Object.values(e).filter((r)=>typeof r==="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function Ft(e,t="|"){return e.map((n)=>jt(n)).join(t)}function Pe(e,t){if(typeof t==="bigint")return t.toString();return t}class or{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function Me(e){return new or(e)}function sr(e){return e===null||e===void 0}function Ye(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function ir(e,t){let n=e/t,r=Math.round(n),o=4*Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-r)<o)return 0;return n-r}function Q(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function $e(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function ce(e){return $e(e._zod.def)??e._zod.def.shape}function ar(e,t,n){Object.defineProperty(e,t,{get(){let r=n();return Q(this,t,r),r},enumerable:!0,configurable:!0})}function cr(e,t,n){if(t in e)Q(e,t,n);else e[t]=n}function ye(e,t,n,r){let o=ce(t);for(let s of n){let i=Object.getOwnPropertyDescriptor(o,s);if(!i.enumerable)continue;if(i.get)ar(e,s,()=>{let m=t._zod.def.shape[s];return r?r(m,s):m});else cr(e,s,r?r(i.value,s):i.value)}}function rd(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);if(!r.enumerable)continue;if(r.get)ar(e,n,()=>t[n]);else cr(e,n,r.value)}}function q(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function dr(e){return JSON.stringify(e)}function ur(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Bt="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ie(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var lr=Me(()=>{if(G.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Ee(e){if(Ie(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(Ie(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Zt(e){if(Ee(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var pr=new Set(["string","number","symbol"]);function me(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function oe(e,t,n){let r=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)r._zod.parent=e;return r}function v(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function jt(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function mr(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var Qe=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))(),Jt={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function od(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 s={};return ye(s,e,et(e,t)),oe(e,q(n,{shape:s,checks:[]}))}function et(e,t){let n=ce(e),r=[];for(let o of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,o)?.enumerable)throw Error(`Unrecognized key: "${String(o)}"`);if(t[o])r.push(o)}return r}function sd(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 s=new Set(et(e,t)),i={};return ye(i,e,Reflect.ownKeys(ce(e)).filter((m)=>!s.has(m))),oe(e,q(n,{shape:i,checks:[]}))}function id(e,t){if(!Ee(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let o=ce(e);for(let s of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return oe(e,q(e._zod.def,{shape:gr(e,t)}))}function gr(e,t){let n={};return ye(n,e,Reflect.ownKeys(ce(e))),rd(n,t),n}function ad(e,t){if(!Ee(t))throw Error("Invalid input to safeExtend: expected a plain object");return oe(e,q(e._zod.def,{shape:gr(e,t)}))}function cd(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={};ye(n,e,Reflect.ownKeys(ce(e))),ye(n,t,Reflect.ownKeys(ce(t)));let r=q(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return oe(e,r)}function fr(e,t,n,r="partial"){let s=t._zod.def.checks;if(s&&s.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let m=n?new Set(et(t,n)):void 0,g={};return ye(g,t,Reflect.ownKeys(ce(t)),e&&((f,h)=>m&&!m.has(h)?f:new e({type:"optional",innerType:f}))),oe(t,q(t._zod.def,{shape:g,checks:[]}))}function dd(e,t,n){let r=n?new Set(et(t,n)):void 0,o={};return ye(o,t,Reflect.ownKeys(ce(t)),(s,i)=>r&&!r.has(i)?s:new e({type:"nonoptional",innerType:s})),oe(t,q(t._zod.def,{shape:o}))}function se(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function hr(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function ge(e,t){return t.map((n)=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Le(e){return typeof e==="string"?e:e?.message}function Gt(e){let t=[];for(let n of e??[]){let r=n._zod.def;if(!/_(length|size)$|_equals$/.test(r.check))break;let o=r.maximum??r.length??r.size;if(o>=0)t.push([o,n])}return t}function tt(e,t,n){var r;for(let o=t;o<e.length;o++)(r=e[o]).schema??(r.schema=n)}function ie(e,t,n){var r;let o=e.inst?._zod?.traits;if(o?.has("$ZodType"))if(o.has("$ZodCheck"))(r=e).schema??(r.schema=e.inst);else e.schema=e.inst;let s=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,i=e.message?e.message:Le(e.inst?._zod.def?.error?.(e))??Le(s?.(e))??Le(t?.error?.(e))??Le(n.customError?.(e))??Le(n.localeError?.(e))??"Invalid input",m={};for(let g of Object.keys(e)){if(g==="inst"||g==="schema"||g==="continue"||g==="input"||g==="__proto__")continue;m[g]=e[g]}if(m.path??(m.path=[]),m.message=i,t?.reportInput)m.input=e.input;return m}var ud=/[\uD800-\uDBFF]/;function nt(e){let t=e.length;if(!ud.test(e))return t;let n=t;for(let r=0;r<t-1;r++)if((e.charCodeAt(r)&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320)n--,r++;return n}function rt(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function _r(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function Se(...e){let[t,n,r]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:r};return{...t}}function yr(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);if(r.get)Object.defineProperty(e,n,{...r,enumerable:!1});else ld(e,n,r.value)}}function de(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function ot(e,t,n){return de(e,t,n,!1)}function Er(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return de(this,n,r(this))},set(o){de(this,n,o)}})}return t}function ld(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:de(this,t,n.bind(this))},set(r){de(this,t,r)}})}function pd(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var Ht,pe=!1,md={configurable:!0,get(){pe=!0;return}};function N(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&Ht!==e._zod){Ht=void 0;return}Ht=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,md);let o=pe;pe=!1;try{let s=n(this);if(pe)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s});return pe=pe||o,s}catch(s){throw delete this[t],pe=pe||o,s}},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o})}})}function gd(e,t,n,r){let o=pd(e,t);if(!o)return;Object.defineProperty(o,t,{configurable:!0,get(){let s={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,s),s.value=n(this),Object.defineProperty(this,t,s),s.value},set(s){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:s})}})}var fd="~constantCatch";function Sr(e){let t=()=>e;return t[fd]=!0,t}var Tr;var Kt={value:void 0,enumerable:!1},wr="captureStackTrace"in Error?Error:null;function hd(e){let t=wr;if(t){let n=t.stackTraceLimit;if(typeof n==="number"){try{t.stackTraceLimit=0}catch{return wr=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function y(e,t,n,r){let o={};function s(k){this.def=k,this.constr=E,this.traits=new Set}s.prototype=o;let i=n,m=i&&new WeakSet;function g(k,S){if(!k._zod){Kt.value=new s(S);try{Object.defineProperty(k,"_zod",Kt)}finally{Kt.value=void 0}}else if(k._zod.traits.has(e))return;if(k._zod.traits.add(e),t(k,S),m){let R=Object.getPrototypeOf(k),x=k._zod.constr.prototype,O=R;while(O&&O!==x)O=Object.getPrototypeOf(O);let Y=O??R;if(!m.has(Y))m.add(Y),yr(Y,i)}let b=E.prototype;for(let R in b){if(!Object.prototype.hasOwnProperty.call(b,R))continue;if(!(R in k))k[R]=b[R].bind(k)}}let f=r?.Parent??Object;class h extends f{}Object.defineProperty(h,"name",{value:e});function E(k){let S=r?.Parent?hd(h):this;g(S,k);let b=S._zod.deferred;if(b){for(let x of b)x();S._zod.deferred=void 0}let R=globalThis.__zod_globalConfig?.postProcessor;if(R)R(S);return S}return Object.defineProperty(E,"init",{value:g}),Object.defineProperty(E,Symbol.hasInstance,{value:(k)=>{if(r?.Parent&&k instanceof r.Parent)return!0;return k?._zod?.traits?.has(e)}}),Object.defineProperty(E,"name",{value:e}),E}class ae extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Ue extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(Tr=globalThis).__zod_globalConfig??(Tr.__zod_globalConfig={});var G=globalThis.__zod_globalConfig;function V(e){if(e)Object.assign(G,e);return G}function _d(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Pe,2)),e.message}function yd(e){this._zod.message=e}var Ed={get:_d,set:yd,enumerable:!0,configurable:!0},Vt={value:void 0,enumerable:!1},Ar=new WeakSet([Object.prototype,Error.prototype]),kr=(e,t)=>{e.name="$ZodError",Vt.value=t,Object.defineProperty(e,"issues",Vt),Vt.value=void 0,Object.defineProperty(e,"message",Ed);let n=Object.getPrototypeOf(e);if(!Ar.has(n))Ar.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}})},br=y("$ZodError",kr),Jp=y("$ZodError",kr,void 0,{Parent:Error});function Sd(e,t,n){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0});else e[t]=n();return e[t]}function Ir(e,t=(n)=>n.message){let n={},r=[];for(let o of e.issues)if(o.path.length>0)Sd(n,o.path[0],()=>[]).push(t(o));else r.push(t(o));return{formErrors:r,fieldErrors:n}}function vr(e,t=(n)=>n.message){let n={_errors:[]},r=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map((m)=>r({issues:m},[...s,...i.path]));else if(i.code==="invalid_key")r({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")r({issues:i.issues},[...s,...i.path]);else{let m=[...s,...i.path];if(m.length===0)n._errors.push(t(i));else{let g=n,f=0;while(f<m.length){let h=m[f],E=f===m.length-1;if(h==="_errors"){if(E)g._errors.push(t(i));f++;continue}if(!Object.prototype.hasOwnProperty.call(g,h))Object.defineProperty(g,h,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let k=g[h];if(E)k._errors.push(t(i));g=k,f++}}}};return r(e),n}function st(e,t){return{callee:t?.callee??e,Err:t?.Err}}var it=(e)=>{let t=(n,r,o,s)=>{let i=o?{...o,async:!1}:{async:!1},m=n._zod.run({value:r,issues:[]},i);if(m instanceof Promise)throw new ae;if(m.issues.length){let g=new(s?.Err??e)(m.issues.map((f)=>ie(f,i,V())));throw Bt(g,s?.callee??t),g}return m.value};return t};var at=(e)=>{let t=async(n,r,o,s)=>{let i=o?{...o,async:!0}:{async:!0},m=n._zod.run({value:r,issues:[]},i);if(m instanceof Promise)m=await m;if(m.issues.length){let g=new(s?.Err??e)(m.issues.map((f)=>ie(f,i,V())));throw Bt(g,s?.callee??t),g}return m.value};return t};var ct=(e)=>(t,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new ae;return s.issues.length?Rr(e,s.issues,o):{success:!0,data:s.value}};function Rr(e,t,n){let r;return{success:!1,get error(){if(!r)r=new e(t.map((o)=>ie(o,n,V()))),t=void 0,n=void 0;return r},set error(o){r=o,t=void 0,n=void 0}}}var dt=(e)=>async(t,n,r)=>{let o=r?{...r,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)s=await s;return s.issues.length?Rr(e,s.issues,o):{success:!0,data:s.value}};var Td=Symbol.for("zod.compile.invalid"),wd=Symbol.for("zod.compile.fallback"),Xt=(e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==Td)return!0;if(r.definite===!0&&n===void 0)return!1}return Ad(e,t,n)};function Ad(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=e._zod.bag.fallbackRun,s;if(o)r[wd]=!0,s=o({value:t,issues:[]},r);else s=e._zod.run({value:t,issues:[]},r);if(s instanceof Promise)throw new ae;return s.issues.length===0}var Yt=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},o=e._zod.run({value:t,issues:[]},r);if(o instanceof Promise)o=await o;return o.issues.length===0},xr=(e)=>{let t=it(e),n=(r,o,s,i)=>{let m=s?{...s,direction:"backward"}:{direction:"backward"};return t(r,o,m,st(n,i))};return n};var Nr=(e)=>{let t=it(e),n=(r,o,s,i)=>t(r,o,s,st(n,i));return n};var Or=(e)=>{let t=at(e),n=async(r,o,s,i)=>{let m=s?{...s,direction:"backward"}:{direction:"backward"};return await t(r,o,m,st(n,i))};return n};var Cr=(e)=>{let t=at(e),n=async(r,o,s,i)=>await t(r,o,s,st(n,i));return n};var Lr=(e)=>(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return ct(e)(t,n,o)};var Dr=(e)=>(t,n,r)=>ct(e)(t,n,r);var Pr=(e)=>async(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return dt(e)(t,n,o)};var Mr=(e)=>async(t,n,r)=>dt(e)(t,n,r);var $r=/^[cC][0-9a-z]{6,}$/,Ur=/^[0-9a-z]+$/,zr=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Wr=/^[0-9a-vA-V]{20}$/,Hr=/^[A-Za-z0-9]{27}$/,Fr=/^[a-zA-Z0-9_-]{21}$/;function Br(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var Zr=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var jr=/^([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})$/,en=(e)=>{if(!e)return/^([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)$/;return 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})$`)};var Jr=/^(?:[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 kd="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function Gr(){return new RegExp(kd,"u")}var Kr=/^(?:(?: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])$/,qr=/^(([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}|:))$/;var Vr=/^((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])$/,Xr=/^(([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])$/,Yr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Qr=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;var eo=/^https?$/,to=/^\+[1-9]\d{6,14}$/;var no="(?:(?:\\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])))";function bd(e){return new RegExp(`^${e}$`)}var ro=bd(no);function Qt(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[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+)?)?"}function oo(e){return new RegExp(`^${Qt(e)}$`)}function so(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${Qt({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${Qt({precision:e.precision})}`:n;return new RegExp(`^${no}T(?:${r})$`)}var io=/^[\s\S]{0,}$/;var tn=/^-?\d+$/,ze=/^-?\d+(?:\.\d+)?$/,ao=/^(?:true|false)$/i;var co=/^[^A-Z]*$/,uo=/^[^a-z]*$/;var Z=y("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])});var nn=(e)=>{let t=e.value;return!sr(t)&&t.length!==void 0},ut={number:"number",bigint:"bigint",object:"date"},rn=y("$ZodCheckLessThan",(e,t)=>{Z.init(e,t);let n=ut[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value<=t.value:r.value<t.value)return;r.issues.push({origin:ut[typeof r.value]??n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),on=y("$ZodCheckGreaterThan",(e,t)=>{Z.init(e,t);let n=ut[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value>=t.value:r.value>t.value)return;r.issues.push({origin:ut[typeof r.value]??n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),lo=y("$ZodCheckMultipleOf",(e,t)=>{Z.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.");if(typeof n.value==="bigint"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):ir(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),po=y("$ZodCheckNumberFormat",(e,t)=>{Z.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[o,s]=Qe[t.format];e._zod.check=(i)=>{let m=i.value;if(n){if(!Number.isInteger(m)){i.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:m,inst:e});return}if(!Number.isSafeInteger(m)){if(m>0)i.issues.push({input:m,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});else i.issues.push({input:m,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});return}}if(m<o)i.issues.push({origin:"number",input:m,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(m>s)i.issues.push({origin:"number",input:m,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var mo=y("$ZodCheckMaxLength",(e,t)=>{var n;Z.init(e,t),(n=e._zod.def).when??(n.when=nn),e._zod.check=(r)=>{let o=r.value,s=o.length;if((typeof o==="string"&&s>t.maximum?nt(o):s)<=t.maximum)return;let m=rt(o);r.issues.push({origin:m,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),go=y("$ZodCheckMinLength",(e,t)=>{var n;Z.init(e,t),(n=e._zod.def).when??(n.when=nn),e._zod.check=(r)=>{let o=r.value,s=o.length;if((typeof o==="string"&&s>=t.minimum&&s<t.minimum*2?nt(o):s)>=t.minimum)return;let m=rt(o);r.issues.push({origin:m,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),fo=y("$ZodCheckLengthEquals",(e,t)=>{var n;Z.init(e,t),(n=e._zod.def).when??(n.when=nn),e._zod.check=(r)=>{let o=r.value,s=o.length,i=typeof o==="string"&&s>=t.length&&s<=t.length*2?nt(o):s;if(i===t.length)return;let m=rt(o),g=i>t.length;r.issues.push({origin:m,...g?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),He=y("$ZodCheckStringFormat",(e,t)=>{var n,r;if(Z.init(e,t),t.pattern)(n=e._zod).check??(n.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(r=e._zod).check??(r.check=()=>{})}),ho=y("$ZodCheckRegex",(e,t)=>{He.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),_o=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=co),He.init(e,t)}),yo=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=uo),He.init(e,t)}),Eo=y("$ZodCheckIncludes",(e,t)=>{Z.init(e,t);let n=me(t.includes),r=new RegExp(typeof t.position==="number"?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),So=y("$ZodCheckStartsWith",(e,t)=>{Z.init(e,t);let n=new RegExp(`^${me(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.startsWith(t.prefix))return;r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),To=y("$ZodCheckEndsWith",(e,t)=>{Z.init(e,t);let n=new RegExp(`.*${me(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.endsWith(t.suffix))return;r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});var wo=y("$ZodCheckOverwrite",(e,t)=>{Z.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}});class sn{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(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
2
|
+
`).filter((s)=>s),r=Math.min(...n.map((s)=>s.length-s.trimStart().length)),o=n.map((s)=>s.slice(r)).map((s)=>" ".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){let e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
|
|
3
|
+
${t.join(`
|
|
4
|
+
`)}
|
|
5
|
+
};`)(...Object.values(this.closed))}}var ko={major:4,minor:6,patch:7};var z=y("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ko;let r=e._zod.def.checks,o=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(let s of o)for(let i of s._zod.onattach)i(e);if(o.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let s=(m,g,f)=>{if(m.memo)return m;let h=se(m),E;for(let k of g){if(k._zod.def.when){if(hr(m))continue;if(!k._zod.def.when(m))continue}else if(h)continue;let S=m.issues.length,b=k._zod.check(m);if(b instanceof Promise&&f?.async===!1)throw new ae;if(E||b instanceof Promise)E=(E??Promise.resolve()).then(async()=>{if(await b,m.issues.length===S)return;if(tt(m.issues,S,e),!h)h=se(m,S)});else{if(m.issues.length===S)continue;if(tt(m.issues,S,e),!h)h=se(m,S)}}if(E)return E.then(()=>m);return m},i=(m,g,f)=>{if(se(m))return m.aborted=!0,m;let h=s(g,o,f);if(h instanceof Promise){if(f.async===!1)throw new ae;return h.then((E)=>e._zod.parse(E,f))}return e._zod.parse(h,f)};e._zod.run=(m,g)=>{if(g.skipChecks)return e._zod.parse(m,g);if(g.direction==="backward"){let h=e._zod.parse({value:m.value,issues:[]},{...g,skipChecks:!0});if(h instanceof Promise)return h.then((E)=>i(E,m,g));return i(h,m,g)}let f=e._zod.parse(m,g);if(f instanceof Promise){if(g.async===!1)throw new ae;return f.then((h)=>s(h,o,g))}return s(f,o,g)}}},{get "~standard"(){return ot(this,"~standard",cn(this))},set "~standard"(e){de(this,"~standard",e)}}),Po=(e,t)=>e.issues.length?{issues:e.issues.map((n)=>ie(n,t,V()))}:{value:e.value};async function Id(e,t){let n={async:!0};return Po(await e._zod.run({value:t,issues:[]},n),n)}function cn(e){return{validate:(t)=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return Po(r,n)}catch(r){}return Id(e,t)},vendor:"zod",version:1}}var gt=y("$ZodString",(e,t)=>{z.init(e,t),e._zod.pattern=t.pattern??io,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(o){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),U=y("$ZodStringFormat",(e,t)=>{He.init(e,t),gt.init(e,t)}),Mo=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=jr),U.init(e,t)}),$o=y("$ZodUUID",(e,t)=>{if(t.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=en(r))}else t.pattern??(t.pattern=en());U.init(e,t)}),Uo=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Jr),U.init(e,t)}),zo=1,pt=2;function Wo(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function vd(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return Wo(e)||pt;return Rd(e,t)}function Rd(e,t){if(!t.normalize&&t.protocol?.source===eo.source&&!/^https?:\/\//i.test(e))return zo;try{if(typeof URL<"u"){let n=URL;if(typeof n.parse==="function")return n.parse(e)??pt}return new URL(e)}catch{return pt}}var xd=/[\t\n\r]/g;function bo(e){return e.replace(xd,"")}function Nd(e,t){return t.lastIndex=0,t.test(e.hostname)}function Od(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var Ho=y("$ZodURL",(e,t)=>{U.init(e,t),e._zod.check=(n)=>{try{let r=n.value.trim(),o=vd(r,t);if(o===zo){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(o===pt){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(o===!0){n.value=bo(r);return}if(t.hostname&&!Nd(o,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});if(t.protocol&&!Od(o,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});n.value=t.normalize?o.href:bo(r);return}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Fo=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Gr()),U.init(e,t)}),Bo=y("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?Fr:Br(t.length)),U.init(e,t)}),Zo=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=$r),U.init(e,t)}),jo=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Ur),U.init(e,t)}),Jo=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=zr),U.init(e,t)}),Go=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Wr),U.init(e,t)}),Ko=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Hr),U.init(e,t)}),qo=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=so(t)),U.init(e,t)}),Vo=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ro),U.init(e,t)}),Xo=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=oo(t)),U.init(e,t)}),Yo=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Zr),U.init(e,t)}),Qo=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Kr),U.init(e,t)}),Cd=/^[0-9a-fA-F:.]+$/;function es(e){if(!Cd.test(e))return!1;return Wo(`http://[${e}]`)}var ts=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=qr),U.init(e,t),e._zod.check=(n)=>{if(!es(n.value))n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}});var ns=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Vr),U.init(e,t)});function Ld(e){let t=e.split("/");if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let o=Number(r);if(`${o}`!==r)return!1;if(o<0||o>128)return!1;return es(n)}var rs=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Xr),U.init(e,t),e._zod.check=(n)=>{if(!Ld(n.value))n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function os(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 dn=/^[0-9a-zA-Z+/]*={0,2}$/,ss=y("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=dn),U.init(e,t),e._zod.check=(n)=>{if(os(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),ft=/^[A-Za-z0-9_-]*$/;function Dd(e){if(!ft.test(e))return!1;let t=e.replace(/[-_]/g,(r)=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return os(n)}var is=y("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ft),U.init(e,t),e._zod.check=(n)=>{if(Dd(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),as=y("$ZodE164",(e,t)=>{t.pattern??(t.pattern=to),U.init(e,t)});function Pd(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&(!("alg"in o)||o.alg!==t))return!1;return!0}catch{return!1}}var cs=y("$ZodJWT",(e,t)=>{U.init(e,t),e._zod.check=(n)=>{if(Pd(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}});var un=y("$ZodNumber",(e,t)=>{z.init(e,t),e._zod.pattern=ze,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(i){}let o=n.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let s=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?String(o):void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),n}}),ds=y("$ZodNumberFormat",(e,t)=>{po.init(e,t),un.init(e,t)}),us=y("$ZodBoolean",(e,t)=>{z.init(e,t),e._zod.pattern=ao,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(s){}let o=n.value;if(typeof o==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}});var ls=y("$ZodUnknown",(e,t)=>{z.init(e,t),e._zod.parse=(n)=>n}),ps=y("$ZodNever",(e,t)=>{z.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Md(e,t){let n=Gt(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map((s)=>s[0])),o=e._zod.parse;e._zod.parse=(s,i)=>{let m=t(s.value);if(m>r&&!i?.skipChecks&&i?.direction!=="backward"){for(let[g,f]of Gt(e._zod.def.checks))if(m>g&&f._zod.def.when(s)){let h=s.issues.length;return f._zod.check(s),s.issues[h].continue=!1,tt(s.issues,h,e),s}}return o(s,i)}}var $d=(e)=>Array.isArray(e)?e.length:-1;function Io(e,t,n){if(e.issues.length)t.issues.push(...ge(n,e.issues));t.value[n]=e.value}var ms=y("$ZodArray",(e,t)=>{z.init(e,t);let n=G.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),r;r.value=n?n.alloc(e,r,Array(s.length),o):Array(s.length);let i=[],m=o?.abortEarly;for(let g=0;g<s.length;g++){let f=s[g],h=t.element._zod.run({value:f,issues:[]},o);if(h instanceof Promise)i.push(h.then((E)=>Io(E,r,g)));else if(Io(h,r,g),m&&h.issues.length!==0&&se(h))break}if(i.length)return Promise.all(i).then(()=>r);return r},Md(e,$d)});function mt(e,t,n,r,o,s){let i=n in r,m=s==="optional";if(!i&&m&&o==="optional")return;if(e.issues.length){if(o!==void 0&&m&&!i)return;t.issues.push(...ge(n,e.issues))}if(!i&&o===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(i||o==="defaulted"&&!m)t.value[n]=void 0}else t.value[n]=e.value}var Ud=[];function gs(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Ud,o=r.length?[...t,...r]:t;for(let i of o)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(i)}": expected a Zod schema`);let s=mr(e.shape);return{...e,allKeys:o,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(s)}}function fs(e,t,n,r,o,s,i){let m=[],g=o.keySet,f=o.catchall._zod,h=f.def.type,{optin:E,optout:k}=f,S=0;for(let b in t){if(i&&n.issues.length!==S){if(se(n,S))break;S=n.issues.length}if(g.has(b))continue;if(b==="__proto__"){if(h==="never")m.push(b);continue}if(h==="never"){m.push(b);continue}let R=f.run({value:t[b],issues:[]},r);if(R instanceof Promise)e.push(R.then((x)=>mt(x,n,b,t,E,k)));else mt(R,n,b,t,E,k)}if(m.length)n.issues.push({code:"unrecognized_keys",keys:m,input:t,inst:s,continue:!0});if(!e.length)return n;return Promise.all(e).then(()=>n)}var zd=y("$ZodObject",(e,t)=>{z.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape"),r=n?.get?n.get.raw:t.shape??{};if(r){let f=()=>{let h={...r};return Object.defineProperty(t,"shape",{value:h}),f.raw=h,h};f.raw=r,Object.defineProperty(t,"shape",{get:f})}let o=Me(()=>gs(t));N(e,"propValues",(f)=>{let h=f.def.shape,E={};for(let k in h){let S=h[k]._zod;if(S.values){if(!Object.prototype.hasOwnProperty.call(E,k))Q(E,k,new Set);for(let b of S.values)E[k].add(b);if(S.optin!==void 0)E[k].add(void 0)}}return E});let s=Ie,i=t.catchall,m,g=G.memoizer;g?.attach(e),e._zod.parse=(f,h)=>{m??(m=o.value);let E=f.value;if(!s(E))return f.issues.push({expected:"object",code:"invalid_type",input:E,inst:e}),f;f.value=g?g.alloc(e,f,{},h):{};let k=[],S=m.shape,b=h?.abortEarly,R=f.issues.length;for(let x of m.allKeys){if(b&&f.issues.length!==R){if(se(f,R))break;R=f.issues.length}if(x==="__proto__")continue;let O=S[x],Y=O._zod.optin,Oe=O._zod.optout,Ce=O._zod.run({value:E[x],issues:[]},h);if(Ce instanceof Promise)k.push(Ce.then((B)=>mt(B,f,x,E,Y,Oe)));else mt(Ce,f,x,E,Y,Oe)}if(!i)return k.length?Promise.all(k).then(()=>f):f;return fs(k,E,f,h,o.value,e,b===!0)}}),hs=y("$ZodObjectJIT",(e,t)=>{zd.init(e,t);let n=e._zod.parse,r=Me(()=>gs(t)),o=G.memoizer,s=(S)=>{let b=r.value,R=b.symbolKeys,x=new sn(["payload","ctx"],{shape:S,inst:e,memo:o,syms:R}),O=(B)=>`shape[${B}]._zod.run({ value: input[${B}], issues: [] }, ctx)`,Y=(B,M)=>`
|
|
6
|
+
let ${B}_ab = false;
|
|
7
|
+
for (let i = 0; i < ${B}.issues.length; i++) {
|
|
8
|
+
const iss = ${B}.issues[i];
|
|
9
|
+
iss.path = iss.path ? [${M}, ...iss.path] : [${M}];
|
|
10
|
+
payload.issues.push(iss);
|
|
11
|
+
if (iss.continue !== true) ${B}_ab = true;
|
|
12
|
+
}
|
|
13
|
+
if (${B}_ab && ctx && ctx.abortEarly) {
|
|
14
|
+
payload.value = newResult;
|
|
15
|
+
return payload;
|
|
16
|
+
}`;x.write("const input = payload.value;");let Oe=Object.create(null),Ce=0;for(let B of b.allKeys)Oe[B]=`key_${Ce++}`;x.write(o?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let B of b.allKeys){if(B==="__proto__")continue;let M=Oe[B],re=typeof B==="symbol"?`syms[${R.indexOf(B)}]`:dr(B),Mt=`${re} in input`,nr=S[B],$t=nr?._zod?.optin,rr=$t!==void 0,Bc=nr?._zod?.optout==="optional";if(x.write(`const ${M} = ${O(re)};`),rr&&Bc){let Zc=$t==="optional"?`${M}_present`:`${M}.value !== undefined || ${M}_present`;x.write(`
|
|
17
|
+
const ${M}_present = ${Mt};
|
|
18
|
+
if (!${M}.issues.length || ${M}_present) {
|
|
19
|
+
if (${M}.issues.length) {${Y(M,re)}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (${Zc}) {
|
|
23
|
+
newResult[${re}] = ${M}.value;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
`)}else if(!rr)x.write(`
|
|
28
|
+
const ${M}_present = ${Mt};
|
|
29
|
+
if (${M}.issues.length) {${Y(M,re)}
|
|
30
|
+
}
|
|
31
|
+
if (!${M}_present && !${M}.issues.length) {
|
|
32
|
+
payload.issues.push({
|
|
33
|
+
code: "invalid_type",
|
|
34
|
+
expected: "nonoptional",
|
|
35
|
+
input: undefined,
|
|
36
|
+
path: [${re}]
|
|
37
|
+
});
|
|
38
|
+
if (ctx && ctx.abortEarly) {
|
|
39
|
+
payload.value = newResult;
|
|
40
|
+
return payload;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (${M}_present) {
|
|
45
|
+
newResult[${re}] = ${M}.value;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
`);else if(x.write(`
|
|
49
|
+
if (${M}.issues.length) {${Y(M,re)}
|
|
50
|
+
}
|
|
51
|
+
`),$t==="defaulted")x.write(`newResult[${re}] = ${M}.value;`);else x.write(`
|
|
52
|
+
if (${M}.value !== undefined || ${Mt}) {
|
|
53
|
+
newResult[${re}] = ${M}.value;
|
|
54
|
+
}
|
|
55
|
+
`)}return x.write("payload.value = newResult;"),x.write("return payload;"),x.compile()},i,m=Ie,g=!G.jitless,h=g&&lr.value,E=t.catchall,k;e._zod.parse=(S,b)=>{k??(k=r.value);let R=S.value;if(!m(R))return S.issues.push({expected:"object",code:"invalid_type",input:R,inst:e}),S;if(g&&h&&b?.async===!1&&b.jitless!==!0){if(!i)i=s(t.shape);if(S=i(S,b),!E)return S;return fs([],R,S,b,k,e,b?.abortEarly===!0)}return n(S,b)}});function vo(e,t,n,r){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter((s)=>!se(s));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((s)=>s.issues.map((i)=>ie(i,r,V())))}),t}var ln=y("$ZodUnion",(e,t)=>{z.init(e,t),N(e,"optin",(r)=>r.def.options.some((o)=>o._zod.optin==="defaulted")?"defaulted":r.def.options.some((o)=>o._zod.optin!==void 0)?"optional":void 0),N(e,"optout",(r)=>r.def.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),N(e,"values",(r)=>{if(r.def.options.every((o)=>o._zod.values))return new Set(r.def.options.flatMap((o)=>Array.from(o._zod.values)));return}),N(e,"pattern",(r)=>{if(r.def.options.every((o)=>o._zod.pattern)){let o=r.def.options.map((s)=>s._zod.pattern);return new RegExp(`^(${o.map((s)=>Ye(s.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let s=!1,i=[];for(let m of t.options){let g=m._zod.run({value:r.value,issues:[]},o);if(g instanceof Promise)i.push(g),s=!0;else{if(g.issues.length===0)return g;i.push(g)}}if(!s)return vo(i,r,e,o);return Promise.all(i).then((m)=>vo(m,r,e,o))}});function Wd(e){let t=new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let o of r)if(t.has(o)){if(o!==void 0)throw Error(`Duplicate discriminator value "${String(o)}"`);t.set(o,null)}else t.set(o,n)}return t}var _s=y("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,ln.init(e,t);let n=e._zod.parse;N(e,"propValues",(o)=>{let s={},i=0;for(let m of o.def.options){let g=m._zod.propValues;if(!g||Object.keys(g).length===0)throw Error(`Invalid discriminated union option at index "${o.def.options.indexOf(m)}"`);if(g[o.def.discriminator]?.has(void 0))i++;for(let[f,h]of Object.entries(g)){if(!Object.prototype.hasOwnProperty.call(s,f))Q(s,f,new Set);for(let E of h)s[f].add(E)}}if(!o.def.unionFallback&&i>1)s[o.def.discriminator]?.delete(void 0);return s}),t.options.forEach((o,s)=>{let i=$e(o._zod.def);if(i&&!Object.prototype.hasOwnProperty.call(i,t.discriminator))throw Error(`Invalid discriminated union option at index "${s}"`)});let r=Me(()=>Wd(t));e._zod.parse=(o,s)=>{let i=o.value;if(!Ie(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let m=i?.[t.discriminator],g=r.value.get(m);if(g&&(m!==void 0||s.direction!=="backward"))return g._zod.run(o,s);if(t.unionFallback||s.direction==="backward")return n(o,s);return o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()).filter((f)=>r.value.get(f)!==null),input:i,path:[t.discriminator],inst:e}),o}}),ys=y("$ZodIntersection",(e,t)=>{z.init(e,t),e._zod.parse=(n,r)=>{let o=n.value,s=t.left._zod.run({value:o,issues:[]},r),i=t.right._zod.run({value:o,issues:[]},r);if(s instanceof Promise||i instanceof Promise)return Promise.all([s,i]).then(([g,f])=>Ro(n,g,f));return Ro(n,s,i)}});function an(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(Ee(e)&&Ee(t)){let n=Object.keys(t),r=Object.keys(e).filter((s)=>n.indexOf(s)!==-1),o={...e,...t};if(Object.prototype.hasOwnProperty.call(o,"__proto__"))delete o.__proto__;for(let s of r){if(s==="__proto__")continue;let i=an(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}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 o=e[r],s=t[r],i=an(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Ro(e,t,n){let r=new Map,o,s=new Map,i=(f,h)=>{let E;if(f.code==="unrecognized_keys"&&!f.path?.length)o??(o=f),E=f.keys;else if(f.code==="invalid_key"&&f.origin==="record"&&f.path?.length===1){let k=String(f.path[0]);if(!s.has(k))s.set(k,f);E=[k]}else return!1;for(let k of E){if(!r.has(k))r.set(k,{});r.get(k)[h]=!0}return!0};for(let f of t.issues)if(!i(f,"l"))e.issues.push(f);for(let f of n.issues)if(!i(f,"r"))e.issues.push(f);let m=[...r].filter(([,f])=>f.l&&f.r).map(([f])=>f);if(m.length){let f=o?m.filter((h)=>o.keys.includes(h)):[];if(f.length)e.issues.push({...o,keys:f});for(let h of m)if(!f.includes(h)&&s.has(h))e.issues.push(s.get(h))}let g=an(t.value,n.value);if(!g.valid){if(se(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(g.mergeErrorPath)}`)}return e.value=g.data,e}var Es=y("$ZodRecord",(e,t)=>{z.init(e,t);let n=G.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let s=r.value;if(!Ee(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),r;let i=[],m=t.keyType._zod.values;if(m&&!t.partial){r.value=n?n.alloc(e,r,{},o):{};let g=new Set;for(let h of m)if(typeof h==="string"||typeof h==="number"||typeof h==="symbol"){if(g.add(typeof h==="number"?h.toString():h),h==="__proto__")continue;let E=t.keyType._zod.run({value:h,issues:[]},o);if(E instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(E.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:E.issues.map((b)=>ie(b,o,V())),input:h,path:[h],inst:e});continue}let k=E.value;if(k==="__proto__")continue;let S=t.valueType._zod.run({value:s[h],issues:[]},o);if(S instanceof Promise)i.push(S.then((b)=>{if(b.issues.length)r.issues.push(...ge(h,b.issues));r.value[k]=b.value}));else{if(S.issues.length)r.issues.push(...ge(h,S.issues));r.value[k]=S.value}}let f;for(let h in s)if(!g.has(h))if(t.mode==="loose"){if(h==="__proto__")continue;r.value[h]=s[h]}else f=f??[],f.push(h);if(f&&f.length>0)r.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:f,continue:!0})}else{r.value=n?n.alloc(e,r,{},o):{};let g;for(let f of Reflect.ownKeys(s)){if(f==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(s,f))continue;let h=t.keyType._zod.run({value:f,issues:[]},o);if(h instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof f==="string"&&ze.test(f)&&h.issues.length){let b=t.keyType._zod.run({value:Number(f),issues:[]},o);if(b instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(b.issues.length===0)h=b}if(h.issues.length){if(t.mode==="loose")r.value[f]=s[f];else if(m)g=g??[],g.push(f);else r.issues.push({code:"invalid_key",origin:"record",issues:h.issues.map((b)=>ie(b,o,V())),input:f,path:[f],inst:e});continue}let k=h.value;if(k==="__proto__")continue;let S=t.valueType._zod.run({value:s[f],issues:[]},o);if(S instanceof Promise)i.push(S.then((b)=>{if(b.issues.length)r.issues.push(...ge(f,b.issues));r.value[k]=b.value}));else{if(S.issues.length)r.issues.push(...ge(f,S.issues));r.value[k]=S.value}}if(g&&g.length>0)r.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:g,continue:!0})}if(i.length)return Promise.all(i).then(()=>r);return r}});var Ss=y("$ZodEnum",(e,t)=>{z.init(e,t);let n=De(t.entries),r=new Set(n);e._zod.values=r,N(e,"pattern",(o)=>{let s=De(o.def.entries).filter((i)=>pr.has(typeof i));return new RegExp(s.length?`^(${s.map((i)=>me(i.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,s)=>{let i=o.value;if(r.has(i))return o;return o.issues.push({code:"invalid_value",values:n,input:i,inst:e}),o}}),Ts=y("$ZodLiteral",(e,t)=>{z.init(e,t);let n=new Set(t.values);e._zod.values=n,N(e,"pattern",(r)=>{let o=r.def.values;return new RegExp(o.length?`^(${o.map((s)=>typeof s==="string"?me(s):s?me(s.toString()):String(s)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,o)=>{let s=r.value;if(n.has(s))return r;return r.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),r}});var ws=y("$ZodTransform",(e,t)=>{z.init(e,t),e._zod.optin="optional",G.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Ue(e.constructor.name);let o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then((i)=>(n.value=i,n));if(o instanceof Promise)throw new ae;return n.value=o,n}});function xo(e,t){return e.value=t.issues.length?void 0:t.value,e}var pn=y("$ZodOptional",(e,t)=>{z.init(e,t),N(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",N(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),N(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${Ye(r.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;let o=t.innerType._zod.run({value:n.value,issues:[]},r);if(o instanceof Promise)return o.then((s)=>xo(n,s));return xo(n,o)}return t.innerType._zod.run(n,r)}}),As=y("$ZodExactOptional",(e,t)=>{pn.init(e,t),N(e,"values",(n)=>n.def.innerType._zod.values),N(e,"pattern",(n)=>n.def.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),ks=y("$ZodNullable",(e,t)=>{z.init(e,t),N(e,"optin",(n)=>n.def.innerType._zod.optin),N(e,"optout",(n)=>n.def.innerType._zod.optout),N(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${Ye(r.source)}|null)$`):void 0}),N(e,"values",(n)=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>{if(n.value===null)return n;return t.innerType._zod.run(n,r)}}),bs=y("$ZodDefault",(e,t)=>{z.init(e,t),e._zod.optin="defaulted",N(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then((s)=>No(s,t));return No(o,t)}});function No(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Is=y("$ZodPrefault",(e,t)=>{z.init(e,t),e._zod.optin="defaulted",N(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,r)}}),vs=y("$ZodNonOptional",(e,t)=>{z.init(e,t),N(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(n,r)=>{let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then((s)=>Oo(s,e));return Oo(o,e)}});function Oo(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}function Co(e,t,n,r){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map((o)=>ie(o,r,V()))},input:e.value}),e}var Rs=y("$ZodCatch",(e,t)=>{z.init(e,t),N(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),N(e,"optout",(n)=>n.def.innerType._zod.optout),N(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run({value:n.value,issues:[]},r);if(o instanceof Promise)return o.then((s)=>Co(n,s,t,r));return Co(n,o,t,r)}});var xs=y("$ZodPipe",(e,t)=>{z.init(e,t),N(e,"values",(n)=>n.def.in._zod.values),N(e,"optin",(n)=>n.def.in._zod.optin),N(e,"optout",(n)=>n.def.out._zod.optout),N(e,"propValues",(n)=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let s=t.out._zod.run(n,r);if(s instanceof Promise)return s.then((i)=>lt(i,t.in,r));return lt(s,t.in,r)}let o=t.in._zod.run(n,r);if(o instanceof Promise)return o.then((s)=>lt(s,t.out,r));return lt(o,t.out,r)}});function lt(e,t,n){if(e.issues.some((r)=>r.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}var Ns=y("$ZodReadonly",(e,t)=>{z.init(e,t),N(e,"propValues",(n)=>n.def.innerType._zod.propValues),N(e,"values",(n)=>n.def.innerType._zod.values),N(e,"optin",(n)=>n.def.innerType?._zod?.optin),N(e,"optout",(n)=>n.def.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then(Lo);return Lo(o)}});function Lo(e){if(!e.memo)e.value=Object.freeze(e.value);return e}var Os=y("$ZodCustom",(e,t)=>{Z.init(e,t),z.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=(n)=>{let r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then((s)=>Do(s,n,r,e));Do(o,n,r,e);return}});function Do(e,t,n,r){if(!e){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};if(r._zod.def.params)o.params=r._zod.def.params;t.issues.push(Se(o))}}class Ls extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var gn="~memo",Cs=[];function Ds(e){return e!==null&&typeof e==="object"}function mn(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var Ps=new WeakMap,Fe=0,yt=1,Be=2;function Et(e,t,n){let r=Ps.get(e);if(r!==void 0)return r?Be:Fe;if(t.has(e))return Be;t.add(e);let o=Fe,s=(h)=>{if(o!==Be&&h?._zod){let E=Et(h,t,n);if(E>o)o=E}},i=(h,E)=>{let k=Fe;for(let S of Reflect.ownKeys(h)){let b=Object.getOwnPropertyDescriptor(h,S);if(E&&!b.enumerable)continue;let R=b.get?yt:b.value?._zod?Et(b.value,t,n):Fe;if(R>k)k=R}return k},m=(h)=>{if(h>o)o=h},g=e._zod.def,f=g.type;switch(f){case"object":{let h=$e(g);m(h?i(h,!0):yt),s(g.catchall);break}case"array":s(g.element);break;case"tuple":for(let h of g.items)s(h);s(g.rest);break;case"record":case"map":s(g.keyType),s(g.valueType);break;case"set":s(g.valueType);break;case"union":for(let h of g.options)s(h);break;case"intersection":s(g.left),s(g.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":s(g.innerType);break;case"pipe":s(g.in),s(g.out);break;case"function":s(g.input),s(g.output);break;case"lazy":{let h=g._cachedInner??(n?e._zod.innerType:void 0);m(h?Et(h,t,!1):yt);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 h in g){let E=Object.getOwnPropertyDescriptor(g,h);if(!E||E.get)continue;let k=E.value;if(!k||typeof k!=="object")continue;if(k._zod)s(k);else if(Array.isArray(k))for(let S of k)s(S)}}return t.delete(e),Hd(e,o)}function Hd(e,t){if(t!==yt)Ps.set(e,t===Be);return t}function Fd(e,t){let n=e.buckets.get(t);if(!n)n=new WeakMap,e.buckets.set(t,n);return n}var ht,_t=[],Bd={alloc(e,t,n){let r=ht;if(!r)return n;ht=void 0;let o={value:n,issues:null};return r.set(t.value,o),_t.push(o),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let n=e._zod.parse,r=(o,s)=>{if(s.direction!=="backward"&&Zd(s,o.value))throw new Ls;return n(o,s)};if(e._zod.parse=r,e._zod.run===n)e._zod.run=r})},attach(e){var t;let n,r=!1,o,s;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let i=e._zod.parse,m=(g,f)=>{if(n===void 0){let O=Et(e,new Set,!1);if(O===Fe){if(e._zod.parse=i,e._zod.run===m)e._zod.run=i;return i(g,f)}if(O===Be||r)n=!0;else r=!0}let h=g.value;if(!Ds(h))return i(g,f);let E=f[gn];if(!E)E={buckets:new WeakMap,backEdges:void 0},f[gn]=E;let k;if(o===f)k=s;else k=Fd(E,e),o=f,s=k;let S=k.get(h);if(S){if(g.value=S.value,S.issues){if(S.issues.length)g.issues.push(...mn(S.issues))}else g.memo=!0,E.backEdges??(E.backEdges=new WeakSet),E.backEdges.add(S.value);return g}ht=k;let b=_t.length,R=i(g,f);ht=void 0;let x=_t.length>b?_t.pop():void 0;if(R instanceof Promise)return R.then((O)=>{if(x)x.issues=O.issues.length?mn(O.issues):Cs;return O});if(x)x.issues=R.issues.length?mn(R.issues):Cs;return R};if(e._zod.parse=m,e._zod.run===i)e._zod.run=m})}};function Ms(){return Bd}function Zd(e,t){let n=e[gn]?.backEdges;return n!==void 0&&Ds(t)&&n.has(t)}var jd=()=>{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(s){return e[s]??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 o(s,i){if(s==="number"&&typeof i==="number"&&!Number.isFinite(i))return String(i);return r[s]??s}return(s)=>{switch(s.code){case"invalid_type":{let i=o(s.expected),m=_r(s.input),g=o(m,s.input);return`Invalid input: expected ${i}, received ${g}`}case"invalid_value":if(s.values.length===1)return`Invalid input: expected ${jt(s.values[0])}`;return`Invalid option: expected one of ${Ft(s.values,"|")}`;case"too_big":{let i=s.exact?"exactly ":s.inclusive?"<=":"<",m=t(s.origin);if(m)return`Too big: expected ${s.origin??"value"} to have ${i}${s.maximum.toString()} ${m.unit??"elements"}`;return`Too big: expected ${s.origin??"value"} to be ${i}${s.maximum.toString()}`}case"too_small":{let i=s.exact?"exactly ":s.inclusive?">=":">",m=t(s.origin);if(m)return`Too small: expected ${s.origin} to have ${i}${s.minimum.toString()} ${m.unit}`;return`Too small: expected ${s.origin} to be ${i}${s.minimum.toString()}`}case"invalid_format":{let i=s;if(i.format==="starts_with")return`Invalid string: must start with "${i.prefix}"`;if(i.format==="ends_with")return`Invalid string: must end with "${i.suffix}"`;if(i.format==="includes")return`Invalid string: must include "${i.includes}"`;if(i.format==="regex")return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${n[i.format]??s.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${s.divisor}`;case"unrecognized_keys":return`Unrecognized key${s.keys.length>1?"s":""}: ${Ft(s.keys,", ")}`;case"invalid_key":return`Invalid key in ${s.origin}`;case"invalid_union":if(s.options&&Array.isArray(s.options)&&s.options.length>0)return`Invalid discriminator value. Expected ${s.options.map((m)=>`'${m}'`).join(" | ")}`;if(s.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${s.origin}`;default:return"Invalid input"}}};function fn(){return{localeError:jd()}}var $s;class Us{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return 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)}}function Jd(){return new Us}($s=globalThis).__zod_globalRegistry??($s.__zod_globalRegistry=Jd());var Te=globalThis.__zod_globalRegistry;function zs(e){if(e.checks)e.checks=[...e.checks];return e}function Ws(e,t){return new e(zs({type:"string",...v(t)}))}function Hs(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...v(t)})}function Fs(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...v(t)})}function Bs(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...v(t)})}function Zs(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v(t)})}function js(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v(t)})}function Js(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v(t)})}function Gs(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...v(t)})}function Ks(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...v(t)})}function qs(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...v(t)})}function Vs(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...v(t)})}function Xs(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...v(t)})}function Ys(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...v(t)})}function Qs(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...v(t)})}function ei(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...v(t)})}function ti(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...v(t)})}function ni(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...v(t)})}function ri(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v(t)})}function oi(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v(t)})}function si(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...v(t)})}function ii(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...v(t)})}function ai(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...v(t)})}function ci(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...v(t)})}function di(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v(t)})}function ui(e,t){return new e({type:"string",format:"date",check:"string_format",...v(t)})}function li(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...v(t)})}function pi(e,t){return new e({type:"string",format:"duration",check:"string_format",...v(t)})}function mi(e,t){return new e(zs({type:"number",checks:[],...v(t)}))}function gi(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...v(t)})}function fi(e,t){return new e({type:"boolean",...v(t)})}function hi(e){return new e({type:"unknown"})}function _i(e,t){return new e({type:"never",...v(t)})}function St(e,t){return new rn({check:"less_than",...v(t),value:e,inclusive:!1})}function Ze(e,t){return new rn({check:"less_than",...v(t),value:e,inclusive:!0})}function Tt(e,t){return new on({check:"greater_than",...v(t),value:e,inclusive:!1})}function je(e,t){return new on({check:"greater_than",...v(t),value:e,inclusive:!0})}function wt(e,t){return new lo({check:"multiple_of",...v(t),value:e})}function At(e,t){return new mo({check:"max_length",...v(t),maximum:e})}function ve(e,t){return new go({check:"min_length",...v(t),minimum:e})}function kt(e,t){return new fo({check:"length_equals",...v(t),length:e})}function hn(e,t){return new ho({check:"string_format",format:"regex",...v(t),pattern:e})}function _n(e){return new _o({check:"string_format",format:"lowercase",...v(e)})}function yn(e){return new yo({check:"string_format",format:"uppercase",...v(e)})}function En(e,t){return new Eo({check:"string_format",format:"includes",...v(t),includes:e})}function Sn(e,t){return new So({check:"string_format",format:"starts_with",...v(t),prefix:e})}function Tn(e,t){return new To({check:"string_format",format:"ends_with",...v(t),suffix:e})}function fe(e){return new wo({check:"overwrite",tx:e})}function wn(e){return fe((t)=>t.normalize(e))}function An(){return fe((e)=>e.trim())}function kn(){return fe((e)=>e.toLowerCase())}function bn(){return fe((e)=>e.toUpperCase())}function In(){return fe((e)=>ur(e))}function yi(e,t,n){return new e({type:"array",element:t,...v(n)})}function Ei(e,t,n){return new e({type:"custom",check:"custom",fn:t,...v(n)})}function Si(e,t){let n=Gd((r)=>(r.addIssue=(o)=>{if(typeof o==="string")r.issues.push(Se(o,r.value,n._zod.def));else{let s=o;if(s.fatal)s.continue=!1;if(s.code??(s.code="custom"),!("input"in s))s.input=r.value;s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),r.issues.push(Se(s))}},e(r.value,r)),t);return n}function Gd(e,t){let n=new Z({check:"custom",...v(t)});return n._zod.check=e,n}function Je(e,...t){for(let n of t)for(let r of Reflect.ownKeys(n))if(Object.prototype.propertyIsEnumerable.call(n,r))Q(e,r,n[r]);return e}function Rn(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??Te,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 ue(e,t,n,r,o){let s=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:r.path,message:o}):t.unrepresentable;if(s==="any")return!1;if(s===void 0||s==="throw")throw Error(o);return Object.assign(n,s),!0}function F(e,t,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,n.schemaPath.includes(e))s.cycle=n.path;return s.schema}let i={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,i),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let m=e._zod.toJSONSchema?.();if(m)i.schema=m;else{let h={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,h);else{let k=i.schema,S=t.processors[o.type];if(!S)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);S(e,t,k,h)}let E=e._zod.parent;if(E){if(!i.ref)i.ref=E;F(E,t,h),t.seen.get(E).isParent=!0}}let g=t.metadataRegistry.get(e);if(g)Je(i.schema,g);if(t.io==="input"&&J(e))delete i.schema.examples,delete i.schema.default;if(t.io==="input"&&"_prefault"in i.schema)(r=i.schema).default??(r.default=i.schema._prefault);return delete i.schema._prefault,t.seen.get(e).schema}function Ti(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function xn(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 i of e.seen.entries()){let m=e.metadataRegistry.get(i[0])?.id;if(m){let g=r.get(m);if(g&&g!==i[0])throw Error(`Duplicate schema id "${m}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(m,i[0])}}let o=(i)=>{let m=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let E=e.external.registry.get(i[0])?.id,k=e.external.uri??((b)=>b);if(E)return{ref:k(E)};let S=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=S,{defId:S,ref:`${k("__shared")}#/${m}/${Ti(S)}`}}let g="#",f=`${g}/${m}/`;if(i[1]===n&&!i[1].schema.id)return{ref:g};let h=i[1].schema.id??`__schema${e.counter++}`;return{defId:h,ref:f+Ti(h)}},s=(i)=>{if(i[1].schema.$ref)return;let m=i[1],{ref:g,defId:f}=o(i);if(m.def={...m.schema},f)m.defId=f;let h=m.schema;for(let E in h)delete h[E];h.$ref=g};if(e.cycles==="throw")for(let i of e.seen.entries()){let m=i[1];if(m.cycle)throw Error(`Cycle detected: #/${m.cycle?.join("/")}/<root>
|
|
56
|
+
|
|
57
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let m=i[1];if(t===i[0]){s(i);continue}if(e.external){let f=e.external.registry.get(i[0])?.id;if(t!==i[0]&&f){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(m.cycle){s(i);continue}if(m.count>1){if(e.reused==="ref")s(i)}}if(e.external)e.sharedDefsExtractedFor=e.external}function ki(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let r of t){if(!r||typeof r!=="object")return;ki(r);let o=Object.keys(r);if(o.length!==1||o[0]!=="type")return;let s=r.type;for(let i of Array.isArray(s)?s:[s]){if(typeof i!=="string")return;if(!n.includes(i))n.push(i)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var bi=new Set(["type","properties","required","additionalProperties"]),wi=["oneOf","anyOf"];function Ai(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function vn(e){let t=[];for(let s of e){if(typeof s!=="object"||s.type!=="object")return null;for(let i in s)if(!bi.has(i))return null;t.push(s)}let n={},r=new Set;for(let s of t){for(let i in s.properties){if(Object.prototype.hasOwnProperty.call(n,i))continue;let m=[];for(let f of t){let h=f.properties?.[i]??Ai(f);if(h===null||h===void 0)continue;if(!m.some((E)=>JSON.stringify(E)===JSON.stringify(h)))m.push(h)}let g=m.length===1?m[0]:vn(m)??{allOf:m};Q(n,i,g)}for(let i of s.required??[])r.add(i)}let o={type:"object",properties:n};if(r.size)o.required=[...r];if(t.every((s)=>s.additionalProperties===!1))o.additionalProperties=!1;else{let s=[];for(let i of t){let m=Ai(i);if(m&&!s.some((g)=>JSON.stringify(g)===JSON.stringify(m)))s.push(m)}if(s.length===1)o.additionalProperties=s[0];else if(s.length>1)o.additionalProperties={allOf:s}}return o}function Kd(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of bi)if(o in e)return;let n=t.filter((o)=>wi.some((s)=>Array.isArray(o[s]))),r=null;if(!n.length)r=vn(t);else{let o=n[0],s=wi.find((g)=>Array.isArray(o[g]));if(Object.keys(o).length!==1)return;let i=t.filter((g)=>g!==o),m=o[s].map((g)=>vn([...i,g]));if(m.some((g)=>!g))return;r={[s]:m}}if(!r)return;delete e.allOf,Je(e,r)}function Nn(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=(m)=>{let g=e.seen.get(m);if(g.ref===null)return;let f=g.def??g.schema,h={...f},E=g.ref;if(g.ref=null,E){r(E);let S=e.seen.get(E),b=S.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))f.allOf=f.allOf??[],f.allOf.push(b);else Je(f,b);if(Je(f,h),m._zod.parent===E)for(let x in f){if(x==="$ref"||x==="allOf")continue;if(!(x in h))delete f[x]}if(b.$ref&&S.def)for(let x in f){if(x==="$ref"||x==="allOf")continue;if(x in S.def&&JSON.stringify(f[x])===JSON.stringify(S.def[x]))delete f[x]}}let k=m._zod.parent;if(k&&k!==E){r(k);let S=e.seen.get(k);if(S?.schema.$ref){if(f.$ref=S.schema.$ref,S.def)for(let b in f){if(b==="$ref"||b==="allOf")continue;if(b in S.def&&JSON.stringify(f[b])===JSON.stringify(S.def[b]))delete f[b]}}}e.override({zodSchema:m,jsonSchema:f,path:g.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let m of[...e.seen.entries()].reverse())r(m[0]);if(e.target!=="openapi-3.0")for(let m of e.seen.entries())ki(m[1].def??m[1].schema);for(let m of e.deferred)m();if(e.intersections.length){let m=new Map;for(let g of e.seen.values())for(let f of[g.schema,g.def]){let h=f?.allOf;if(!Array.isArray(h))continue;let E=m.get(h);if(E)E.push(f);else m.set(h,[f])}for(let g of e.intersections)for(let f of m.get(g)??[])Kd(f)}}let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let m=e.external.registry.get(t)?.id;if(!m)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(m)}Je(o,n.defId?n.schema:n.def??n.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&o.id===s)delete o.id;let i=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let m of e.seen.entries()){let g=m[1];if(g.def&&g.defId){if(g.def.id===g.defId)delete g.def.id;Q(i,g.defId,g.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(i).length>0)if(e.target==="draft-2020-12")o.$defs=i;else o.definitions=i;try{let m=JSON.parse(JSON.stringify(o));return Object.defineProperty(m,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ge(t,"input",e.processors),output:Ge(t,"output",e.processors)}},enumerable:!1,writable:!1}),m}catch(m){throw Error("Error converting schema to JSON.")}}function J(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(r.type==="transform")return!0;if(r.type==="array")return J(r.element,n);if(r.type==="set")return J(r.valueType,n);if(r.type==="lazy")return J(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault"||r.type==="catch")return J(r.innerType,n);if(r.type==="intersection")return J(r.left,n)||J(r.right,n);if(r.type==="record"||r.type==="map")return J(r.keyType,n)||J(r.valueType,n);if(r.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return J(r.in,n)||J(r.out,n)}if(r.type==="object"){for(let o in r.shape)if(J(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(J(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(J(o,n))return!0;if(r.rest&&J(r.rest,n))return!0;return!1}return!1}var Ii=(e,t={})=>(n)=>{let r=Rn({...n,processors:t});return F(e,r),xn(r,e),Nn(r,e)},Ge=(e,t,n={})=>(r)=>{let{libraryOptions:o,target:s}=r??{},i=Rn({...o??{},target:s,io:t,processors:n});return F(e,i),xn(i,e),Nn(i,e)};var Re=(e,t,n)=>{if(e[t]===void 0||n>e[t])e[t]=n},xe=(e,t,n)=>{if(e[t]===void 0||n<e[t])e[t]=n},vi=(e,t)=>{Re(e,"minimum",t),xe(e,"maximum",t)},Oi=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},Ci=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Li=(e,t)=>{e.mime=e.mime?e.mime.filter((n)=>t.includes(n)):[...t]},Di=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},Ri=(e,t)=>Re(e,"minimum",t.minimum),xi=(e,t)=>xe(e,"maximum",t.maximum),Ni=(e)=>(t,n)=>{Di(t,n.format);let[r,o]=e[n.format];Re(t,"minimum",r),xe(t,"maximum",o)},qd={greater_than:(e,t)=>Re(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>xe(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Oi(e,t.value),number_format:Ni(Qe),bigint_format:Ni(Jt),min_length:Ri,max_length:xi,length_equals:(e,t)=>vi(e,t.length),min_size:Ri,max_size:xi,size_equals:(e,t)=>vi(e,t.size),string_format:(e,t)=>{if(Di(e,t.format),t.pattern)Ci(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>Li(e,t.mime)};function ee(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let s of r)qd[s._zod.def.check]?.(t,s._zod.def);let o=e._zod.bag;if(o.minimum!==void 0)Re(t,"minimum",o.minimum);if(o.exclusiveMinimum!==void 0)Re(t,"exclusiveMinimum",o.exclusiveMinimum);if(o.maximum!==void 0)xe(t,"maximum",o.maximum);if(o.exclusiveMaximum!==void 0)xe(t,"exclusiveMaximum",o.exclusiveMaximum);if(o.multipleOf!==void 0)Oi(t,o.multipleOf);if(o.format!==void 0){if(t.format??(t.format=o.format),o.format.includes("int"))t.isInt=!0}if(o.mime)Li(t,o.mime);for(let s of o.patterns??[])Ci(t,s);return t}var Vd={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Xd=new Map([[dn,Yr],[ft,Qr]]),Pi=(e)=>Xd.get(e)??e,Mi=(e,t,n,r)=>{let o=n;o.type="string";let{minimum:s,maximum:i,format:m,patterns:g,contentEncoding:f,laxFormat:h}=ee(e);if(typeof s==="number")o.minLength=s;if(typeof i==="number")o.maxLength=i;if(m){if(o.format=Vd[m]??m,o.format==="")delete o.format;if(m==="time"||h)delete o.format}if(f)o.contentEncoding=f;if(g&&g.size>0){let E=[...g].map(Pi);if(E.length===1)o.pattern=E[0].source;else if(E.length>1)o.allOf=[...E.map((k)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:k.source}))]}},$i=(e,t,n,r)=>{let o=n,{minimum:s,maximum:i,multipleOf:m,exclusiveMaximum:g,exclusiveMinimum:f,isInt:h}=ee(e);o.type=h?"integer":"number";let E=typeof f==="number"&&f>=(s??Number.NEGATIVE_INFINITY),k=typeof g==="number"&&g<=(i??Number.POSITIVE_INFINITY),S=t.target==="draft-04"||t.target==="openapi-3.0";if(E)if(S)o.minimum=f,o.exclusiveMinimum=!0;else o.exclusiveMinimum=f;else if(typeof s==="number")o.minimum=s;if(k)if(S)o.maximum=g,o.exclusiveMaximum=!0;else o.exclusiveMaximum=g;else if(typeof i==="number")o.maximum=i;if(m){let b=new Set;for(let O of m)if(Number.isFinite(O)&&O!==0)b.add(Math.abs(O));else ue(e,t,o,r,`A multipleOf divisor of ${O} cannot be represented in JSON Schema`);let[R,...x]=b;if(R!==void 0)o.multipleOf=R;if(x.length)o.allOf=[...o.allOf??[],...x.map((O)=>({multipleOf:O}))]}},Ui=(e,t,n,r)=>{n.type="boolean"};var zi=(e,t,n,r)=>{n.not={}};var Wi=(e,t,n,r)=>{};var Hi=(e,t,n,r)=>{let o=e._zod.def,s=De(o.entries);if(s.length===0){n.not={};return}if(s.every((i)=>typeof i==="number"))n.type="number";if(s.every((i)=>typeof i==="string"))n.type="string";n.enum=s},Fi=(e,t,n,r)=>{let o=e._zod.def;if(o.values.length===0){n.not={};return}let s=[];for(let i of o.values)if(i===void 0){if(ue(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i==="bigint"){if(ue(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;s.push(Number(i))}else s.push(i);if(s.length===0);else if(s.length===1){let i=s[0];if(n.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[i];else n.const=i}else{if(s.every((i)=>typeof i==="number"))n.type="number";if(s.every((i)=>typeof i==="string"))n.type="string";if(s.every((i)=>typeof i==="boolean"))n.type="boolean";if(s.every((i)=>i===null))n.type="null";n.enum=s}};var Bi=(e,t,n,r)=>{ue(e,t,n,r,"Custom types cannot be represented in JSON Schema")};var Zi=(e,t,n,r)=>{ue(e,t,n,r,"Transforms cannot be represented in JSON Schema")};var ji=(e,t,n,r)=>{let o=n,s=e._zod.def,{minimum:i,maximum:m}=ee(e);if(typeof i==="number")o.minItems=i;if(typeof m==="number")o.maxItems=m;o.type="array",o.items=F(s.element,t,{...r,path:[...r.path,"items"]})};function bt(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return bt(t.out);if(t.type==="catch")return bt(t.innerType);return e._zod.optin}var Ji=(e,t,n,r)=>{let o=n,s=e._zod.def,i=s.shape;if(Object.getOwnPropertySymbols(i).length&&ue(e,t,o,r,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(let f in i)Q(o.properties,f,F(i[f],t,{...r,path:[...r.path,"properties",f]}));let g=[];for(let f of Object.keys(i)){let h=s.shape[f];if(t.io==="input"?bt(h)===void 0:h._zod.optout===void 0)g.push(f)}if(g.length>0)o.required=g;if(s.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")o.additionalProperties=!1}else if(s.catchall)o.additionalProperties=F(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},Gi=(e,t,n,r)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((m,g)=>F(m,t,{...r,path:[...r.path,s?"oneOf":"anyOf",g]}));if(s)n.oneOf=i;else n.anyOf=i},Ki=(e,t,n,r)=>{let o=e._zod.def,s=F(o.left,t,{...r,path:[...r.path,"allOf",0]}),i=F(o.right,t,{...r,path:[...r.path,"allOf",1]}),m=(f)=>("allOf"in f)&&Object.keys(f).length===1,g=[...m(s)?s.allOf:[s],...m(i)?i.allOf:[i]];n.allOf=g,t.intersections.push(g)};function On(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let b=e.get(t)?.def;if(!b)return t;let R=On(e,b,n);return R===b?t:R}for(let b of["anyOf","oneOf"]){let R=t[b];if(!Array.isArray(R))continue;let x=R.map((O)=>On(e,O,n));if(x.some((O,Y)=>O!==R[Y]))t={...t,[b]:x}}let r=Array.isArray(t.type)?t.type:[t.type],o=!r.includes("string")&&r.some((b)=>b==="number"||b==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!s?.some((b)=>typeof b==="number"))return t;let{minimum:i,maximum:m,exclusiveMinimum:g,exclusiveMaximum:f,multipleOf:h,format:E,id:k,...S}=t;if(S.enum)S.enum=S.enum.map((b)=>typeof b==="number"?String(b):b);else if(typeof S.const==="number")S.const=String(S.const);if(!o)return S;if(S.type="string",!s)S.pattern=(r.includes("number")?ze:tn).source;return S}var Cn=new WeakMap;function Yd(e){let t=new Map;for(let r of e.seen.values())if(r.def&&!t.has(r.schema))t.set(r.schema,r);let n=new Map;for(let r of Cn.get(e)??[]){let o=e.seen.get(r),s=(o?.def??o?.schema)?.propertyNames;if(!s||s===!0||n.has(s))continue;let i=On(t,s,new Set);if(i!==s)n.set(s,i)}if(!n.size)return;for(let r of e.seen.values())for(let o of[r.schema,r.def]){let s=o&&n.get(o.propertyNames);if(s)o.propertyNames=s}}var qi=(e,t,n,r)=>{let o=n,s=e._zod.def;o.type="object";let i=s.keyType,m=ee(i).patterns;if(s.mode==="loose"&&m&&m.size>0){let h=F(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let E of m)Q(o.patternProperties,Pi(E).source,h)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=F(s.keyType,t,{...r,path:[...r.path,"propertyNames"]});let h=Cn.get(t);if(!h)h=[],Cn.set(t,h),t.deferred.push(()=>Yd(t));h.push(e)}o.additionalProperties=F(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let g=i._zod.values,f=t.io==="input"&&bt(s.valueType)!==void 0;if(g&&!s.partial&&!f){let h=[...g].filter((E)=>typeof E==="string"||typeof E==="number");if(h.length>0)o.required=h.map(String)}},Vi=(e,t,n,r)=>{let o=e._zod.def,s=F(o.innerType,t,r),i=t.seen.get(e);if(t.target==="openapi-3.0")i.ref=o.innerType,n.nullable=!0;else n.anyOf=[s,{type:"null"}]},Xi=(e,t,n,r)=>{let o=e._zod.def;F(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType},Ln=Symbol();function Yi(e,t,n,r,o){let s=!1,i=JSON.stringify(e,(m,g)=>{if(typeof g!=="bigint")return g;return s=!0,null});if(!s)return JSON.parse(i);return ue(t,n,r,o,"BigInt defaults cannot be represented in JSON Schema"),Ln}var Qi=(e,t,n,r)=>{let o=e._zod.def;F(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType;let i=Yi(o.defaultValue,e,t,n,r);if(i!==Ln)n.default=i},ea=(e,t,n,r)=>{let o=e._zod.def;F(o.innerType,t,r);let s=t.seen.get(e);if(s.ref=o.innerType,t.io!=="input")return;let i=Yi(o.defaultValue,e,t,n,r);if(i!==Ln)n._prefault=i},ta=(e,t,n,r)=>{let o=e._zod.def;F(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{ue(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=i},na=(e,t,n,r)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;F(i,t,r);let m=t.seen.get(e);m.ref=i},ra=(e,t,n,r)=>{let o=e._zod.def;F(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType,n.readOnly=!0};var Dn=(e,t,n,r)=>{let o=e._zod.def;F(o.innerType,t,r);let s=t.seen.get(e);s.ref=o.innerType};var oa=new WeakSet([Object.prototype,Error.prototype]);function It(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let r=n(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}var iu=(e,t)=>{br.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);if(oa.has(n))return;oa.add(n),It(n,"format",(r)=>(o)=>vr(r,o)),It(n,"flatten",(r)=>(o)=>Ir(r,o)),It(n,"addIssue",(r)=>(o)=>{r.issues.push(o),r.message=JSON.stringify(r.issues,Pe,2)}),It(n,"addIssues",(r)=>(o)=>{r.issues.push(...o),r.message=JSON.stringify(r.issues,Pe,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})};var X=y("ZodError",iu,void 0,{Parent:Error});var sa=it(X),ia=at(X),aa=ct(X),ca=dt(X),da=xr(X),ua=Nr(X),la=Or(X),pa=Cr(X),ma=Lr(X),ga=Dr(X),fa=Pr(X),ha=Mr(X);function cu(){if(!G.localeError)V(fn())}function Rt(){if(!G.memoizer)V({memoizer:Ms()})}var W=y("ZodType",(e,t)=>(cu(),z.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(q(t,{checks:[...t.checks??[],...e.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return oe(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(ol(e,t))},superRefine(e,t){return this.check(sl(e,t))},overwrite(e){return this.check(fe(e))},optional(){return Ea(this)},exactOptional(){return ju(this)},nullable(){return Sa(this)},nullish(){return Ea(Sa(this))},nonoptional(e){return Xu(this,e)},array(){return ne(this)},or(e){return we([this,e])},and(e){return Hu(this,e)},transform(e){return Ta(this,Zu(e))},default(e){return Ku(this,e)},prefault(e){return Vu(this,e)},catch(e){return Qu(this,e)},pipe(e){return Ta(this,e)},readonly(){return nl(this)},describe(e){let t=this.clone();return Te.add(t,{description:e}),t},meta(...e){if(e.length===0)return Te.get(this);let t=this.clone();return Te.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return ot(this,"~standard",{...cn(this),jsonSchema:{input:Ge(this,"input"),output:Ge(this,"output")}})},set "~standard"(e){de(this,"~standard",e)},parse:function e(t,n){return sa(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await ia(this,t,n,{callee:e})},safeParse(e,t){return aa(this,e,t)},async safeParseAsync(e,t){return ca(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){de(this,"spa",e)},validate(e,t){return Xt(this,e,t)},validateAsync(e,t){return Yt(this,e,t)},encode:function e(t,n){return da(this,t,n,{callee:e})},decode:function e(t,n){return ua(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await la(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await pa(this,t,n,{callee:e})},safeEncode(e,t){return ma(this,e,t)},safeDecode(e,t){return ga(this,e,t)},async safeEncodeAsync(e,t){return fa(this,e,t)},async safeDecodeAsync(e,t){return ha(this,e,t)},toJSONSchema(e){return Ii(this,{})(e)},get description(){return Te.get(this)?.description},get _def(){return this._zod.def}}),wa=y("_ZodString",(e,t)=>{gt.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Mi(e,n,r,o)},Er({format:(e)=>ee(e).format??null,minLength:(e)=>ee(e).minimum??null,maxLength:(e)=>ee(e).maximum??null},{regex(...e){return this.check(hn(...e))},includes(...e){return this.check(En(...e))},startsWith(...e){return this.check(Sn(...e))},endsWith(...e){return this.check(Tn(...e))},min(...e){return this.check(ve(...e))},max(...e){return this.check(At(...e))},length(...e){return this.check(kt(...e))},nonempty(...e){return this.check(ve(1,...e))},lowercase(e){return this.check(_n(e))},uppercase(e){return this.check(yn(e))},trim(){return this.check(An())},normalize(...e){return this.check(wn(...e))},toLowerCase(){return this.check(kn())},toUpperCase(){return this.check(bn())},slugify(){return this.check(In())}})),du=y("ZodString",(e,t)=>{gt.init(e,t),wa.init(e,t)},{email(e){return this.check(Hs(gu,e))},url(e){return this.check(Gs(hu,e))},jwt(e){return this.check(ci(Ou,e))},emoji(e){return this.check(Ks(_u,e))},guid(e){return this.check(Fs(fu,e))},uuid(e){return this.check(Bs(vt,e))},uuidv4(e){return this.check(Zs(vt,e))},uuidv6(e){return this.check(js(vt,e))},uuidv7(e){return this.check(Js(vt,e))},nanoid(e){return this.check(qs(yu,e))},cuid(e){return this.check(Vs(Eu,e))},cuid2(e){return this.check(Xs(Su,e))},ulid(e){return this.check(Ys(Tu,e))},base64(e){return this.check(si(Ru,e))},base64url(e){return this.check(ii(xu,e))},xid(e){return this.check(Qs(wu,e))},ksuid(e){return this.check(ei(Au,e))},ipv4(e){return this.check(ti(ku,e))},ipv6(e){return this.check(ni(bu,e))},cidrv4(e){return this.check(ri(Iu,e))},cidrv6(e){return this.check(oi(vu,e))},e164(e){return this.check(ai(Nu,e))},datetime(e){return this.check(di(uu,e))},date(e){return this.check(ui(lu,e))},time(e){return this.check(li(pu,e))},duration(e){return this.check(pi(mu,e))}});function T(e){return Ws(du,e)}var H=y("ZodStringFormat",(e,t)=>{U.init(e,t),wa.init(e,t)}),uu=y("ZodISODateTime",(e,t)=>{qo.init(e,t),H.init(e,t)}),lu=y("ZodISODate",(e,t)=>{Vo.init(e,t),H.init(e,t)}),pu=y("ZodISOTime",(e,t)=>{Xo.init(e,t),H.init(e,t)}),mu=y("ZodISODuration",(e,t)=>{Yo.init(e,t),H.init(e,t)}),gu=y("ZodEmail",(e,t)=>{Uo.init(e,t),H.init(e,t)});var fu=y("ZodGUID",(e,t)=>{Mo.init(e,t),H.init(e,t)});var vt=y("ZodUUID",(e,t)=>{$o.init(e,t),H.init(e,t)});var hu=y("ZodURL",(e,t)=>{Ho.init(e,t),H.init(e,t)});var _u=y("ZodEmoji",(e,t)=>{Fo.init(e,t),H.init(e,t)});var yu=y("ZodNanoID",(e,t)=>{Bo.init(e,t),H.init(e,t)});var Eu=y("ZodCUID",(e,t)=>{Zo.init(e,t),H.init(e,t)});var Su=y("ZodCUID2",(e,t)=>{jo.init(e,t),H.init(e,t)});var Tu=y("ZodULID",(e,t)=>{Jo.init(e,t),H.init(e,t)});var wu=y("ZodXID",(e,t)=>{Go.init(e,t),H.init(e,t)});var Au=y("ZodKSUID",(e,t)=>{Ko.init(e,t),H.init(e,t)});var ku=y("ZodIPv4",(e,t)=>{Qo.init(e,t),H.init(e,t)});var bu=y("ZodIPv6",(e,t)=>{ts.init(e,t),H.init(e,t)});var Iu=y("ZodCIDRv4",(e,t)=>{ns.init(e,t),H.init(e,t)});var vu=y("ZodCIDRv6",(e,t)=>{rs.init(e,t),H.init(e,t)});var Ru=y("ZodBase64",(e,t)=>{ss.init(e,t),H.init(e,t)});var xu=y("ZodBase64URL",(e,t)=>{is.init(e,t),H.init(e,t)});var Nu=y("ZodE164",(e,t)=>{as.init(e,t),H.init(e,t)});var Ou=y("ZodJWT",(e,t)=>{cs.init(e,t),H.init(e,t)});var Aa=y("ZodNumber",(e,t)=>{un.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>$i(e,n,r,o),e.isFinite=!0},Er({minValue:(e)=>{let{minimum:t,exclusiveMinimum:n}=ee(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:n}=ee(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:n}=ee(e);return!!t||!!n?.some(Number.isSafeInteger)},format:(e)=>ee(e).format??null},{gt(e,t){return this.check(Tt(e,t))},gte(e,t){return this.check(je(e,t))},min(e,t){return this.check(je(e,t))},lt(e,t){return this.check(St(e,t))},lte(e,t){return this.check(Ze(e,t))},max(e,t){return this.check(Ze(e,t))},int(e){return this.check(_a(e))},safe(e){return this.check(_a(e))},positive(e){return this.check(Tt(0,e))},nonnegative(e){return this.check(je(0,e))},negative(e){return this.check(St(0,e))},nonpositive(e){return this.check(Ze(0,e))},multipleOf(e,t){return this.check(wt(e,t))},step(e,t){return this.check(wt(e,t))},finite(){return this}}));function le(e){return mi(Aa,e)}var Cu=y("ZodNumberFormat",(e,t)=>{ds.init(e,t),Aa.init(e,t)});function _a(e){return gi(Cu,e)}var Lu=y("ZodBoolean",(e,t)=>{us.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ui(e,n,r,o)});function Ke(e){return fi(Lu,e)}var Du=y("ZodUnknown",(e,t)=>{ls.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Wi(e,n,r,o)});function he(){return hi(Du)}var Pu=y("ZodNever",(e,t)=>{ps.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>zi(e,n,r,o)});function Mu(e){return _i(Pu,e)}var $u=y("ZodArray",(e,t)=>{Rt(),ms.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ji(e,n,r,o),e.element=t.element},{min(e,t){return this.check(ve(e,t))},nonempty(e){return this.check(ve(1,e))},max(e,t){return this.check(At(e,t))},length(e,t){return this.check(kt(e,t))},unwrap(){return this.element}});function ne(e,t){return yi($u,e,t)}var Uu=y("ZodObject",(e,t)=>{Rt(),hs.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ji(e,n,r,o),gd(e,"shape",(n)=>n._zod.def.shape,!1)},{keyof(){return K(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(q(this._zod.def,{catchall:e}))},passthrough(){return this.clone(q(this._zod.def,{catchall:he()}))},loose(){return this.clone(q(this._zod.def,{catchall:he()}))},strict(){return this.clone(q(this._zod.def,{catchall:Mu()}))},strip(){return this.clone(q(this._zod.def,{catchall:void 0}))},extend(e){return id(this,e)},safeExtend(e){return ad(this,e)},merge(e){return cd(this,e)},pick(e){return od(this,e)},omit(e){return sd(this,e)},partial(...e){return fr(va,this,e[0])},exactPartial(...e){return fr(Ra,this,e[0],"exactPartial")},required(...e){return dd(xa,this,e[0])}});function I(e,t){let n={type:"object",shape:e??{},...v(t)};return new Uu(n)}var ka=y("ZodUnion",(e,t)=>{ln.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Gi(e,n,r,o),e.options=t.options});function we(e,t){return new ka({type:"union",options:e,...v(t)})}var zu=y("ZodDiscriminatedUnion",(e,t)=>{ka.init(e,t),_s.init(e,t)});function ba(e,t,n){return new zu({type:"union",options:t,discriminator:e,...v(n)})}var Wu=y("ZodIntersection",(e,t)=>{ys.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Ki(e,n,r,o)});function Hu(e,t){return new Wu({type:"intersection",left:e,right:t})}var ya=y("ZodRecord",(e,t)=>{Rt(),Es.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>qi(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType});function Ia(e,t,n){if(!t||!t._zod)return new ya({type:"record",keyType:T(),valueType:e,...v(t)});return new ya({type:"record",keyType:e,valueType:t,...v(n)})}var Mn=y("ZodEnum",(e,t)=>{Ss.init(e,t),W.init(e,t),e._zod.processJSONSchema=(r,o,s)=>Hi(e,r,o,s),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=t.entries[i];else throw Error(`Key ${i} not found in enum`);return new Mn({...t,checks:[],...v(o),entries:s})},e.exclude=(r,o)=>{let s={...t.entries};for(let i of r)if(n.has(i))delete s[i];else throw Error(`Key ${i} not found in enum`);return new Mn({...t,checks:[],...v(o),entries:s})}});function K(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new Mn({type:"enum",entries:n,...v(t)})}var Fu=y("ZodLiteral",(e,t)=>{Ts.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Fi(e,n,r,o),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 C(e,t){return new Fu({type:"literal",values:Array.isArray(e)?e:[e],...v(t)})}var Bu=y("ZodTransform",(e,t)=>{Rt(),ws.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Zi(e,n,r,o),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Ue(e.constructor.name);n.addIssue=(s)=>{if(typeof s==="string")n.issues.push(Se(s,n.value,t));else{let i=s;if(i.fatal)i.continue=!1;if(i.code??(i.code="custom"),!("input"in i))i.input=n.value;i.inst??(i.inst=e),n.issues.push(Se(i))}};let o=t.transform(n.value,n);if(o instanceof Promise)return o.then((s)=>(n.value=s,n));return n.value=o,n}});function Zu(e){return new Bu({type:"transform",transform:e})}var va=y("ZodOptional",(e,t)=>{pn.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Dn(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Ea(e){return new va({type:"optional",innerType:e})}var Ra=y("ZodExactOptional",(e,t)=>{As.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Dn(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function ju(e){return new Ra({type:"optional",innerType:e})}var Ju=y("ZodNullable",(e,t)=>{ks.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Vi(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Sa(e){return new Ju({type:"nullable",innerType:e})}var Gu=y("ZodDefault",(e,t)=>{bs.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Qi(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Ku(e,t){return new Gu({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Zt(t)}})}var qu=y("ZodPrefault",(e,t)=>{Is.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ea(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Vu(e,t){return new qu({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Zt(t)}})}var xa=y("ZodNonOptional",(e,t)=>{vs.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Xi(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function Xu(e,t){return new xa({type:"nonoptional",innerType:e,...v(t)})}var Yu=y("ZodCatch",(e,t)=>{Rs.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ta(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Qu(e,t){return new Yu({type:"catch",innerType:e,catchValue:typeof t==="function"?t:Sr(t)})}var el=y("ZodPipe",(e,t)=>{xs.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>na(e,n,r,o),e.in=t.in,e.out=t.out});function Ta(e,t){return new el({type:"pipe",in:e,out:t})}var tl=y("ZodReadonly",(e,t)=>{Ns.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ra(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});function nl(e){return new tl({type:"readonly",innerType:e})}var rl=y("ZodCustom",(e,t)=>{Os.init(e,t),W.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Bi(e,n,r,o)});function ol(e,t={}){return Ei(rl,e,t)}function sl(e,t){return Si(e,t)}var Oa=60000,il={JOIN_LINK_INVALID:410,JOIN_LINK_NOT_FOUND:404,ROLE_NOT_ALLOWED:400,NOT_A_MEMBER:403,PEOPLE_LIMIT:409,AGENTS_LIMIT:409,FORBIDDEN:403,HOST_REGISTRATION_CANCELLED:410,HOST_REGISTRATION_CONFLICT:409,AGENT_HOST_CONFLICT:409,HOST_REGISTRATION_MISSING:409,HOST_REGISTRATION_UNSETTLED:503,INVALID_REQUEST:400,BAD_ORIGIN:403,UNAUTHENTICATED:401,WORKSPACE_NOT_FOUND:404},al={HOST_REGISTRATION_CONFLICT:"this code was redeemed by a different host registration; a computer that already has a host in this workspace joins with the claim it already holds, or the owner mints a new code",AGENT_HOST_CONFLICT:"an agent in this code already rides another active host; revoke that host, then mint a new code",HOST_REGISTRATION_CANCELLED:"the owner cancelled this registration; mint a new code",HOST_REGISTRATION_MISSING:"this workspace no longer holds the pending registration; mint a new code",HOST_REGISTRATION_UNSETTLED:`this workspace has not answered the registration within ${Oa/1000} seconds; the code is unspent, so run the same command again in a minute, or mint a new code`};function _(e){return typeof e==="string"&&Object.hasOwn(il,e)}var Ne=T().min(1).max(256),xt=T().regex(/^sha256:[a-f0-9]{64}$/u),Nt=T().min(1).max(64),cl=T().trim().min(1).max(64).regex(/^[^\u0000-\u001f\u007f]+$/u,"a name carries no control characters");var dl=cl,Ca=dl,qe=["codex","gemini","copilot","opencode","kilo","goose","pi","dsh","copapo","devin","cursor","amp","qwen","cline","omp"],Ve={codex:"Codex",gemini:"Gemini",copilot:"Copilot",opencode:"OpenCode",kilo:"Kilo",goose:"Goose",pi:"Pi",dsh:"dsh",copapo:"copapo",devin:"Devin",cursor:"Cursor",amp:"Amp",qwen:"Qwen Code",cline:"Cline",omp:"omp"},A=(e)=>typeof e==="string"&&Object.hasOwn(Ve,e),ul=K(qe),ll=I({code:T(),credentialHash:xt,pluginVersion:Nt,ahpdVersion:Nt,name:Ca.optional(),app:ul.optional(),hostId:T().min(1).max(128).optional()}).strict(),Na=I({workspaceId:Ne,hostId:Ne,ownerAccountId:Ne,credentialHash:xt,agentMemberIds:ne(Ne),pluginVersion:Nt,ahpdVersion:Nt,registrationFingerprint:xt,name:Ca.optional()}).strict(),La=I({workspaceId:Ne,hostId:Ne,registrationFingerprint:xt,state:K(["registered","cancelled"])}).strict(),pl=we([I({ok:C(!0),value:La}).strict(),I({ok:C(!1),code:K(["HOST_REGISTRATION_CONFLICT","AGENT_HOST_CONFLICT","HOST_REGISTRATION_MISSING"]),message:T()}).strict()]),_f=we([I({kind:C("register"),command:Na}).strict(),I({kind:C("cancel"),cancellation:we([I({kind:C("pending"),command:Na}).strict(),I({kind:C("registered"),receipt:La}).strict()])}).strict()]);var ml="0123456789ABCDEFGHJKMNPQRSTVWXYZ",gl=12;var fl=/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/u,hl=/^[0-9A-F]{4}$/u,_l=/^(?=.{1,64}$)[A-Za-z0-9][A-Za-z0-9._-]*(?: [A-Za-z0-9._-]+)*$/u,If=I({browser:T().trim().regex(_l),publicKey:T().regex(fl),personName:T().trim().min(1).max(120).nullable(),check:T().regex(hl)});function yl(e,t){let n=e.toUpperCase().replace(/[\s-]/g,"").replace(/O/g,"0").replace(/[IL]/g,"1");if(n.length!==t)return null;for(let r of n)if(!ml.includes(r))return null;return n}function l(e){return yl(e,gl)}var Ma="ht_session",$a="ht_auth_state";var bl=`${$a}=; Path=/auth; HttpOnly; Secure; SameSite=Lax; Max-Age=0`,Il=`${Ma}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`;var Ha;(function(e){e.Snapshot="snapshot",e.Replay="replay",e.Live="live"})(Ha||(Ha={}));var Fa;(function(e){e.Enabled="enabled",e.Disabled="disabled",e.Unconfigured="unconfigured"})(Fa||(Fa={}));var Un;(function(e){e.Creating="creating",e.Ready="ready",e.Failed="failed"})(Un||(Un={}));var Ot;(function(e){e[e.Idle=1]="Idle",e[e.Error=2]="Error",e[e.InProgress=8]="InProgress",e[e.InputNeeded=24]="InputNeeded",e[e.IsRead=32]="IsRead",e[e.IsArchived=64]="IsArchived"})(Ot||(Ot={}));var Ba;(function(e){e.Automation="automation"})(Ba||(Ba={}));var zn;(function(e){e.ChatInput="chatInput",e.ToolConfirmation="toolConfirmation",e.ToolClientExecution="toolClientExecution",e.ToolAuthentication="toolAuthentication"})(zn||(zn={}));var Wn;(function(e){e.Plugin="plugin",e.Directory="directory",e.Agent="agent",e.Skill="skill",e.Prompt="prompt",e.Rule="rule",e.Hook="hook",e.McpServer="mcpServer"})(Wn||(Wn={}));var Za;(function(e){e.Global="global",e.Workspace="workspace",e.Session="session"})(Za||(Za={}));var ja;(function(e){e.Loading="loading",e.Loaded="loaded",e.Degraded="degraded",e.Error="error"})(ja||(ja={}));var Hn;(function(e){e.Starting="starting",e.Ready="ready",e.AuthRequired="authRequired",e.Error="error",e.Stopped="stopped"})(Hn||(Hn={}));var Ja;(function(e){e.Required="required",e.Expired="expired",e.InsufficientScope="insufficientScope"})(Ja||(Ja={}));var Ga;(function(e){e.Shell="shell",e.Subagent="subagent"})(Ga||(Ga={}));var Ka;(function(e){e.User="user",e.Fork="fork",e.SideChat="sideChat",e.Tool="tool"})(Ka||(Ka={}));var qa;(function(e){e.Full="full",e.ReadOnly="read-only",e.Hidden="hidden"})(qa||(qa={}));var Fn;(function(e){e.Steering="steering",e.Queued="queued"})(Fn||(Fn={}));var Va;(function(e){e.Accept="accept",e.Decline="decline",e.Cancel="cancel"})(Va||(Va={}));var Xa;(function(e){e.Text="text",e.Number="number",e.Integer="integer",e.Boolean="boolean",e.SingleSelect="single-select",e.MultiSelect="multi-select"})(Xa||(Xa={}));var Ya;(function(e){e.Text="text",e.Number="number",e.Boolean="boolean",e.Selected="selected",e.SelectedMany="selected-many"})(Ya||(Ya={}));var Qa;(function(e){e.Draft="draft",e.Submitted="submitted",e.Skipped="skipped"})(Qa||(Qa={}));var Bn;(function(e){e.Complete="complete",e.Cancelled="cancelled",e.Error="error"})(Bn||(Bn={}));var ec;(function(e){e.Simple="simple",e.EmbeddedResource="embeddedResource",e.Resource="resource",e.Annotations="annotations",e.Chat="chat"})(ec||(ec={}));var tc;(function(e){e.User="user",e.Agent="agent",e.Tool="tool",e.Automation="automation",e.SystemNotification="systemNotification"})(tc||(tc={}));var Zn;(function(e){e.Markdown="markdown",e.ContentRef="contentRef",e.ToolCall="toolCall",e.Reasoning="reasoning",e.SystemNotification="systemNotification",e.InputRequest="inputRequest",e.Error="error"})(Zn||(Zn={}));var jn;(function(e){e.Streaming="streaming",e.PendingConfirmation="pending-confirmation",e.Running="running",e.AuthRequired="auth-required",e.PendingResultConfirmation="pending-result-confirmation",e.Completed="completed",e.Cancelled="cancelled"})(jn||(jn={}));var Jn;(function(e){e.NotNeeded="not-needed",e.UserAction="user-action",e.Setting="setting"})(Jn||(Jn={}));var nc;(function(e){e.Judge="judge"})(nc||(nc={}));var rc;(function(e){e.Loading="loading",e.Complete="complete"})(rc||(rc={}));var Gn;(function(e){e.Denied="denied",e.Skipped="skipped",e.ResultDenied="result-denied"})(Gn||(Gn={}));var oc;(function(e){e.Approve="approve",e.Deny="deny"})(oc||(oc={}));var Kn;(function(e){e.Client="client",e.MCP="mcp"})(Kn||(Kn={}));var sc;(function(e){e.Text="text",e.EmbeddedResource="embeddedResource",e.Resource="resource",e.FileEdit="fileEdit",e.Terminal="terminal",e.Subagent="subagent"})(sc||(sc={}));var qn;(function(e){e.Running="running",e.Exited="exited"})(qn||(qn={}));var ic;(function(e){e.Client="client",e.Session="session"})(ic||(ic={}));var Vn;(function(e){e.Computing="computing",e.Recomputing="recomputing",e.Ready="ready",e.Error="error"})(Vn||(Vn={}));var ac;(function(e){e[e.Editing=1]="Editing"})(ac||(ac={}));var Xn;(function(e){e.Idle="idle",e.Running="running",e.Error="error",e.Disabled="disabled"})(Xn||(Xn={}));var cc;(function(e){e.Changeset="changeset",e.Resource="resource",e.Range="range"})(cc||(cc={}));var dc;(function(e){e.Added="added",e.Updated="updated",e.Deleted="deleted"})(dc||(dc={}));var uc;(function(e){e.Update="update",e.Remove="remove",e.Run="run"})(uc||(uc={}));var lc;(function(e){e.Skip="skip",e.RunOnce="runOnce"})(lc||(lc={}));var pc;(function(e){e.Schedule="schedule",e.Event="event"})(pc||(pc={}));var mc;(function(e){e.AfterRuns="afterRuns",e.AfterDate="afterDate"})(mc||(mc={}));var gc;(function(e){e.Pending="pending",e.Running="running",e.Completed="completed",e.Failed="failed",e.Cancelled="cancelled"})(gc||(gc={}));var fc;(function(e){e.Manual="manual",e.Trigger="trigger"})(fc||(fc={}));var c;(function(e){e.RootAgentsChanged="root/agentsChanged",e.RootActiveSessionsChanged="root/activeSessionsChanged",e.SessionReady="session/ready",e.SessionCreationFailed="session/creationFailed",e.SessionChatAdded="session/chatAdded",e.SessionChatRemoved="session/chatRemoved",e.SessionChatUpdated="session/chatUpdated",e.SessionChatsReordered="session/chatsReordered",e.SessionDefaultChatChanged="session/defaultChatChanged",e.ChatTurnStarted="chat/turnStarted",e.ChatDelta="chat/delta",e.ChatResponsePart="chat/responsePart",e.ChatToolCallStart="chat/toolCallStart",e.ChatToolCallDelta="chat/toolCallDelta",e.ChatToolCallReady="chat/toolCallReady",e.ChatToolCallConfirmed="chat/toolCallConfirmed",e.ChatToolCallComplete="chat/toolCallComplete",e.ChatToolCallResultConfirmed="chat/toolCallResultConfirmed",e.ChatToolCallContentChanged="chat/toolCallContentChanged",e.ChatToolCallAuthRequired="chat/toolCallAuthRequired",e.ChatToolCallAuthResolved="chat/toolCallAuthResolved",e.ChatTurnComplete="chat/turnComplete",e.ChatTurnCancelled="chat/turnCancelled",e.ChatError="chat/error",e.ChatTurnResume="chat/turnResume",e.ChatActivityChanged="chat/activityChanged",e.ChatBackgroundWorkSet="chat/backgroundWorkSet",e.ChatBackgroundWorkRemoved="chat/backgroundWorkRemoved",e.ChatMovableChanged="chat/movableChanged",e.ChatChangesetsChanged="chat/changesetsChanged",e.ChatCanvasesChanged="chat/canvasesChanged",e.CanvasStateChanged="canvas/stateChanged",e.ChatWorkingDirectorySet="chat/workingDirectorySet",e.ChatWorkingDirectoryRemoved="chat/workingDirectoryRemoved",e.SessionTitleChanged="session/titleChanged",e.ChatUsage="chat/usage",e.ChatReasoning="chat/reasoning",e.SessionServerToolsChanged="session/serverToolsChanged",e.SessionActiveClientSet="session/activeClientSet",e.SessionActiveClientRemoved="session/activeClientRemoved",e.SessionWorkingDirectorySet="session/workingDirectorySet",e.SessionWorkingDirectoryRemoved="session/workingDirectoryRemoved",e.SessionWorkingDirectoryReplaced="session/workingDirectoryReplaced",e.SessionInputNeededSet="session/inputNeededSet",e.SessionInputNeededRemoved="session/inputNeededRemoved",e.ChatPendingMessageSet="chat/pendingMessageSet",e.ChatPendingMessageRemoved="chat/pendingMessageRemoved",e.ChatQueuedMessagesReordered="chat/queuedMessagesReordered",e.ChatDraftChanged="chat/draftChanged",e.ChatIsReadChanged="chat/isReadChanged",e.ChatIsArchivedChanged="chat/isArchivedChanged",e.ChatConfigChanged="chat/configChanged",e.ChatMoved="chat/moved",e.ChatInputRequested="chat/inputRequested",e.ChatInputAnswerChanged="chat/inputAnswerChanged",e.ChatInputCompleted="chat/inputCompleted",e.SessionCustomizationsChanged="session/customizationsChanged",e.SessionCustomizationToggled="session/customizationToggled",e.SessionCustomizationUpdated="session/customizationUpdated",e.SessionCustomizationRemoved="session/customizationRemoved",e.SessionMcpServerStateChanged="session/mcpServerStateChanged",e.SessionMcpServerStartRequested="session/mcpServerStartRequested",e.SessionMcpServerStopRequested="session/mcpServerStopRequested",e.SessionMcpServerBackgroundRequested="session/mcpServerBackgroundRequested",e.ChatTruncated="chat/truncated",e.ChatTurnsLoaded="chat/turnsLoaded",e.SessionIsReadChanged="session/isReadChanged",e.SessionIsArchivedChanged="session/isArchivedChanged",e.SessionActivityChanged="session/activityChanged",e.SessionChangesetsChanged="session/changesetsChanged",e.SessionConfigChanged="session/configChanged",e.SessionMetaChanged="session/metaChanged",e.ChangesetStatusChanged="changeset/statusChanged",e.ChangesetFileSet="changeset/fileSet",e.ChangesetFileRemoved="changeset/fileRemoved",e.ChangesetFilesReviewChanged="changeset/filesReviewChanged",e.ChangesetContentChanged="changeset/contentChanged",e.ChangesetOperationsChanged="changeset/operationsChanged",e.ChangesetOperationStatusChanged="changeset/operationStatusChanged",e.ChangesetCleared="changeset/cleared",e.AnnotationsSet="annotations/set",e.AnnotationsUpdated="annotations/updated",e.AnnotationsRemoved="annotations/removed",e.AnnotationsEntrySet="annotations/entrySet",e.AnnotationsEntryRemoved="annotations/entryRemoved",e.RootTerminalsChanged="root/terminalsChanged",e.RootConfigChanged="root/configChanged",e.TerminalData="terminal/data",e.TerminalInput="terminal/input",e.TerminalResized="terminal/resized",e.TerminalClaimed="terminal/claimed",e.TerminalTitleChanged="terminal/titleChanged",e.TerminalCwdChanged="terminal/cwdChanged",e.TerminalExited="terminal/exited",e.TerminalCleared="terminal/cleared",e.TerminalCommandDetectionAvailable="terminal/commandDetectionAvailable",e.TerminalCommandExecuted="terminal/commandExecuted",e.TerminalCommandFinished="terminal/commandFinished",e.ResourceWatchChanged="resourceWatch/changed",e.AutomationCreateRequested="automation/createRequested",e.AutomationUpdateRequested="automation/updateRequested",e.AutomationSet="automation/set",e.AutomationRemoved="automation/removed",e.AutomationRunLifecycleChanged="automationRun/lifecycleChanged",e.AutomationRunSessionSet="automationRun/sessionSet",e.AutomationRunSessionRemoved="automationRun/sessionRemoved",e.AutomationRunPrimarySessionChanged="automationRun/primarySessionChanged",e.AutomationRunCancelRequested="automationRun/cancelRequested"})(c||(c={}));var Ol={[c.RootAgentsChanged]:!1,[c.RootActiveSessionsChanged]:!1,[c.RootTerminalsChanged]:!1,[c.RootConfigChanged]:!0,[c.SessionReady]:!1,[c.SessionCreationFailed]:!1,[c.SessionChatAdded]:!1,[c.SessionChatRemoved]:!1,[c.SessionChatUpdated]:!1,[c.SessionChatsReordered]:!1,[c.SessionDefaultChatChanged]:!1,[c.SessionTitleChanged]:!0,[c.SessionServerToolsChanged]:!1,[c.SessionActiveClientSet]:!0,[c.SessionActiveClientRemoved]:!0,[c.SessionWorkingDirectorySet]:!0,[c.SessionWorkingDirectoryRemoved]:!0,[c.SessionWorkingDirectoryReplaced]:!0,[c.SessionInputNeededSet]:!1,[c.SessionInputNeededRemoved]:!1,[c.SessionCustomizationsChanged]:!1,[c.SessionCustomizationToggled]:!0,[c.SessionCustomizationUpdated]:!1,[c.SessionCustomizationRemoved]:!1,[c.SessionMcpServerStateChanged]:!1,[c.SessionMcpServerStartRequested]:!0,[c.SessionMcpServerStopRequested]:!0,[c.SessionMcpServerBackgroundRequested]:!0,[c.SessionIsReadChanged]:!0,[c.SessionIsArchivedChanged]:!0,[c.SessionActivityChanged]:!1,[c.SessionChangesetsChanged]:!1,[c.SessionConfigChanged]:!0,[c.SessionMetaChanged]:!1,[c.ChatTurnStarted]:!0,[c.ChatDelta]:!1,[c.ChatResponsePart]:!1,[c.ChatToolCallStart]:!1,[c.ChatToolCallDelta]:!1,[c.ChatToolCallReady]:!1,[c.ChatToolCallConfirmed]:!0,[c.ChatToolCallComplete]:!0,[c.ChatToolCallResultConfirmed]:!0,[c.ChatToolCallContentChanged]:!0,[c.ChatToolCallAuthRequired]:!1,[c.ChatToolCallAuthResolved]:!1,[c.ChatTurnComplete]:!1,[c.ChatTurnCancelled]:!0,[c.ChatError]:!1,[c.ChatTurnResume]:!0,[c.ChatActivityChanged]:!1,[c.ChatBackgroundWorkSet]:!1,[c.ChatBackgroundWorkRemoved]:!1,[c.ChatMovableChanged]:!1,[c.ChatChangesetsChanged]:!1,[c.ChatCanvasesChanged]:!1,[c.CanvasStateChanged]:!1,[c.ChatWorkingDirectorySet]:!0,[c.ChatWorkingDirectoryRemoved]:!0,[c.ChatUsage]:!1,[c.ChatReasoning]:!1,[c.ChatPendingMessageSet]:!0,[c.ChatPendingMessageRemoved]:!0,[c.ChatQueuedMessagesReordered]:!0,[c.ChatDraftChanged]:!0,[c.ChatIsReadChanged]:!0,[c.ChatIsArchivedChanged]:!0,[c.ChatConfigChanged]:!0,[c.ChatMoved]:!1,[c.ChatInputRequested]:!1,[c.ChatInputAnswerChanged]:!0,[c.ChatInputCompleted]:!0,[c.ChatTruncated]:!0,[c.ChatTurnsLoaded]:!1,[c.ChangesetStatusChanged]:!1,[c.ChangesetFileSet]:!1,[c.ChangesetFileRemoved]:!1,[c.ChangesetFilesReviewChanged]:!0,[c.ChangesetContentChanged]:!1,[c.ChangesetOperationsChanged]:!1,[c.ChangesetOperationStatusChanged]:!1,[c.ChangesetCleared]:!1,[c.AnnotationsSet]:!0,[c.AnnotationsUpdated]:!0,[c.AnnotationsRemoved]:!0,[c.AnnotationsEntrySet]:!0,[c.AnnotationsEntryRemoved]:!0,[c.TerminalData]:!1,[c.TerminalInput]:!0,[c.TerminalResized]:!0,[c.TerminalClaimed]:!0,[c.TerminalTitleChanged]:!0,[c.TerminalCwdChanged]:!1,[c.TerminalExited]:!1,[c.TerminalCleared]:!0,[c.TerminalCommandDetectionAvailable]:!1,[c.TerminalCommandExecuted]:!1,[c.TerminalCommandFinished]:!1,[c.ResourceWatchChanged]:!1,[c.AutomationCreateRequested]:!0,[c.AutomationUpdateRequested]:!0,[c.AutomationSet]:!1,[c.AutomationRemoved]:!0,[c.AutomationRunLifecycleChanged]:!1,[c.AutomationRunSessionSet]:!1,[c.AutomationRunSessionRemoved]:!1,[c.AutomationRunPrimarySessionChanged]:!1,[c.AutomationRunCancelRequested]:!0};var Cl=["channel/credit","tcp/reset","unsubscribe"],A_=new Set(Cl);var hc;(function(e){e.Posix="posix",e.Windows="windows"})(hc||(hc={}));var _c;(function(e){e.Replay="replay",e.Snapshot="snapshot"})(_c||(_c={}));var yc;(function(e){e.Base64="base64",e.Utf8="utf-8"})(yc||(yc={}));var Ec;(function(e){e.Truncate="truncate",e.Append="append",e.Insert="insert"})(Ec||(Ec={}));var Sc;(function(e){e.File="file",e.Directory="directory",e.Symlink="symlink"})(Sc||(Sc={}));var Tc;(function(e){e.McpServer="mcpServer"})(Tc||(Tc={}));var wc;(function(e){e.UserMessage="userMessage"})(wc||(wc={}));var Ac;(function(e){e.Fork="fork",e.SideChat="sideChat"})(Ac||(Ac={}));var kc;(function(e){e.Session="session",e.NewSession="newSession"})(kc||(kc={}));var bc;(function(e){e.Resource="resource",e.Range="range"})(bc||(bc={}));var Ic;(function(e){e.Required="required",e.Expired="expired"})(Ic||(Ic={}));var V_=Object.freeze(["1.0.0","0.9.0"]);var X_={[c.RootAgentsChanged]:"0.1.0",[c.RootActiveSessionsChanged]:"0.1.0",[c.SessionReady]:"0.1.0",[c.SessionCreationFailed]:"0.1.0",[c.SessionChatAdded]:"0.4.0",[c.SessionChatRemoved]:"0.4.0",[c.SessionChatUpdated]:"0.4.0",[c.SessionChatsReordered]:"0.9.0",[c.SessionDefaultChatChanged]:"0.4.0",[c.SessionTitleChanged]:"0.1.0",[c.SessionServerToolsChanged]:"0.1.0",[c.SessionActiveClientSet]:"0.5.0",[c.SessionActiveClientRemoved]:"0.5.0",[c.SessionWorkingDirectorySet]:"0.7.0",[c.SessionWorkingDirectoryRemoved]:"0.7.0",[c.SessionWorkingDirectoryReplaced]:"0.8.0",[c.SessionInputNeededSet]:"0.5.1",[c.SessionInputNeededRemoved]:"0.5.1",[c.SessionCustomizationsChanged]:"0.1.0",[c.SessionCustomizationToggled]:"0.1.0",[c.SessionCustomizationUpdated]:"0.1.0",[c.SessionCustomizationRemoved]:"0.2.0",[c.SessionMcpServerStateChanged]:"0.3.0",[c.SessionMcpServerStartRequested]:"0.5.2",[c.SessionMcpServerStopRequested]:"0.5.2",[c.SessionMcpServerBackgroundRequested]:"0.9.0",[c.SessionIsReadChanged]:"0.1.0",[c.SessionIsArchivedChanged]:"0.1.0",[c.SessionActivityChanged]:"0.1.0",[c.SessionChangesetsChanged]:"0.2.0",[c.SessionConfigChanged]:"0.1.0",[c.SessionMetaChanged]:"0.1.0",[c.ChatTurnStarted]:"0.4.0",[c.ChatDelta]:"0.4.0",[c.ChatResponsePart]:"0.4.0",[c.ChatToolCallStart]:"0.4.0",[c.ChatToolCallDelta]:"0.4.0",[c.ChatToolCallReady]:"0.4.0",[c.ChatToolCallConfirmed]:"0.4.0",[c.ChatToolCallComplete]:"0.4.0",[c.ChatToolCallResultConfirmed]:"0.4.0",[c.ChatToolCallContentChanged]:"0.4.0",[c.ChatToolCallAuthRequired]:"0.6.0",[c.ChatToolCallAuthResolved]:"0.6.0",[c.ChatTurnComplete]:"0.4.0",[c.ChatTurnCancelled]:"0.4.0",[c.ChatError]:"0.4.0",[c.ChatTurnResume]:"0.9.0",[c.ChatActivityChanged]:"0.5.0",[c.ChatBackgroundWorkSet]:"0.9.0",[c.ChatBackgroundWorkRemoved]:"0.9.0",[c.ChatMovableChanged]:"0.9.0",[c.ChatChangesetsChanged]:"0.9.0",[c.ChatCanvasesChanged]:"0.10.0",[c.CanvasStateChanged]:"0.10.0",[c.ChatWorkingDirectorySet]:"0.7.0",[c.ChatWorkingDirectoryRemoved]:"0.7.0",[c.ChatUsage]:"0.4.0",[c.ChatReasoning]:"0.4.0",[c.ChatPendingMessageSet]:"0.4.0",[c.ChatPendingMessageRemoved]:"0.4.0",[c.ChatQueuedMessagesReordered]:"0.4.0",[c.ChatDraftChanged]:"0.5.0",[c.ChatIsReadChanged]:"0.9.0",[c.ChatIsArchivedChanged]:"0.9.0",[c.ChatConfigChanged]:"1.1.0",[c.ChatMoved]:"1.1.0",[c.ChatInputRequested]:"0.4.0",[c.ChatInputAnswerChanged]:"0.4.0",[c.ChatInputCompleted]:"0.4.0",[c.ChatTruncated]:"0.4.0",[c.ChatTurnsLoaded]:"0.5.1",[c.ChangesetStatusChanged]:"0.2.0",[c.ChangesetFileSet]:"0.2.0",[c.ChangesetFileRemoved]:"0.2.0",[c.ChangesetFilesReviewChanged]:"0.6.0",[c.ChangesetContentChanged]:"0.4.0",[c.ChangesetOperationsChanged]:"0.2.0",[c.ChangesetOperationStatusChanged]:"0.3.0",[c.ChangesetCleared]:"0.2.0",[c.AnnotationsSet]:"0.4.0",[c.AnnotationsUpdated]:"0.4.0",[c.AnnotationsRemoved]:"0.4.0",[c.AnnotationsEntrySet]:"0.4.0",[c.AnnotationsEntryRemoved]:"0.4.0",[c.RootTerminalsChanged]:"0.1.0",[c.RootConfigChanged]:"0.1.0",[c.TerminalData]:"0.1.0",[c.TerminalInput]:"0.1.0",[c.TerminalResized]:"0.1.0",[c.TerminalClaimed]:"0.1.0",[c.TerminalTitleChanged]:"0.1.0",[c.TerminalCwdChanged]:"0.1.0",[c.TerminalExited]:"0.1.0",[c.TerminalCleared]:"0.1.0",[c.TerminalCommandDetectionAvailable]:"0.1.0",[c.TerminalCommandExecuted]:"0.1.0",[c.TerminalCommandFinished]:"0.1.0",[c.ResourceWatchChanged]:"0.2.0",[c.AutomationCreateRequested]:"0.8.0",[c.AutomationUpdateRequested]:"0.8.0",[c.AutomationSet]:"0.8.0",[c.AutomationRemoved]:"0.8.0",[c.AutomationRunLifecycleChanged]:"0.8.0",[c.AutomationRunSessionSet]:"0.8.0",[c.AutomationRunSessionRemoved]:"0.8.0",[c.AutomationRunPrimarySessionChanged]:"0.8.0",[c.AutomationRunCancelRequested]:"0.8.0"};var Qn=["SOURCE_UNBOUND","SOURCE_UNAVAILABLE","SERVICE_IDENTITY_UNAVAILABLE","SERVICE_IDENTITY_NOT_GRANTED","AGENT_NOT_MAPPED","NOT_MAPPED","INVALID_ADDRESS","HOST_OFFLINE","SOURCE_GAP","FRAME_TOO_LARGE","ITEM_TOO_LARGE","STALE_EXPECTATION","SOURCE_READER_RESTARTING"];var jl=1000;var j=T().min(1).max(256),be=T().min(1).max(1024),Jl=T().regex(/^(0|[1-9][0-9]{0,17})$/u),Dt=I({epoch:j,ordinal:Jl}).strict(),ke={workspaceId:j,sourceId:j,hostId:j},Rc=I({address:be,version:j,scope:j,columns:I({title:T().max(4096),state:j,owner:j.nullable(),parent:be.nullable(),project:be.nullable(),labels:ne(j).max(256),url:T().max(2048).nullable(),updatedAt:T().max(64).nullable()}).strict(),extra:he()}).strict(),er=I({position:Dt,change:ba("op",[I({op:C("upsert"),row:Rc}).strict(),I({op:C("delete"),address:be}).strict()])}).strict(),Gl=I({address:be}).strict(),Kl=I({page:T().min(1).max(4096).optional(),limit:le().int().min(1).max(jl)}).strict(),ql=I({address:be,ownerMemberId:j,expectedOwner:j.nullable(),intentId:j,ifRevision:T().min(1).max(256).optional()}).strict(),Vl=I({on:Ke()}).strict(),Xl=I({memberId:j}).strict(),Ct=(e,t)=>I({...ke,caller:Xl,op:C(e),args:t}).strict(),iE=ba("op",[Ct("read",Gl),Ct("list",Kl),Ct("assign",ql),Ct("watch",Vl)]),Yl=I({generation:j,snapshot:j,base:Dt,rows:ne(Rc),next:T().min(1).max(4096).nullable(),complete:Ke(),progressAsOf:T().min(1).max(64).optional(),progressStale:I({since:T().min(1).max(64),reason:T().min(1).max(4096)}).strict().optional()}).strict().refine((e)=>e.rows.length>0||e.complete&&e.next===null,{message:"a page carries at least one item"}).refine((e)=>e.complete===(e.next===null),{message:"a page is complete exactly when it has no next token"}),Ql=I({intentId:j,result:he(),observation:er,revision:j.nullable().optional()}).strict(),Yn={read:I({observation:er}).strict(),list:Yl,assign:Ql,watch:I({on:Ke()}).strict()},vc=K(Qn),ep=["OPERATION_NOT_ALLOWLISTED","OPERATION_SHAPE_INVALID"],Lt=(e)=>we([I({...ke,op:C(e),outcome:K(["applied","noop"]),body:Yn[e]}).strict(),I({...ke,op:C(e),outcome:K(["applied","noop"]),code:C("SOURCE_READER_RESTARTING"),body:Yn[e]}).strict(),I({...ke,op:C(e),outcome:C("rejected"),code:vc,body:Yn[e]}).strict(),I({...ke,op:C(e),outcome:K(["unknown","refused"]),code:we([vc.exclude(["ITEM_TOO_LARGE"]),K(ep)])}).strict(),I({...ke,op:C(e),outcome:C("refused"),code:C("ITEM_TOO_LARGE"),item:be}).strict()]),aE=we([Lt("read"),Lt("list"),Lt("assign"),Lt("watch")]),cE=I({...ke,position:Dt,observations:ne(er).min(1)}).strict().refine((e)=>{let{observations:t,position:n}=e,r=t[t.length-1];if(r===void 0||r.position.epoch!==n.epoch||r.position.ordinal!==n.ordinal)return!1;return t.every((o,s)=>o.position.epoch===n.epoch&&(s===0||BigInt(o.position.ordinal)===BigInt(t[s-1].position.ordinal)+1n))},{message:"a push is one epoch of consecutive ordinals, numbered by its last"}),dE=I({applied:Dt.nullable(),seq:le().int().min(0),relist:Ke()}).strict();var Pt="x-hh-records";var tp=`${Pt}/changed`;var pE=I({address:T().min(1).max(1024),ownerMemberId:T().min(1).max(256),expectedOwner:T().min(1).max(256).nullable().optional(),ifRevision:T().min(1).max(256),intentId:T().min(1).max(256)}).strict(),xc=T().min(1).max(256),Nc=T().min(1).max(1024),Oc=I({address:Nc,revision:T().min(1).max(256),scope:T().min(1).max(256),columns:Ia(T(),he()),extra:he().optional()}).strict(),mE=I({source:xc,epoch:T().min(1).max(256),records:ne(Oc)}).strict(),np=I({type:C(tp),source:xc,revision:T().min(1).max(256),address:Nc,deleted:C(!0).optional(),record:Oc.optional()}).strict(),gE=I({channel:T().min(1),serverSeq:le().int().min(0).optional(),action:np}),fE=new RegExp(`^${Pt}://[^/?#]+$`,"u");var rp=I({id:T().min(1),revision:le().int().min(0),state:T(),operations:ne(T())}).passthrough();var tr=le().int().min(0),yE=I({id:T().min(1),engine:T().min(1),owner:T().min(1),name:T().min(1),description:T().optional(),tags:ne(T()).optional(),model:he().optional(),config:Ia(T(),he()),ifRevision:tr}).passthrough(),EE=I({id:T().min(1),ifRevision:tr}).strict(),SE=I({id:T().min(1),ifRevision:tr}).strict(),Cc=-32602,TE=I({code:C(Cc),message:T(),data:I({staleRevision:le().int().min(1),row:rp})}),wE=I({code:C(Cc),message:T(),data:I({staleRevision:C(0)})});var op=["subscribe","x-ahpd/invokeOperation","resourceRead","listSessions","authenticate"],sp="x-hh-services://",xE=`${sp} and ${Pt}://<sourceId>`;var NE=["x-ahpd/agents/list","x-ahpd/agents/put","x-ahpd/agents/remove","x-ahpd/agents/enable","x-ahpd/agents/pause","x-ahpd/agents/disable",...op];var ip=1e4,OE=ip-1000;var CE=I({workspaceId:T().min(1).optional(),hostId:T().min(1).optional(),agentMemberId:T().min(1).optional(),caller:T().min(1).max(256).optional()}).strict(),ap=["unmapped","timedOut","outside"],LE=I({reason:K(ap)}).strict();var cp=I({resource:T().min(1),customizationId:T().min(1)}).strict(),Lc=I({available:Ke(),reason:T().min(1).max(200).optional(),server:cp.optional()}).strict();var DE=I({resource:T().min(1),_meta:I({"hh/agentMemberId":T().min(1),"hh/hostTools":Lc.optional()}).strict()}).strict(),PE=I({channel:C("ahp-root://"),session:T().min(1),changes:I({_meta:I({"hh/agentMemberId":T().min(1),"hh/hostTools":Lc}).strict()}).strict()}).strict();var ME=I({channel:T().min(1),resource:T().min(1),reason:C("expired")}).strict();var dp=["session/ready","chat/turnStarted","chat/turnComplete","x-hh/turnFailed"];var up=["OPERATION_NOT_ALLOWLISTED","OPERATION_SHAPE_INVALID","INVALID_OPERATION_SHAPE","WORKSPACE_OR_MEMBER_UNKNOWN","UNKNOWN_HOUSE_OR_MEMBER","AGENT_NOT_MAPPED","UNMAPPED_LOCAL_AGENT","FOREIGN_SESSION","FOREIGN_SESSION_REFUSED","TOKEN_EXPIRED_OR_REVOKED","HOST_REVOKED","HOST_RESTARTED","INPUT_REQUIRED","APPROVAL_REQUIRED","VERSION_UNSUPPORTED","WAKE_NOT_SENT","TURN_TIMED_OUT","WAKE_ATTEMPTS_EXHAUSTED","HOST_START_FAILED","WAKE_TEXT_NOT_ALLOWED","ROOM_ASKS_UNTRUSTED","ASK_UNSIGNED","KEY_NOT_FOR_AUTHOR","ASK_STALE","ASK_REPLAYED","SERVICE_NOT_ALLOWED","TURN_CANCELLED",...Qn],Dc=16,Pc=49152,Mc=262144,lp=I({id:T().min(1),from:I({memberId:T().min(1)}).strict(),text:T(),replyTo:T().min(1).optional(),deleted:C(!0).optional(),signed:I({keyId:T().min(1),createdAt:T().min(1),signature:T().min(1),clientId:T().min(1),attachmentIds:ne(T().min(1))}).strict().optional()}).strict(),pp=(e)=>new TextEncoder().encode(JSON.stringify(e)).byteLength,mp=ne(lp).min(1).superRefine((e,t)=>{if(e.length>Dc){t.addIssue({code:"custom",message:`a wake carries at most ${Dc} triggering envelopes, not ${e.length}`});return}if(new Set(e.map((r)=>r.id)).size!==e.length){t.addIssue({code:"custom",message:"a wake names each triggering message once"});return}let n=0;for(let r of e){let o=pp(r);if(o>Pc){t.addIssue({code:"custom",message:`triggering envelope ${r.id} is ${o} bytes, over the ${Pc}-byte limit`});return}n+=o}if(n>Mc)t.addIssue({code:"custom",message:`the triggering envelopes take ${n} bytes, over the ${Mc}-byte limit`})}),HE=I({workspaceId:T().min(1),deliveryId:T().min(1),turnId:T().min(1).optional(),agentMemberId:T().min(1),threadRef:T().min(1),afterMessageId:T().min(1).optional(),triggeringMessageIds:ne(T().min(1)).min(1).refine((e)=>new Set(e).size===e.length).optional(),triggering:mp.optional()}).strict(),FE=I({event:K(dp),channel:T().min(1),workspaceId:T().min(1),deliveryId:T().min(1),session:T().min(1),chat:T().min(1),turnId:T().min(1).optional(),clientSeq:le().int().min(1).optional(),turnState:K(["created","running","finished","error"]),statusCode:T().min(1).max(64),errorCode:K(up).optional(),errorDetail:T().max(256).optional()}).strict();var gp=["session/ready","chat/turnStarted","chat/turnComplete","chat/turnCancelled","chat/error"],BE=I({channel:T().min(1),serverSeq:le().int().min(0).optional(),origin:I({clientId:T().min(1),clientSeq:le().int().min(1)}).optional(),action:I({type:K(gp),turnId:T().min(1).optional(),part:I({error:I({errorType:T().min(1)})}).optional()})});var a="Hightea-Host",d="x-hightea-host";async function Fc(e,t){let n=wp(e)?[e]:t.split(Tp).filter((r)=>r!=="").map((r)=>Ap(r,e));for(let r of n)try{if(await Ep(r,yp.X_OK),(await Sp(r)).isFile())return!0}catch{}return!1}async function L(e=process.env.PATH??"",t=process.platform){let n=[];for(let r of qe){let o=Hc[r];if(o===void 0)throw Error("HOST_JOIN_APPS_ROW_MISSING");if(!await Fc(o.command,e))continue;let s=Wc(o,t);n.push({id:r,name:Ve[r],command:o.command,...s===void 0?{}:{install:s},...o.page===void 0?{}:{page:o.page}})}return n}function u(e){if(e.install!==void 0)return e.install;return e.page===void 0?`install ${e.name}`:`install ${e.name}: ${e.page}`}function p(e,t=process.platform){let n=Hc[e];if(n===void 0)throw Error("HOST_JOIN_APPS_ROW_MISSING");let r=Wc(n,t);return{id:e,name:Ve[e],command:n.command,...r===void 0?{}:{install:r},...n.page===void 0?{}:{page:n.page}}}async function w(e,t=process.env.PATH??""){return Fc(e.command,t)}var D=(e)=>qe.includes(e);function P(e=process.platform){return"no agent app on this computer: "+qe.map((n)=>p(n,e)).map((n)=>`${n.name} (${u(n)})`).join("; ")+". Install one, then run the same command again. Nothing was redeemed and nothing was written."}
|
|
58
|
+
export{_,A,l,a,d,L,u,p,w,D,P};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{s,f}from"./chunk-kjkww5cr.js";import{chmod as p,mkdir as u,readFile as I,rm as O,stat as _,writeFile as N}from"node:fs/promises";import{homedir as x}from"node:os";import{join as h}from"node:path";var R=new Set(["FORBIDDEN","NOT_A_MEMBER","UNAUTHENTICATED"]);function t(){return{fetch:(r,o)=>globalThis.fetch(r,o),readFile:(r)=>I(r,"utf8"),stat:(r)=>_(r),writeFile:(r,o,n)=>N(r,o,n),mkdir:async(r,o)=>{await u(r,o)},chmod:(r,o)=>p(r,o),rm:(r,o)=>O(r,o),env:process.env,home:x(),nowMs:()=>Date.now(),out:(r)=>{process.stdout.write(`${r}
|
|
2
|
+
`)},err:(r)=>{process.stderr.write(`${r}
|
|
3
|
+
`)}}}async function T(r,o,n,c){let d=r.sessionFile?.trim()||o.env.HIGHTEA_SESSION_FILE?.trim();if(d===void 0||d===""){let i=await f(c,o);if("credential"in i)return{cookie:i.credential.sessionToken};if(i.error.startsWith("AUTH_NOT_SIGNED_IN")){let a=h(o.env.XDG_CONFIG_HOME?.trim()||h(o.home,".config"),"hightea","session"),m=await S(a,o,n);if(!("error"in m))return m;return{error:`${n}_SESSION_MISSING: ${i.error}`}}if(i.error.startsWith("AUTH_CREDENTIALS_EXPOSED"))return{error:`${n}_SESSION_EXPOSED: ${i.error}`};if(i.error.startsWith("AUTH_SESSION_EXPIRED")||i.error.startsWith("AUTH_REFRESH"))return{error:`${n}_SESSION_EXPIRED: ${i.error}`};return{error:`${n}_SESSION_INVALID: ${i.error}`}}return await S(d,o,n)}async function S(r,o,n){let c,d;try{c=await o.readFile(r),d=(await o.stat(r)).mode}catch(a){return{error:`${n}_SESSION_MISSING: no session in ${r} (${a.message}). Sign in to the deployment in a browser and write its ht_session cookie to that file, or pass --session-file.`}}if((d&63)!==0)return{error:`${n}_SESSION_EXPOSED: ${r} is mode 0${(d&511).toString(8).padStart(3,"0")}; run chmod 600 ${r}.`};let i=c.split(`
|
|
4
|
+
`).map((a)=>a.trim()).filter((a)=>a.length>0);if(i.length!==1)return{error:`${n}_SESSION_INVALID: ${r} must hold exactly one non-empty line (the ht_session cookie value); it holds ${i.length}.`};return{cookie:i[0]}}async function e(r,o,n){let c=s(r.origin,n.label);if("error"in c)return{exit:1,error:c.error};let d=await T(r,o,n.label,c.origin);if("error"in d)return{exit:1,error:d.error};let i=`${c.origin}/api/ws/${encodeURIComponent(r.workspace)}${n.path}`,a;try{a=await o.fetch(i,{method:n.method,headers:{cookie:`ht_session=${d.cookie}`,origin:c.origin,accept:"application/json","cache-control":"no-store",...n.headers,...n.body===void 0?{}:{"content-type":"application/json"}},...n.body===void 0?{}:{body:JSON.stringify(n.body)}})}catch(l){return{exit:1,error:`${n.label}_UNREACHABLE: ${n.what} ${n.method} ${i} did not answer: ${l.message}`}}let m=await a.text(),y={};if(m.length>0)try{let l=JSON.parse(m);if(typeof l!=="object"||l===null||Array.isArray(l))throw SyntaxError("not a JSON object");y=l}catch(l){if(!(l instanceof SyntaxError))throw l;return{exit:1,error:`${n.label}_ANSWER_INVALID: ${n.what} ${n.method} ${i} answered HTTP ${a.status} with non-JSON: ${m.slice(0,300)}`}}if(a.ok)return{answer:y};let g=y.error,w=typeof g?.code==="string"?g.code:`HTTP_${a.status}`,E=typeof g?.message==="string"?g.message:m.slice(0,300);return{exit:R.has(w)?3:n.extraExits?.[w]??1,error:`${w}: ${E}`,body:y}}
|
|
5
|
+
export{t,e};
|