@hallohuman/hightea 0.1.32 → 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.
@@ -54,5 +54,5 @@ ${t.join(`
54
54
  }
55
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
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 d(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 a;(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"})(a||(a={}));var Ol={[a.RootAgentsChanged]:!1,[a.RootActiveSessionsChanged]:!1,[a.RootTerminalsChanged]:!1,[a.RootConfigChanged]:!0,[a.SessionReady]:!1,[a.SessionCreationFailed]:!1,[a.SessionChatAdded]:!1,[a.SessionChatRemoved]:!1,[a.SessionChatUpdated]:!1,[a.SessionChatsReordered]:!1,[a.SessionDefaultChatChanged]:!1,[a.SessionTitleChanged]:!0,[a.SessionServerToolsChanged]:!1,[a.SessionActiveClientSet]:!0,[a.SessionActiveClientRemoved]:!0,[a.SessionWorkingDirectorySet]:!0,[a.SessionWorkingDirectoryRemoved]:!0,[a.SessionWorkingDirectoryReplaced]:!0,[a.SessionInputNeededSet]:!1,[a.SessionInputNeededRemoved]:!1,[a.SessionCustomizationsChanged]:!1,[a.SessionCustomizationToggled]:!0,[a.SessionCustomizationUpdated]:!1,[a.SessionCustomizationRemoved]:!1,[a.SessionMcpServerStateChanged]:!1,[a.SessionMcpServerStartRequested]:!0,[a.SessionMcpServerStopRequested]:!0,[a.SessionMcpServerBackgroundRequested]:!0,[a.SessionIsReadChanged]:!0,[a.SessionIsArchivedChanged]:!0,[a.SessionActivityChanged]:!1,[a.SessionChangesetsChanged]:!1,[a.SessionConfigChanged]:!0,[a.SessionMetaChanged]:!1,[a.ChatTurnStarted]:!0,[a.ChatDelta]:!1,[a.ChatResponsePart]:!1,[a.ChatToolCallStart]:!1,[a.ChatToolCallDelta]:!1,[a.ChatToolCallReady]:!1,[a.ChatToolCallConfirmed]:!0,[a.ChatToolCallComplete]:!0,[a.ChatToolCallResultConfirmed]:!0,[a.ChatToolCallContentChanged]:!0,[a.ChatToolCallAuthRequired]:!1,[a.ChatToolCallAuthResolved]:!1,[a.ChatTurnComplete]:!1,[a.ChatTurnCancelled]:!0,[a.ChatError]:!1,[a.ChatTurnResume]:!0,[a.ChatActivityChanged]:!1,[a.ChatBackgroundWorkSet]:!1,[a.ChatBackgroundWorkRemoved]:!1,[a.ChatMovableChanged]:!1,[a.ChatChangesetsChanged]:!1,[a.ChatCanvasesChanged]:!1,[a.CanvasStateChanged]:!1,[a.ChatWorkingDirectorySet]:!0,[a.ChatWorkingDirectoryRemoved]:!0,[a.ChatUsage]:!1,[a.ChatReasoning]:!1,[a.ChatPendingMessageSet]:!0,[a.ChatPendingMessageRemoved]:!0,[a.ChatQueuedMessagesReordered]:!0,[a.ChatDraftChanged]:!0,[a.ChatIsReadChanged]:!0,[a.ChatIsArchivedChanged]:!0,[a.ChatConfigChanged]:!0,[a.ChatMoved]:!1,[a.ChatInputRequested]:!1,[a.ChatInputAnswerChanged]:!0,[a.ChatInputCompleted]:!0,[a.ChatTruncated]:!0,[a.ChatTurnsLoaded]:!1,[a.ChangesetStatusChanged]:!1,[a.ChangesetFileSet]:!1,[a.ChangesetFileRemoved]:!1,[a.ChangesetFilesReviewChanged]:!0,[a.ChangesetContentChanged]:!1,[a.ChangesetOperationsChanged]:!1,[a.ChangesetOperationStatusChanged]:!1,[a.ChangesetCleared]:!1,[a.AnnotationsSet]:!0,[a.AnnotationsUpdated]:!0,[a.AnnotationsRemoved]:!0,[a.AnnotationsEntrySet]:!0,[a.AnnotationsEntryRemoved]:!0,[a.TerminalData]:!1,[a.TerminalInput]:!0,[a.TerminalResized]:!0,[a.TerminalClaimed]:!0,[a.TerminalTitleChanged]:!0,[a.TerminalCwdChanged]:!1,[a.TerminalExited]:!1,[a.TerminalCleared]:!0,[a.TerminalCommandDetectionAvailable]:!1,[a.TerminalCommandExecuted]:!1,[a.TerminalCommandFinished]:!1,[a.ResourceWatchChanged]:!1,[a.AutomationCreateRequested]:!0,[a.AutomationUpdateRequested]:!0,[a.AutomationSet]:!1,[a.AutomationRemoved]:!0,[a.AutomationRunLifecycleChanged]:!1,[a.AutomationRunSessionSet]:!1,[a.AutomationRunSessionRemoved]:!1,[a.AutomationRunPrimarySessionChanged]:!1,[a.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_={[a.RootAgentsChanged]:"0.1.0",[a.RootActiveSessionsChanged]:"0.1.0",[a.SessionReady]:"0.1.0",[a.SessionCreationFailed]:"0.1.0",[a.SessionChatAdded]:"0.4.0",[a.SessionChatRemoved]:"0.4.0",[a.SessionChatUpdated]:"0.4.0",[a.SessionChatsReordered]:"0.9.0",[a.SessionDefaultChatChanged]:"0.4.0",[a.SessionTitleChanged]:"0.1.0",[a.SessionServerToolsChanged]:"0.1.0",[a.SessionActiveClientSet]:"0.5.0",[a.SessionActiveClientRemoved]:"0.5.0",[a.SessionWorkingDirectorySet]:"0.7.0",[a.SessionWorkingDirectoryRemoved]:"0.7.0",[a.SessionWorkingDirectoryReplaced]:"0.8.0",[a.SessionInputNeededSet]:"0.5.1",[a.SessionInputNeededRemoved]:"0.5.1",[a.SessionCustomizationsChanged]:"0.1.0",[a.SessionCustomizationToggled]:"0.1.0",[a.SessionCustomizationUpdated]:"0.1.0",[a.SessionCustomizationRemoved]:"0.2.0",[a.SessionMcpServerStateChanged]:"0.3.0",[a.SessionMcpServerStartRequested]:"0.5.2",[a.SessionMcpServerStopRequested]:"0.5.2",[a.SessionMcpServerBackgroundRequested]:"0.9.0",[a.SessionIsReadChanged]:"0.1.0",[a.SessionIsArchivedChanged]:"0.1.0",[a.SessionActivityChanged]:"0.1.0",[a.SessionChangesetsChanged]:"0.2.0",[a.SessionConfigChanged]:"0.1.0",[a.SessionMetaChanged]:"0.1.0",[a.ChatTurnStarted]:"0.4.0",[a.ChatDelta]:"0.4.0",[a.ChatResponsePart]:"0.4.0",[a.ChatToolCallStart]:"0.4.0",[a.ChatToolCallDelta]:"0.4.0",[a.ChatToolCallReady]:"0.4.0",[a.ChatToolCallConfirmed]:"0.4.0",[a.ChatToolCallComplete]:"0.4.0",[a.ChatToolCallResultConfirmed]:"0.4.0",[a.ChatToolCallContentChanged]:"0.4.0",[a.ChatToolCallAuthRequired]:"0.6.0",[a.ChatToolCallAuthResolved]:"0.6.0",[a.ChatTurnComplete]:"0.4.0",[a.ChatTurnCancelled]:"0.4.0",[a.ChatError]:"0.4.0",[a.ChatTurnResume]:"0.9.0",[a.ChatActivityChanged]:"0.5.0",[a.ChatBackgroundWorkSet]:"0.9.0",[a.ChatBackgroundWorkRemoved]:"0.9.0",[a.ChatMovableChanged]:"0.9.0",[a.ChatChangesetsChanged]:"0.9.0",[a.ChatCanvasesChanged]:"0.10.0",[a.CanvasStateChanged]:"0.10.0",[a.ChatWorkingDirectorySet]:"0.7.0",[a.ChatWorkingDirectoryRemoved]:"0.7.0",[a.ChatUsage]:"0.4.0",[a.ChatReasoning]:"0.4.0",[a.ChatPendingMessageSet]:"0.4.0",[a.ChatPendingMessageRemoved]:"0.4.0",[a.ChatQueuedMessagesReordered]:"0.4.0",[a.ChatDraftChanged]:"0.5.0",[a.ChatIsReadChanged]:"0.9.0",[a.ChatIsArchivedChanged]:"0.9.0",[a.ChatConfigChanged]:"1.1.0",[a.ChatMoved]:"1.1.0",[a.ChatInputRequested]:"0.4.0",[a.ChatInputAnswerChanged]:"0.4.0",[a.ChatInputCompleted]:"0.4.0",[a.ChatTruncated]:"0.4.0",[a.ChatTurnsLoaded]:"0.5.1",[a.ChangesetStatusChanged]:"0.2.0",[a.ChangesetFileSet]:"0.2.0",[a.ChangesetFileRemoved]:"0.2.0",[a.ChangesetFilesReviewChanged]:"0.6.0",[a.ChangesetContentChanged]:"0.4.0",[a.ChangesetOperationsChanged]:"0.2.0",[a.ChangesetOperationStatusChanged]:"0.3.0",[a.ChangesetCleared]:"0.2.0",[a.AnnotationsSet]:"0.4.0",[a.AnnotationsUpdated]:"0.4.0",[a.AnnotationsRemoved]:"0.4.0",[a.AnnotationsEntrySet]:"0.4.0",[a.AnnotationsEntryRemoved]:"0.4.0",[a.RootTerminalsChanged]:"0.1.0",[a.RootConfigChanged]:"0.1.0",[a.TerminalData]:"0.1.0",[a.TerminalInput]:"0.1.0",[a.TerminalResized]:"0.1.0",[a.TerminalClaimed]:"0.1.0",[a.TerminalTitleChanged]:"0.1.0",[a.TerminalCwdChanged]:"0.1.0",[a.TerminalExited]:"0.1.0",[a.TerminalCleared]:"0.1.0",[a.TerminalCommandDetectionAvailable]:"0.1.0",[a.TerminalCommandExecuted]:"0.1.0",[a.TerminalCommandFinished]:"0.1.0",[a.ResourceWatchChanged]:"0.2.0",[a.AutomationCreateRequested]:"0.8.0",[a.AutomationUpdateRequested]:"0.8.0",[a.AutomationSet]:"0.8.0",[a.AutomationRemoved]:"0.8.0",[a.AutomationRunLifecycleChanged]:"0.8.0",[a.AutomationRunSessionSet]:"0.8.0",[a.AutomationRunSessionRemoved]:"0.8.0",[a.AutomationRunPrimarySessionChanged]:"0.8.0",[a.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 c="Hightea-Host",l="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,d,c,l,L,u,p,w,D,P};
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};
@@ -1,4 +1,4 @@
1
- import{s,f}from"./chunk-dvsftn8z.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}
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
2
  `)},err:(r)=>{process.stderr.write(`${r}
3
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
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}}
@@ -1,4 +1,4 @@
1
- import"./chunk-dvsftn8z.js";import{t,e}from"./chunk-55a0ndzw.js";var c=`hightea host list --origin https://your-deployment --workspace SLUG [--session-file FILE] [--json]
1
+ import"./chunk-kjkww5cr.js";import{t,e}from"./chunk-vzkbknwq.js";var c=`hightea host list --origin https://your-deployment --workspace SLUG [--session-file FILE] [--json]
2
2
  hightea host remove --origin https://your-deployment --workspace SLUG --host HOST [--remove-agents] [--session-file FILE] [--json]`;async function g(s,n=t()){if(s.workspace.trim().length===0||s.host.trim().length===0)return n.err(`HOST_REMOVE_INPUT: --workspace and --host are required.
3
3
  ${c}`),1;let r=s.host.trim(),i=s.removeAgents===!0?"?removeAgents=1":"",o=await e(s,n,{method:"DELETE",path:`/hosts/${encodeURIComponent(r)}${i}`,what:"remove",label:"HOST_REMOVE"});if("error"in o)return n.err(o.error),o.exit;if(s.json)return n.out(JSON.stringify(o.answer)),0;let a=o.answer.host??{},d=typeof a.endedDeliveries==="number"?a.endedDeliveries:0,u=String(a.hostId??r);if(a.alreadyRevoked===!0)return n.out(`host ${u} was already removed; nothing was left running`),0;n.out(`removed host ${u}: revoked, ${d} ${d===1?"delivery":"deliveries"} ended`);let h=Array.isArray(o.answer.agentsKeptUnrouted)?o.answer.agentsKeptUnrouted.length:0;return n.out(h===0?"Its agents have no host until they join again with a new join code.":`Its ${h===1?"agent is":`${String(h)} agents are`} still a member, now with no computer; a new join code routes ${h===1?"it":"them"} again. (--remove-agents deletes them with the computer.)`),0}function l(s){let n=(d)=>s[d]===null||s[d]===void 0?"none":String(s[d]),r=Array.isArray(s.agentMemberIds)&&s.agentMemberIds.length>0?s.agentMemberIds.join(","):"none",i=n("status")==="revoked"?`revoked ${n("revokedAt")}`:`last seen ${n("lastSeenAt")}`,o=typeof s.initializeNote==="string"?` ${s.initializeNote}`:"",a=n("link")==="attaching"?`connected, never initialized${n("attachedAt")==="none"?"":` since ${n("attachedAt")}`}`:s.connected===!0||n("link")==="ready"?"connected":"not connected";return`${n("hostId")} ${n("status")} ${a} plugin ${n("pluginVersion")} agents ${r} owner ${n("ownerAccountId")} ${i}${o}`}async function p(s,n=t()){if(s.workspace.trim().length===0)return n.err(`HOST_LIST_INPUT: --workspace is required.
4
4
  ${c}`),1;let r=await e(s,n,{method:"GET",path:"/hosts",what:"list",label:"HOST_LIST"});if("error"in r)return n.err(r.error),r.exit;if(s.json)return n.out(JSON.stringify(r.answer)),0;let i=Array.isArray(r.answer.hosts)?r.answer.hosts:[];if(i.length===0)return n.out(`no hosts in workspace ${s.workspace.trim()} that your account can see (a workspace owner sees every host)`),0;if(n.out(i.map(l).join(`
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "hightea-pipe",
3
3
  "main": "./plugin.mjs",
4
- "version": "0.1.32",
4
+ "version": "0.1.33",
5
5
  "grants": [
6
6
  "session:write",
7
7
  "session:state",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hallohuman/hightea",
3
- "version": "0.1.32",
3
+ "version": "0.1.33",
4
4
  "description": "The Hightea command line: join this machine to a Hightea workspace as a host.",
5
5
  "license": "UNLICENSED",
6
6
  "publishConfig": {
@@ -1,5 +0,0 @@
1
- import{_,A,d,c,l,u,p,w}from"./chunk-ah99zytf.js";import{r}from"./chunk-v221hgba.js";import{readdir as le,readFile as oe,realpath as Oe,rm as gt}from"node:fs/promises";import{createRequire as Ln}from"node:module";import{homedir as xn,hostname as Fn}from"node:os";import{basename as yt,dirname as F,isAbsolute as wt,join as P,resolve as Kn}from"node:path";import{fromEnvRef as jn,isRecord as K,readJsonObject as _t,readSecret as Gn,secretRef as Bn,writeJsonAtomic as Ne}from"@ahpd/sdk";import{fileVault as Mn}from"@ahpd/server/dist/vault.js";import{createHash as De,randomBytes as Tt}from"node:crypto";import{constants as ee}from"node:fs";import{link as Nt,lstat as ge,mkdir as Ue,mkdtemp as Et,open as $e,realpath as At,rm as Ht}from"node:fs/promises";import{dirname as se,join as M}from"node:path";import{isDeepStrictEqual as Pe}from"node:util";import{fileVault as Je}from"@ahpd/server/dist/vault.js";function b(e){throw Error(e)}function Le(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(Le(s)!=="EEXIST")b("HOST_JOIN_CUSTODY_IO")});let t=await ge(e);if(!t.isDirectory()||t.uid!==process.getuid?.()||(t.mode&63)!==0)b("HOST_JOIN_UNSAFE_PATH")}async function kt(e){let t=await $e(e,ee.O_RDONLY|ee.O_DIRECTORY|ee.O_NOFOLLOW);try{await t.sync()}finally{await t.close()}}async function Z(e){let t=await $e(e,ee.O_RDONLY|ee.O_NOFOLLOW);try{await t.sync()}finally{await t.close()}for(let s=se(e);;s=se(s))if(await kt(s),s===se(s))break}function fe(e){if(typeof e.origin!=="string"||typeof e.workspaceSlug!=="string"||typeof e.code!=="string"||typeof e.pluginVersion!=="string"||typeof e.ahpdVersion!=="string")b("HOST_JOIN_INVALID_INTENT");let t;try{t=new URL(e.origin)}catch{return b("HOST_JOIN_INVALID_INTENT")}let s=d(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)b("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 a=y.codePointAt(0)??0;return a<32||a===127})))b("HOST_JOIN_INVALID_INTENT");if(e.app!==void 0&&!A(e.app))b("HOST_JOIN_INVALID_INTENT");if(e.hostId!==void 0&&(typeof e.hostId!=="string"||!/^[A-Za-z0-9_.:-]{1,128}$/u.test(e.hostId)))b("HOST_JOIN_INVALID_INTENT");if(e.ownerConfiguration===null&&e.app===void 0)b("HOST_JOIN_INVALID_INTENT");let f;try{f=e.ownerConfiguration===null?null:JSON.parse(JSON.stringify(e.ownerConfiguration))}catch{return b("HOST_JOIN_INVALID_INTENT")}if(f!==null&&(typeof f!=="object"||!Pe(f,e.ownerConfiguration)))b("HOST_JOIN_INVALID_INTENT");return{...e,origin:t.origin,code:s,ownerConfiguration:f}}async function xe(e,t){let s=fe(t),f=await Ke(e),y=M(f,"hightea"),a=M(y,"claims"),h=De("sha256").update(JSON.stringify([s.origin,s.workspaceSlug,s.code])).digest("hex"),S=M(a,h),T=M(S,"ahpd");try{for(let E of[y,a,S,T])await Y(E);let N=M(T,"vault.json"),I=await Et(M(T,".claim-"));try{let E=M(I,"vault.json"),v=Je({file:E});await v.set("host:hightea",`Bearer ${Tt(32).toString("base64url")}`),await v.set("host:hightea-join",JSON.stringify({schema:1,...s}));try{await Nt(E,N)}catch(D){if(Le(D)!=="EEXIST")b("HOST_JOIN_CUSTODY_PUBLICATION_FAILED")}let{authorization:H,credentialHash:k,intent:J}=await je(N);if(J.origin!==s.origin||J.workspaceSlug!==s.workspaceSlug||J.code!==s.code||J.app!==s.app||J.hostId!==s.hostId||!Pe(J.ownerConfiguration,s.ownerConfiguration))b("HOST_JOIN_CLAIM_CONFLICT");return await Z(N),{home:S,vaultFile:N,authorization:H,credentialHash:k,intent:J}}finally{await Ht(I,{recursive:!0})}}catch(N){if(N instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(N.message))throw N;return b("HOST_JOIN_CUSTODY_IO")}}async function Fe(e,t,s){let f=fe(s);if(f.hostId===void 0)b("HOST_JOIN_INVALID_INTENT");try{let y=await Ke(e),a=M(y,"hightea"),h=M(a,"claims");if(se(t)!==h)b("HOST_JOIN_NO_CLAIM_FOR_HOST");let S=M(t,"ahpd");for(let I of[a,h,t,S])await Y(I);let T=M(S,"vault.json"),N=await je(T);if(N.intent.origin!==f.origin||N.intent.workspaceSlug!==f.workspaceSlug||N.intent.hostId!==void 0&&f.hostId!==N.intent.hostId)b("HOST_JOIN_CLAIM_CONFLICT");return await Z(T),{home:t,vaultFile:T,authorization:N.authorization,credentialHash:N.credentialHash,intent:f}}catch(y){if(y instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(y.message))throw y;return b("HOST_JOIN_NO_CLAIM_FOR_HOST")}}async function Ke(e){try{await Ue(e,{recursive:!0,mode:448});let t=await ge(e);if(!t.isDirectory()||t.uid!==process.getuid?.()||(t.mode&18)!==0)b("HOST_JOIN_UNSAFE_PATH");return await At(e)}catch{return b("HOST_JOIN_UNSAFE_PATH")}}async function je(e){let t=await ge(e);if(!t.isFile()||t.uid!==process.getuid?.()||(t.mode&511)!==384)b("HOST_JOIN_UNSAFE_PATH");let s=Je({file:e}),f=await s.get("host:hightea"),y=await s.get("host:hightea-join");if(!f||!/^Bearer [A-Za-z0-9_-]{43}$/u.test(f)||!y)b("HOST_JOIN_CLAIM_CORRUPT");let a;try{a=JSON.parse(y)}catch{return b("HOST_JOIN_CLAIM_CORRUPT")}if(!a||typeof a!=="object"||!("schema"in a)||a.schema!==1)b("HOST_JOIN_CLAIM_CORRUPT");let h;try{h=fe(a)}catch{return b("HOST_JOIN_CLAIM_CORRUPT")}return{authorization:f,credentialHash:`sha256:${De("sha256").update(f.slice(7),"utf8").digest("hex")}`,intent:h}}import{link as Rt,lstat as bt,mkdtemp as vt,rm as Ct}from"node:fs/promises";import{join as te}from"node:path";import{isDeepStrictEqual as Dt}from"node:util";import{isRecordSlug as Ut,readJsonObject as $t,writeJsonAtomic as Ge}from"@ahpd/sdk";async function Be(e,t){return Ve(e,te(e.home,"ahpd"),"config.json",t)}async function Me(e,t){if(!Ut(t.id))throw Error("HOST_JOIN_CONFIG_CONFLICT");let s=te(e.home,"ahpd","agents");await Y(s),await Ve(e,s,`${t.id}.json`,{...t})}async function Ve(e,t,s,f){let y=te(t,s),a;try{if(JSON.stringify(f).includes(e.authorization))throw Error("HOST_JOIN_CONFIG_SECRET");a=await vt(te(t,".config-"));let h=te(a,"config.json");Ge(h,f,{mode:384});try{await Rt(h,y)}catch(I){if(!I||typeof I!=="object"||!("code"in I)||I.code!=="EEXIST")throw Error("HOST_JOIN_CONFIG_PUBLICATION_FAILED")}let S=await bt(y);if(!S.isFile()||S.uid!==process.getuid?.()||(S.mode&511)!==384)throw Error("HOST_JOIN_UNSAFE_PATH");let T=$t(y);if(!T.ok)throw Error("HOST_JOIN_CONFIG_CORRUPT");let N={};for(let[I,E]of Object.entries(f)){let v=I==="unattendedAutoApprove"&&E===!1||I==="pluginMarketplaces"&&Array.isArray(E)&&E.length===0;if(s==="config.json"&&v&&!Object.hasOwn(T.value,I)){N[I]=E;continue}if(!Dt(T.value[I],E))throw Error("HOST_JOIN_CONFIG_CONFLICT")}if(Object.keys(N).length>0)Ge(y,{...T.value,...N},{mode:384});return await Z(y),y}catch(h){if(h instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(h.message))throw h;throw Error("HOST_JOIN_CONFIG_IO")}finally{if(a!==void 0)await Ct(a,{recursive:!0})}}import{isRecord as W}from"@ahpd/sdk";class ne extends Error{kind;status;serverCode;constructor(e,t,s){super(e);this.kind=e;this.status=t;this.serverCode=s}}function Pt(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 We(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}})}),f;try{f=await fetch(s)}catch{throw Error("HOST_JOIN_NETWORK_UNKNOWN")}if(f.status===410){let a;try{a=await f.json()}catch{}if(W(a)&&W(a.error)&&a.error.code==="HOST_REGISTRATION_CANCELLED")throw Error("HOST_JOIN_CANCELLED");throw Error("HOST_JOIN_LINK_UNAVAILABLE")}if(f.status>=500){let a;try{a=await f.json()}catch{}let h=W(a)&&W(a.error)&&_(a.error.code)?a.error.code:void 0;if(h==="HOST_REGISTRATION_UNSETTLED")throw new ne("HOST_JOIN_UNSETTLED",f.status,h);throw Error("HOST_JOIN_REMOTE_UNAVAILABLE")}if(!f.ok){let a;try{a=await f.json()}catch{}let h=W(a)&&W(a.error)&&_(a.error.code)?a.error.code:void 0;throw new ne(Pt(f.status,h),f.status,h)}let y;try{y=await f.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 Jt,stat as he}from"node:fs/promises";import{constants as Lt}from"node:fs";import{delimiter as xt,dirname as ze,isAbsolute as Ft,join as Kt}from"node:path";import{fileURLToPath as jt}from"node:url";import{fromEnvRef as Gt,isRecord as V,isRecordSlug as Bt,readJsonObject as Mt,scopeOf as Vt,secretPaths as Wt,secretRef as zt}from"@ahpd/sdk";import{checkManifest as Yt,checkStandalone as Zt,readManifest as Xt,readStandalone as qt,resolvePlugin as Qt}from"@ahpd/server/dist/plugins.js";function U(e="HOST_JOIN_OWNER_RESOURCE"){throw Error(e)}function Ye(e){let t=Gt(e);if(t!==void 0){if(!process.env[t])U();return!0}let s=zt(e);if(s===void 0)return!1;return Vt(s),!0}async function en(e){let t=Ft(e)?[e]:(process.env.PATH??"").split(xt).map((s)=>Kt(s,e));for(let s of t)try{if(await Jt(s,Lt.X_OK),(await he(s)).isFile())return}catch{}U()}async function re(e){let t=Mt(e);if(!t.ok)U("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))U();let f=new Set,y=new Set,a=[];try{for(let I of s.plugins){let E=typeof I==="string"?{source:I}:I;if(!V(E)||typeof E.source!=="string"||E.enabled===!1)U();let H=Qt(E,{cwd:ze(e),configDir:ze(e)});if(!H.path||!(await he(H.path)).isFile())U();let k=H.manifestPath?qt(H.manifestPath):H.packageDir?Xt(H.packageDir):void 0;if(!k||k.problem||(k.standalone?Zt(k):Yt(k,H.packageDir)))U();if(k.name==="@ahpd/bot"||k.name==="bot")U("HOST_JOIN_OWNER_BOT");for(let D of k.contracts?.engines??[])f.add(D);for(let D of k.contracts?.agents??[])y.add(D);if(E.options!==void 0&&!V(E.options))U();let J=V(E.options)?E.options:{};for(let D of Wt(k.optionsSchema??{},J)){let L=J;for(let G of D.split("."))L=V(L)?L[G]:void 0;if(L!==void 0&&!Ye(L))U("HOST_JOIN_OWNER_SECRET")}a.push({...E,source:H.manifestPath??H.packageDir??H.path})}let h=[],S=new Set(y);for(let I of s.records){if(!V(I)||typeof I.id!=="string"||!Bt(I.id)||S.has(I.id)||typeof I.engine!=="string"||!f.has(I.engine)||typeof I.owner!=="string"||typeof I.name!=="string"||!V(I.config)||I.mode!==void 0&&I.mode!=="enabled")U();if(I.model!==void 0&&(typeof I.model!=="string"||I.model.trim()===""))U();if(I.engine==="acp"&&typeof I.config.command!=="string")U();if(I.config.command!==void 0){if(typeof I.config.command!=="string"||!I.config.command)U();await en(I.config.command)}if(I.config.env!==void 0){if(!V(I.config.env))U();for(let E of Object.values(I.config.env))if(!Ye(E))U("HOST_JOIN_OWNER_SECRET")}S.add(I.id),h.push(I)}let T=[],N=new Set;for(let I of s.agents){if(!Array.isArray(I)||I.length!==2||typeof I[0]!=="string"||!I[0]||N.has(I[0])||!V(I[1])||typeof I[1].provider!=="string"||!S.has(I[1].provider)||typeof I[1].workingDirectory!=="string")U();let E=new URL(I[1].workingDirectory);if(E.protocol!=="file:"||E.hostname||!(await he(jt(E))).isDirectory())U();if(I[1].settings!==void 0&&!V(I[1].settings))U();N.add(I[0]),T.push([I[0],{provider:I[1].provider,workingDirectory:E.href,...I[1].settings===void 0?{}:{settings:I[1].settings}}])}return{agents:T,plugins:a,records:h}}catch(h){if(h instanceof Error&&/^HOST_JOIN_OWNER_[A-Z_]+$/u.test(h.message))throw h;return U()}}import{constants as tn}from"node:fs";import{access as nn,mkdir as rn,stat as on,writeFile as sn}from"node:fs/promises";import{createRequire as an}from"node:module";import{dirname as Xe,resolve as qe}from"node:path";import{pathToFileURL as dn}from"node:url";class ae extends Error{file;entry;constructor(e,t){super("HOST_JOIN_OWNER_CONFIG_NEEDS_AGENT");this.file=e;this.entry=t}}function cn(){try{return Xe(an(import.meta.url).resolve("@ahpd/agent-acp/package.json"))}catch{throw Error("HOST_JOIN_AGENT_PLUGIN_MISSING")}}function Qe(e,t,s){return[t,{provider:e.id,workingDirectory:dn(qe(s)).href}]}function ln(e,t,s){return JSON.stringify(Qe(e,t,s))}function un(e,t){let[s,f]=Qe(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,f]]},null,2)}
2
- `}async function et(e){let t=qe(e.file);if(await nn(t,tn.F_OK).then(()=>!0,()=>!1))return Ze(t,e);await rn(Xe(t),{recursive:!0,mode:448});try{await sn(t,un(e,cn()),{flag:"wx",mode:384})}catch(f){if(f!==null&&typeof f==="object"&&"code"in f&&f.code==="EEXIST")return Ze(t,e);throw Error("HOST_JOIN_OWNER_FILE_IO")}let s=await on(t);if(!s.isFile()||s.uid!==process.getuid?.()||(s.mode&511)!==384)throw Error("HOST_JOIN_UNSAFE_PATH");return re(t)}async function Ze(e,t){let s=await re(e);if(s.agents.some(([f])=>f===t.agentMemberId))return s;throw new ae(e,ln(t.app,t.agentMemberId,t.workingDirectory))}import{access as Vn}from"node:fs/promises";import{constants as Wn}from"node:fs";import{createHash as gn}from"node:crypto";import{lstat as tt,mkdir as fn,mkdtemp as hn,readFile as me,rename as pn,rm as mn,writeFile as pe}from"node:fs/promises";import{isAbsolute as nt,join as j,normalize as de}from"node:path";var yn="hightea-pipe",we="bundle.json";function _e(e){return j(e,"hightea","plugins")}async function rt(e){let t;try{t=await me(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 f=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,a=typeof s==="object"&&s!==null&&"version"in s?s.version:void 0;if(y!==yn||typeof a!=="string"||typeof f!=="string"||nt(f)||de(f).startsWith("..")||de(f).includes("/")||["plugin.json",we].includes(de(f)))throw Error("HOST_JOIN_PLUGIN_BUNDLE");let h;try{h=await me(j(e,f))}catch{throw Error("HOST_JOIN_PLUGIN_BUNDLE")}return{manifestBytes:t,version:a,main:de(f),mainBytes:h,sha256:wn(t,h)}}function wn(e,t){return gn("sha256").update(e).update("\x00").update(t).digest("hex")}async function ce(e){let t=j(e,".."),s;try{s=JSON.parse(await me(j(t,we),"utf8"))}catch(y){return{ok:!1,reason:ot(y)?"missing":"corrupt"}}let f;try{f=await rt(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!==f.sha256)return{ok:!1,reason:"corrupt"};return{ok:!0,bundle:{manifest:e,version:s.version,sha256:f.sha256}}}async function Ie(e,t,s){if(!nt(e)||!/^[0-9A-Za-z.+-]+$/u.test(s))throw Error("HOST_JOIN_UNSAFE_PATH");let f=await rt(t);if(f.version!==s)throw Error("HOST_JOIN_PLUGIN_BUNDLE");try{await fn(e,{recursive:!0,mode:448});let T=await tt(e);if(!T.isDirectory()||T.uid!==process.getuid?.()||(T.mode&18)!==0)throw Error("unsafe")}catch{throw Error("HOST_JOIN_UNSAFE_PATH")}let y=_e(e);for(let T of[j(e,"hightea"),y])await Y(T);let a=j(y,s),h=j(a,"plugin.json");if(!await _n(a)){let T=await hn(j(y,`.${s}-`));try{await pe(j(T,"plugin.json"),f.manifestBytes,{mode:384}),await pe(j(T,f.main),f.mainBytes,{mode:384}),await pe(j(T,we),`${JSON.stringify({version:s,sha256:f.sha256})}
3
- `,{mode:384});try{await pn(T,a)}catch(N){if(!ye(N,"EEXIST")&&!ye(N,"ENOTEMPTY"))throw Error("HOST_JOIN_CONFIG_IO")}}finally{await mn(T,{recursive:!0,force:!0})}}let S=await ce(h);if(!S.ok||S.bundle.sha256!==f.sha256||S.bundle.version!==s)throw Error("HOST_JOIN_PLUGIN_BUNDLE_CONFLICT");return S.bundle}async function _n(e){try{return await tt(e),!0}catch(t){if(ot(t))return!1;throw Error("HOST_JOIN_UNSAFE_PATH")}}function ot(e){return ye(e,"ENOENT")}function ye(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}import{createPrivateKey as kn,createPublicKey as Rn,generateKeyPairSync as bn,sign as lo}from"node:crypto";import{appendFile as go,chmod as vn,readFile as it,rename as Cn,writeFile as Dn}from"node:fs/promises";import{join as st}from"node:path";var eo=Buffer.from("302a300506032b6570032100","hex");import{createHash as On}from"node:crypto";import{existsSync as Sn,readFileSync as Tn}from"node:fs";import{join as Nn}from"node:path";var En="trusted-keys.json",m=/^(?=.{1,64}$)[A-Za-z0-9][A-Za-z0-9._-]*(?: [A-Za-z0-9._-]+)*$/u,An=/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/u,Hn=(e)=>Buffer.from(e).toString("base64url");function o(e){if(!An.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:Hn(On("sha256").update(Buffer.from(e,"base64url")).digest())}}function g(e){let t=Nn(e,En);if(!Sn(t))return{state:"missing",file:t};let s;try{s=JSON.parse(Tn(t,"utf8"))}catch(y){throw Error(`TRUST_FILE_UNREADABLE: ${t} is not JSON (${y.message})`)}let f=s;if(typeof s!=="object"||s===null||f.v!==1||!Array.isArray(f.keys))throw Error(`TRUST_FILE_UNREADABLE: ${t} is not a version 1 list of trusted keys`);for(let y of f.keys){let a=y,h=typeof a.publicKey==="string"?o(a.publicKey):void 0;if(typeof a.name!=="string"||!m.test(a.name)||h===void 0||"error"in h||a.keyId!==h.keyId||typeof a.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:f.keys}}var at="host-signing-key";async function dt(e){try{await it(st(e,at))}catch(t){if(t.code==="ENOENT")return{state:"missing"}}try{return{state:"ok",key:await Un(e)}}catch(t){return{state:"unreadable",reason:t instanceof Error?t.message:String(t)}}}async function Un(e,t=()=>Date.now()){let s=st(e,at),f;try{f=await it(s,"utf8")}catch(S){if(S.code!=="ENOENT")throw Error(`HOST_KEY_UNREADABLE: ${s} exists but cannot be read (${String(S)}); it is never regenerated, fix or remove it by hand`)}if(f===void 0){let S=bn("ed25519").privateKey.export({format:"pem",type:"pkcs8"}).toString(),T=`${s}.${String(process.pid)}.tmp`;await Dn(T,S,{mode:384,flag:"wx"}),await vn(T,384),await Cn(T,s),f=S}let y;try{if(y=kn({key:f,format:"pem"}),y.asymmetricKeyType!=="ed25519")throw Error(`a ${String(y.asymmetricKeyType)} key, not Ed25519`)}catch(S){throw Error(`HOST_KEY_UNREADABLE: ${s} is not an Ed25519 PKCS8 key (${String(S)}); it is never regenerated, fix or remove it by hand`)}let a=Rn(y).export({format:"jwk"}).x,h=a===void 0?{error:"no public key"}:o(a);if("error"in h)throw Error(`HOST_KEY_UNREADABLE: ${s}: ${h.error}`);return{privateKey:y,trusted:{name:"this-host",keyId:h.keyId,publicKey:a,addedAt:new Date(t()).toISOString()}}}import{createServer as $n}from"node:net";var ct="hightea";function lt(e){return`http://127.0.0.1:${String(e)}/mcp`}function Pn(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 ut(e){let t=Pn(e);for(let s=0;s<200;s+=1){let f=40000+(t-40000+s)%20000;if(await Jn(f))return f}throw Error(`HOST_TOOLS_PORT_UNAVAILABLE: every port from ${String(t)} to ${String(t+199)} on 127.0.0.1 is taken`)}async function Jn(e){let t=$n();return await new Promise((s)=>{t.once("error",()=>{s(!1)}),t.listen(e,"127.0.0.1",()=>{t.close(()=>{s(!0)})})})}var zn="hightea host join --origin https://your-deployment --workspace SLUG --code CODE --owner-config /absolute/owner.json",Yn=(e)=>[...e].some((t)=>{let s=t.codePointAt(0)??0;return s<32||s===127});function Zn(e=Fn()){let t=e.trim();return t===""||t.length>64||Yn(t)?void 0:t}var Xn="https://hightea.ai/docs/host#owner";class Ee extends Error{file;constructor(e){super("HOST_JOIN_OWNER_CONFIG_MISSING");this.file=e}}var qn=(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 ${Xn} — then run the same command again. Nothing was redeemed and nothing was written.`,Qn=(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 Ae extends Error{appName;install;constructor(e,t){super("HOST_JOIN_APP_MISSING");this.appName=e;this.install=t}}var er=(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: ${zn}`,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]||P(xn(),t);if(!wt(s))throw Error("HOST_JOIN_UNSAFE_PATH");return s}function tr(){let e=Ln(import.meta.url).resolve("@ahpd/server/package.json");return{node:process.execPath,main:P(F(e),"dist","main.js")}}var Se=(e)=>`'${e.replaceAll("'","'\\''")}'`;function ie(e,t=tr()){return`XDG_CONFIG_HOME=${Se(e)} ${Se(t.node)} ${Se(t.main)} start`}var nr={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"},rr={HOST_JOIN_NOT_AUTHORIZED:3,HOST_JOIN_AGENT_BOUND:4,HOST_JOIN_REJECTED:1,HOST_JOIN_UNSETTLED:2};function or(e){let t=e.serverCode===void 0?"":` The deployment says ${nr[e.serverCode]}.`;return`${e.kind}: ${q[e.kind]}${t} (HTTP ${e.status}, server code ${e.serverCode??"unrecognised"})`}async function O(e,t){try{let{origin:s,workspace:f,code:y,ownerConfig:a}=e;if(!s||!f||!y||!a)throw Error("HOST_JOIN_USAGE");let h=Kn(a),S=await Vn(h,Wn.F_OK).then(()=>!0,()=>!1);if(!S&&e.ownerConfigIsDefault!==!0)throw Error("HOST_JOIN_OWNER_INPUT");if(!S&&e.app===void 0)throw new Ee(h);let T=e.app===void 0?void 0:p(e.app);if(T!==void 0&&!await w(T))throw new Ae(T.name,u(T));let N=S?await re(h):null,I=z("XDG_CONFIG_HOME",".config"),E=z("XDG_DATA_HOME",P(".local","share")),v=Zn(),H={origin:s,workspaceSlug:f,code:y,pluginVersion:t.version,ahpdVersion:"0.15.0-rc.4",ownerConfiguration:N,...v===void 0?{}:{name:v},...e.app===void 0?{}:{app:e.app},...e.hostId===void 0?{}:{hostId:e.hostId}},k;if(e.hostId===void 0)k=await xe(I,H);else{let B=await n(e.hostId);if("error"in B)throw Error("HOST_JOIN_NO_CLAIM_FOR_HOST");k=await Fe(I,B.claim,H)}if(k.intent.pluginVersion!==t.version)throw Error("HOST_JOIN_CLAIM_VERSION");let J=Mn({file:k.vaultFile}),D=async(B)=>{let ve=Bn(B),Ce=jn(B);if(Ce!==void 0){if(!process.env[Ce])throw Error("HOST_JOIN_OWNER_RESOURCE")}else if(ve!==void 0)try{await Gn(J,ve)}catch{throw Error("HOST_JOIN_OWNER_RESOURCE")}else if(Array.isArray(B))for(let ue of B)await D(ue);else if(K(B))for(let ue of Object.values(B))await D(ue)};if(N!==null)await D(N);let L=await Ie(E,t.directory,t.version),G=await We(k);if(G.state==="pending")return console.log("Host registration pending. Run the same command again to resume."),2;let Q=T===void 0?N:await et({file:h,app:T,agentMemberId:hr(G.agentMemberId),workingDirectory:e.workingDirectory??process.cwd()});if(Q===null)throw Error("HOST_JOIN_OWNER_INPUT");if(T!==void 0)await D(Q);for(let B of Q.records)await Me(k,B);let Re=new URL(`/gateway/${encodeURIComponent(G.workspaceId)}/host`,k.intent.origin);Re.protocol="wss:";let be=await ut(k.home);return await Be(k,{host:"127.0.0.1",updateCheck:!1,httpApi:!1,modelApi:!1,mcpTools:"none",unattendedAutoApprove:!1,pluginMarketplaces:[],mcpServers:{[ct]:{type:"http",url:lt(be)}},plugins:[...Q.plugins,{source:L.manifest,grants:[...It],options:{cloudUrl:Re.href,workspaceId:G.workspaceId,agents:Q.agents,mcpUrl:new URL(`/w/${encodeURIComponent(G.workspaceId)}`,k.intent.origin).href,hostToolsPort:be,headers:{[c]:G.hostId,authorization:{$secret:"host:hightea"}}}}]}),console.log(`Host registered; local configuration saved. Start it with: ${ie(k.home)}`),0}catch(s){if(s instanceof ne)return console.error(or(s)),rr[s.kind];if(s instanceof Ee)return console.error(qn(s.file)),1;if(s instanceof ae)return console.error(Qn(s.file,s.entry)),1;if(s instanceof Ae)return console.error(er(s)),1;let f=s instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(s.message)?s.message:"HOST_JOIN_INPUT";return console.error(`${f}: ${q[f]??"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 He(e){return K(e)&&K(e.options)&&typeof(e.options.workspaceId??e.options.houseId)==="string"&&K(e.options.headers)&&typeof(e.options.headers[c]??e.options.headers[l])==="string"}async function ke(e){let t=P(e,"ahpd","config.json"),s;try{s=await oe(t,"utf8")}catch(N){return typeof N==="object"&&N!==null&&"code"in N&&N.code==="ENOENT"?{claim:e,state:"pending"}:{claim:e,state:"unreadable",config:t}}let f;try{f=JSON.parse(s)}catch{return{claim:e,state:"unreadable",config:t}}let a=(K(f)&&Array.isArray(f.plugins)?f.plugins:[]).find(He);if(a===void 0||typeof a.source!=="string"||!K(a.options)||!K(a.options.headers))return{claim:e,state:"unreadable",config:t};let h=a.source,S=await ce(h),T=!S.ok?S.reason:S.bundle.version===yt(F(h))?"ok":"wrong-version";return{claim:e,state:"joined",config:t,start:ie(e),pluginBundle:h,bundle:T,...S.ok?{pluginVersion:S.bundle.version}:{},workspaceId:String(a.options.workspaceId??a.options.houseId),hostId:String(a.options.headers[c]??a.options.headers[l]),...typeof a.options.cloudUrl==="string"?{gateway:a.options.cloudUrl}:{},signingKey:await sr(F(t)),...await ir(F(t))}}async function ir(e){let t=await Ot(e);if(t===void 0||t instanceof Error)return{};return{heldBundle:{from:t.from,toVersion:t.toVersion,connected:await St(e)===t.toVersion}}}async function sr(e){let t=await dt(e);if(t.state==="ok")return{state:"ok",keyId:t.key.trusted.keyId,publicKey:t.key.trusted.publicKey};return t}function ar(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 dr(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=P(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 le(t)).filter((a)=>!a.startsWith(".")).sort()}catch(a){if(!(typeof a==="object"&&a!==null&&("code"in a)&&a.code==="ENOENT"))return console.error(`HOST_STATUS_UNREADABLE: cannot list ${t}`),1}let f=await Promise.all(s.map((a)=>ke(P(t,a))));if(e.json)console.log(JSON.stringify({version:e.version,claims:t,hosts:f},null,2));else for(let a of f)if(a.state==="pending")console.log(`pending ${a.claim} (registration not finished; rerun the same join command)`);else if(a.state==="unreadable")console.log(`unreadable ${a.config}`);else console.log([`joined workspace ${a.workspaceId} host ${a.hostId}`,` gateway ${a.gateway??"(none)"}`,` config ${a.config}`,` start ${a.start}`,` plugin ${a.pluginBundle} (${a.bundle}${dr(a.pluginVersion,e.version)})`,` key ${ar(a.signingKey)}`,...a.heldBundle===void 0?[]:[` held ${a.heldBundle.from} until this host connects at ${a.heldBundle.toVersion}${a.heldBundle.connected?" (it has; the next `hightea host update` removes it)":""}`]].join(`
4
- `));let y=f.filter((a)=>a.state==="joined"&&a.bundle!=="ok");for(let a of y){let h=a.bundle==="missing"?"is missing":a.bundle==="corrupt"?"does not match its recorded hash":`records version ${a.pluginVersion}, not the version its directory names`,S=a.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 ${a.pluginBundle} ${h}; the host cannot load it. ${S}`)}if(y.length>0)return 2;if(f.some((a)=>a.state==="unreadable"))return console.error("HOST_STATUS_CONFIG_UNREADABLE: a saved host configuration could not be read; it was left unchanged."),1;if(!f.some((a)=>a.state==="joined"))return console.error(`HOST_STATUS_NONE: no joined host under ${t}.`),1;return 0}var It=["session:write","session:state","session:list","chat:turns","agent:list"],Te=["service:watch","service:logs","service:put","service:remove","service:start","service:stop","service:restart","service:accept"],ft=["services:list","services:get","services:put","services:delete","services:control"];async function n(e){let t;try{t=P(z("XDG_CONFIG_HOME",".config"),"hightea","claims")}catch{return{error:`SERVICE_UNSAFE_PATH: ${q.HOST_JOIN_UNSAFE_PATH}`}}let s=[];try{s=(await le(t)).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 ${t}`}}let f=await Promise.all(s.map((h)=>ke(P(t,h)))),y=f.filter((h)=>h.state==="joined"),a=e?.trim();if(a!==void 0&&a!==""){let h=y.find((S)=>S.hostId===a);if(h===void 0)return{error:`SERVICE_HOST_UNKNOWN: no joined host ${a} on this machine (joined here: ${y.map((S)=>S.hostId).join(", ")||"none"})`};return ht(h)}if(y.length===0){let h=f.find((S)=>S.state==="unreadable");return{error:h===void 0?`SERVICE_NO_HOST: no joined host under ${t}; join this machine with \`hightea host join\` first`:`SERVICE_HOST_UNREADABLE: ${h.config} could not be read; it was left unchanged`}}if(y.length>1)return{error:`SERVICE_HOST_AMBIGUOUS: this machine holds ${y.length} joined hosts (${y.map((h)=>h.hostId).join(", ")}); name one with --host <id>`};return ht(y[0])}function ht(e){let t=e.config;return{claim:e.claim,configDir:F(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 le(e)}catch{return[]}let s=[],f=new Set;for(let y of t){if(!/^\d+$/u.test(y))continue;let a;try{a=(await oe(P(e,y,"cmdline"),"utf8")).split("\x00").filter((k)=>k!=="")}catch{continue}let h=a.indexOf("--config-file"),S=h<0?void 0:a[h+1];if(S===void 0||!wt(S)||f.has(S))continue;f.add(S);let T=F(S),N=(k)=>{let J=a.indexOf(k),D=J<0?void 0:a[J+1];return D===void 0||D===""?void 0:D},I=N("--port"),E=I!==void 0&&/^\d{1,5}$/u.test(I)?Number(I):void 0,v=N("--connection-token-file"),H=N("--host")??"127.0.0.1";s.push({pid:Number(y),config:S,configDir:T,hostIds:await cr(S),host:H,...E===void 0?{}:{port:E},...v===void 0?{}:{connectionTokenFile:v}})}return s}async function cr(e){let t;try{t=JSON.parse(await oe(e,"utf8"))}catch{return[]}if(!K(t)||!Array.isArray(t.plugins))return[];let s=new Set;for(let f of t.plugins){if(!K(f)||!K(f.options)||!K(f.options.headers))continue;let y=f.options.headers[c]??f.options.headers[l];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=_t(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 f=Array.isArray(s.value.plugins)?s.value.plugins:[],y=f.findIndex(He),a=f[y];if(a===void 0)return console.error(`SERVICE_CONFIG_UNREADABLE: ${t.config} holds no Hightea plugin entry; it was left unchanged`),1;if(a.grants!==void 0&&!(Array.isArray(a.grants)&&a.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 h=a.grants??[],S=[...Te,...ft],T=ft,N=h.filter((H)=>!T.includes(H)),I=e.enable?[...N,...Te.filter((H)=>!N.includes(H))]:h.filter((H)=>!S.includes(H)),E=`Hightea managing this machine's services (host ${t.hostId})`;if(I.length===h.length&&I.every((H,k)=>H===h[k]))return console.log(`${E} is already ${e.enable?"enabled":"disabled"}; ${t.config} was left unchanged.`),0;let v=f.slice();v[y]={...a,grants:I};try{Ne(t.config,{...s.value,plugins:v},{mode:384})}catch(H){return console.error(`SERVICE_CONFIG_UNWRITABLE: ${t.config}: ${H.message}`),1}return console.log(`${E} is now ${e.enable?"enabled":"disabled"}: ${e.enable?"added":"removed"} ${Te.join(", ")} in ${t.config}.`),console.log(`It takes effect when this host's ahpd next loads its configuration; restart it with: ${ie(t.claim)}`),0}function pt(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 lr(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",ur="pipe-connected.json";async function Ot(e){let t;try{t=await oe(P(e,X),"utf8")}catch(f){return K(f)&&f.code==="ENOENT"?void 0:Error(`cannot read ${P(e,X)}`)}let s;try{s=JSON.parse(t)}catch{return Error(`${P(e,X)} is not JSON`)}if(!K(s)||typeof s.from!=="string"||typeof s.to!=="string"||typeof s.fromVersion!=="string"||typeof s.toVersion!=="string"||typeof s.at!=="string")return Error(`${P(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 St(e){try{let t=JSON.parse(await oe(P(e,ur),"utf8"));return K(t)&&typeof t.version==="string"?t.version:void 0}catch{return}}async function gr(){let e;try{e=P(z("XDG_CONFIG_HOME",".config"),"hightea","claims")}catch{return{error:`HOST_UPDATE_UNSAFE_PATH: ${q.HOST_JOIN_UNSAFE_PATH}`}}let t;try{t=(await le(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(P(e,s))))}}async function fr(e,t){let s,f;try{s=await Oe(F(e.from))}catch{return{refused:"it cannot be resolved"}}try{f=await Oe(_e(z("XDG_DATA_HOME",P(".local","share"))))}catch{return{refused:"the plugin bundles root cannot be resolved"}}if(F(s)!==f)return{refused:`it is not directly under the plugin bundles root ${f}`};if(yt(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 a;try{a=await Oe(F(y.pluginBundle))}catch{continue}if(a===s)return{refused:`${y.config} names it now`}}return{directory:s}}async function mt(e){let t=await Ot(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 St(e.configDir)!==t.toVersion){console.log(`Keeping the previous plugin bundle ${F(t.from)} until this host connects at ${t.toVersion}; restart it with: ${ie(e.claim)}`);return}let f=await gr();if("error"in f){console.error(`${f.error}; the previous bundle ${F(t.from)} was kept`);return}let y=f.entries.filter((h)=>h.pluginBundle===t.from||h.state==="unreadable");if(y.length>0){console.log(`Keeping the previous plugin bundle ${F(t.from)}: ${y.map((h)=>h.state==="unreadable"?`${h.config} (unreadable)`:h.config).join(", ")} may still name it.`);return}let a=await fr(t,f.entries);if("refused"in a){console.error(`HOST_UPDATE_PRUNE_REFUSED: ${F(t.from)}: ${a.refused}; nothing was removed`);return}try{await gt(a.directory,{recursive:!0,force:!0}),await gt(P(e.configDir,X),{force:!0})}catch(h){console.error(`HOST_UPDATE_PRUNE_FAILED: ${F(t.from)}: ${h.message}`);return}console.log(`Removed the previous plugin bundle ${F(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 f=_t(s.config);if(!f.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(f.value.plugins)?f.value.plugins:[],a=y.findIndex(He),h=y[a];if(h===void 0||typeof h.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 S=await ce(h.source);if(!S.ok)return console.error(`HOST_UPDATE_BUNDLE_UNREADABLE: the installed plugin bundle ${h.source} is ${S.reason}; nothing changed. \`hightea host status\` names the repair.`),1;let T=S.bundle.version,N=pt(T),I=pt(t.version);if(N===void 0||I===void 0)return console.error(`HOST_UPDATE_VERSION_UNREADABLE: cannot order the installed bundle ${T} against this CLI's ${t.version} (each must be x.y.z or x.y.z-dev.<hash8>); nothing changed`),1;let E=lr(I,N)||(t.version===T?0:1);if(E<0)return console.error(`HOST_UPDATE_DOWNGRADE: host ${s.hostId} runs plugin bundle ${T}, newer than this CLI's ${t.version}; nothing changed. Update the CLI instead.`),1;if(E===0)return console.log(`Host ${s.hostId} already runs plugin bundle ${T}; ${s.config} was left unchanged.`),await mt(s),0;await mt(s);let v;try{v=await Ie(z("XDG_DATA_HOME",P(".local","share")),t.directory,t.version)}catch(L){let G=L instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(L.message)?L.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:h.source,to:v.manifest,fromVersion:T,toVersion:v.version,at:new Date().toISOString()},k=y.slice(),J=Array.isArray(h.grants)?h.grants.filter((L)=>typeof L==="string"):[],D=It.filter((L)=>!J.includes(L));k[a]={...h,source:v.manifest,...D.length===0?{}:{grants:[...J,...D]}};try{Ne(P(s.configDir,X),H,{mode:384}),Ne(s.config,{...f.value,plugins:k},{mode:384})}catch(L){return console.error(`HOST_UPDATE_CONFIG_UNWRITABLE: ${s.config}: ${L.message}`),1}return console.log(`Host ${s.hostId} now loads plugin bundle ${v.version} (was ${T}), 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 ${F(h.source)} is kept until the host connects at ${v.version}. Restart it with: ${ie(s.claim)}`),0}function hr(e){if(e===void 0||e==="")throw Error("HOST_JOIN_RECEIPT_INVALID");return e}
5
- export{m,o,g,O,R,n,i,x,C};
@@ -1 +0,0 @@
1
- import{O,R,n,i,x,C}from"./chunk-c7atktnb.js";import"./chunk-ah99zytf.js";export{O as hostJoin,x as hostServicesGrants,R as hostStatus,C as hostUpdate,n as localHost,i as runningAhpds};
@@ -1 +0,0 @@
1
- import{h}from"./chunk-nfmmht3j.js";import"./chunk-c7atktnb.js";import"./chunk-ah99zytf.js";export{h as hostTrust};