@hallohuman/hightea 0.1.32 → 0.1.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +23 -23
- package/dist/{chunk-nfmmht3j.js → chunk-3w7svm2r.js} +1 -1
- package/dist/{chunk-749gsvce.js → chunk-4gpw7vjp.js} +69 -69
- package/dist/{chunk-wyzpk81n.js → chunk-88mhcx5q.js} +1 -1
- package/dist/{chunk-5hvk5pvs.js → chunk-9fxpgay8.js} +1 -1
- package/dist/chunk-a1vwy98c.js +1 -0
- package/dist/chunk-axj8ef03.js +1 -0
- package/dist/chunk-dw3tmpqv.js +1 -0
- package/dist/{chunk-h9f45p57.js → chunk-e9s05rg6.js} +4 -4
- package/dist/{chunk-v221hgba.js → chunk-evg5apz3.js} +2 -2
- package/dist/{chunk-pexgyagn.js → chunk-jaf9mk6s.js} +2 -2
- package/dist/{chunk-dvsftn8z.js → chunk-kjkww5cr.js} +4 -4
- package/dist/chunk-kq5y08g7.js +5 -0
- package/dist/{chunk-hrtxeg8j.js → chunk-ntj1fcak.js} +1 -1
- package/dist/{chunk-dzr0pvfa.js → chunk-p1142ccr.js} +1 -1
- package/dist/chunk-q669464j.js +13 -0
- package/dist/{chunk-ah99zytf.js → chunk-tay0pyz4.js} +2 -2
- package/dist/{chunk-55a0ndzw.js → chunk-vzkbknwq.js} +1 -1
- package/dist/{chunk-7mgx0krk.js → chunk-ym5anbc7.js} +1 -1
- package/dist/plugin/plugin.json +1 -1
- package/dist/plugin/plugin.mjs +3 -3
- package/package.json +2 -2
- package/dist/chunk-c7atktnb.js +0 -5
- package/dist/chunk-gbwfgq6g.js +0 -1
- package/dist/chunk-pdnrwmme.js +0 -1
- package/dist/chunk-vr4rsfaf.js +0 -13
- package/dist/chunk-w2f84aab.js +0 -1
package/dist/plugin/plugin.mjs
CHANGED
|
@@ -60,7 +60,7 @@ ${t.join(`
|
|
|
60
60
|
}
|
|
61
61
|
`)}return g.write("payload.value = newResult;"),g.write("return payload;"),g.compile()},i,a=mt,c=!Q.jitless,u=c&&Sa.value,l=t.catchall,p;e._zod.parse=(f,m)=>{p??(p=n.value);let y=f.value;if(!a(y))return f.issues.push({expected:"object",code:"invalid_type",input:y,inst:e}),f;if(c&&u&&m?.async===!1&&m.jitless!==!0){if(!i)i=s(t.shape);if(f=i(f,m),!l)return f;return ku([],y,f,m,p,e,m?.abortEarly===!0)}return r(f,m)}});function zc(e,t,r,n){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter((s)=>!he(s));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((s)=>s.issues.map((i)=>xe(i,n,ce())))}),t}var bo=_("$ZodUnion",(e,t)=>{z.init(e,t),P(e,"optin",(n)=>n.def.options.some((o)=>o._zod.optin==="defaulted")?"defaulted":n.def.options.some((o)=>o._zod.optin!==void 0)?"optional":void 0),P(e,"optout",(n)=>n.def.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),P(e,"values",(n)=>{if(n.def.options.every((o)=>o._zod.values))return new Set(n.def.options.flatMap((o)=>Array.from(o._zod.values)));return}),P(e,"pattern",(n)=>{if(n.def.options.every((o)=>o._zod.pattern)){let o=n.def.options.map((s)=>s._zod.pattern);return new RegExp(`^(${o.map((s)=>Or(s.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,o)=>{if(r)return r(n,o);let s=!1,i=[];for(let a of t.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}if(!s)return zc(i,n,e,o);return Promise.all(i).then((a)=>zc(a,n,e,o))}});function Jm(e){let t=new Map;for(let r of e.options){let n=r._zod.propValues?.[e.discriminator];if(!n||n.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(r)}"`);for(let o of n)if(t.has(o)){if(o!==void 0)throw Error(`Duplicate discriminator value "${String(o)}"`);t.set(o,null)}else t.set(o,r)}return t}var Ru=_("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,bo.init(e,t);let r=e._zod.parse;P(e,"propValues",(o)=>{let s={},i=0;for(let a of o.def.options){let c=a._zod.propValues;if(!c||Object.keys(c).length===0)throw Error(`Invalid discriminated union option at index "${o.def.options.indexOf(a)}"`);if(c[o.def.discriminator]?.has(void 0))i++;for(let[d,u]of Object.entries(c)){if(!Object.prototype.hasOwnProperty.call(s,d))fe(s,d,new Set);for(let l of u)s[d].add(l)}}if(!o.def.unionFallback&&i>1)s[o.def.discriminator]?.delete(void 0);return s}),t.options.forEach((o,s)=>{let i=Lt(o._zod.def);if(i&&!Object.prototype.hasOwnProperty.call(i,t.discriminator))throw Error(`Invalid discriminated union option at index "${s}"`)});let n=Dt(()=>Jm(t));e._zod.parse=(o,s)=>{let i=o.value;if(!mt(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),o;let a=i?.[t.discriminator],c=n.value.get(a);if(c&&(a!==void 0||s.direction!=="backward"))return c._zod.run(o,s);if(t.unionFallback||s.direction==="backward")return r(o,s);return o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()).filter((d)=>n.value.get(d)!==null),input:i,path:[t.discriminator],inst:e}),o}}),Ou=_("$ZodIntersection",(e,t)=>{z.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);if(s instanceof Promise||i instanceof Promise)return Promise.all([s,i]).then(([c,d])=>Mc(r,c,d));return Mc(r,s,i)}});function wo(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(Xe(e)&&Xe(t)){let r=Object.keys(t),n=Object.keys(e).filter((s)=>r.indexOf(s)!==-1),o={...e,...t};if(Object.prototype.hasOwnProperty.call(o,"__proto__"))delete o.__proto__;for(let s of n){if(s==="__proto__")continue;let i=wo(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 r=[];for(let n=0;n<e.length;n++){let o=e[n],s=t[n],i=wo(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Mc(e,t,r){let n=new Map,o,s=new Map,i=(d,u)=>{let l;if(d.code==="unrecognized_keys"&&!d.path?.length)o??(o=d),l=d.keys;else if(d.code==="invalid_key"&&d.origin==="record"&&d.path?.length===1){let p=String(d.path[0]);if(!s.has(p))s.set(p,d);l=[p]}else return!1;for(let p of l){if(!n.has(p))n.set(p,{});n.get(p)[u]=!0}return!0};for(let d of t.issues)if(!i(d,"l"))e.issues.push(d);for(let d of r.issues)if(!i(d,"r"))e.issues.push(d);let a=[...n].filter(([,d])=>d.l&&d.r).map(([d])=>d);if(a.length){let d=o?a.filter((u)=>o.keys.includes(u)):[];if(d.length)e.issues.push({...o,keys:d});for(let u of a)if(!d.includes(u)&&s.has(u))e.issues.push(s.get(u))}let c=wo(t.value,r.value);if(!c.valid){if(he(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Tu=_("$ZodTuple",(e,t)=>{z.init(e,t);let r=t.items,n=Q.memoizer;n?.attach(e),e._zod.parse=(o,s)=>{let i=o.value;if(!Array.isArray(i))return o.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),o;o.value=n?n.alloc(e,o,[],s):[];let a=[],c=Dc(r,"optin"),d=Dc(r,"optout");if(!t.rest){if(i.length<c)return o.issues.push({code:"too_small",minimum:c,inclusive:!0,input:i,inst:e,origin:"array"}),o;if(i.length>r.length)o.issues.push({code:"too_big",maximum:r.length,inclusive:!0,input:i,inst:e,origin:"array"})}let u=Array(r.length),l=t.rest?s?.abortEarly:void 0,p=!1;for(let f=0;f<r.length;f++){let m=r[f]._zod.run({value:i[f],issues:[]},s);if(m instanceof Promise)a.push(m.then((y)=>{u[f]=y}));else if(u[f]=m,l&&!p&&m.issues.length)p=he(m)}if(t.rest&&!p){let f=r.length-1,m=i.slice(r.length),y=o.issues.length;for(let g of m){if(l&&o.issues.length!==y){if(he(o,y))break;y=o.issues.length}f++;let w=t.rest._zod.run({value:g,issues:[]},s);if(w instanceof Promise)a.push(w.then((b)=>Lc(b,o,f)));else Lc(w,o,f)}}if(a.length)return Promise.all(a).then(()=>Uc(u,o,r,i,d));return Uc(u,o,r,i,d)}});function Dc(e,t){for(let r=e.length-1;r>=0;r--)if(!(t==="optin"?e[r]._zod.optin!==void 0:e[r]._zod.optout==="optional"))return r+1;return 0}function Lc(e,t,r){if(e.issues.length)t.issues.push(...ve(r,e.issues));t.value[r]=e.value}function Uc(e,t,r,n,o){for(let s=0;s<r.length;s++){let i=e[s],a=s<n.length;if(!a&&s>=o&&r[s]._zod.optin==="optional"){t.value.length=s;break}if(i.issues.length){if(!a&&s>=o){t.value.length=s;break}t.issues.push(...ve(s,i.issues))}t.value[s]=i.value}for(let s=t.value.length-1;s>=n.length;s--)if(r[s]._zod.optout==="optional"&&t.value[s]===void 0)t.value.length=s;else break;return t}var Au=_("$ZodRecord",(e,t)=>{z.init(e,t);let r=Q.memoizer;r?.attach(e),e._zod.parse=(n,o)=>{let s=n.value;if(!Xe(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),n;let i=[],a=t.keyType._zod.values;if(a&&!t.partial){n.value=r?r.alloc(e,n,{},o):{};let c=new Set;for(let u of a)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){if(c.add(typeof u==="number"?u.toString():u),u==="__proto__")continue;let l=t.keyType._zod.run({value:u,issues:[]},o);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(l.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((m)=>xe(m,o,ce())),input:u,path:[u],inst:e});continue}let p=l.value;if(p==="__proto__")continue;let f=t.valueType._zod.run({value:s[u],issues:[]},o);if(f instanceof Promise)i.push(f.then((m)=>{if(m.issues.length)n.issues.push(...ve(u,m.issues));n.value[p]=m.value}));else{if(f.issues.length)n.issues.push(...ve(u,f.issues));n.value[p]=f.value}}let d;for(let u in s)if(!c.has(u))if(t.mode==="loose"){if(u==="__proto__")continue;n.value[u]=s[u]}else d=d??[],d.push(u);if(d&&d.length>0)n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:d,continue:!0})}else{n.value=r?r.alloc(e,n,{},o):{};let c;for(let d of Reflect.ownKeys(s)){if(d==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(s,d))continue;let u=t.keyType._zod.run({value:d,issues:[]},o);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof d==="string"&&Zt.test(d)&&u.issues.length){let m=t.keyType._zod.run({value:Number(d),issues:[]},o);if(m instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(m.issues.length===0)u=m}if(u.issues.length){if(t.mode==="loose")n.value[d]=s[d];else if(a)c=c??[],c.push(d);else n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((m)=>xe(m,o,ce())),input:d,path:[d],inst:e});continue}let p=u.value;if(p==="__proto__")continue;let f=t.valueType._zod.run({value:s[d],issues:[]},o);if(f instanceof Promise)i.push(f.then((m)=>{if(m.issues.length)n.issues.push(...ve(d,m.issues));n.value[p]=m.value}));else{if(f.issues.length)n.issues.push(...ve(d,f.issues));n.value[p]=f.value}}if(c&&c.length>0)n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:c,continue:!0})}if(i.length)return Promise.all(i).then(()=>n);return n}});var $u=_("$ZodEnum",(e,t)=>{z.init(e,t);let r=zt(t.entries),n=new Set(r);e._zod.values=n,P(e,"pattern",(o)=>{let s=zt(o.def.entries).filter((i)=>va.has(typeof i));return new RegExp(s.length?`^(${s.map((i)=>Fe(i.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,s)=>{let i=o.value;if(n.has(i))return o;return o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}}),Pu=_("$ZodLiteral",(e,t)=>{z.init(e,t);let r=new Set(t.values);e._zod.values=r,P(e,"pattern",(n)=>{let o=n.def.values;return new RegExp(o.length?`^(${o.map((s)=>typeof s==="string"?Fe(s):s?Fe(s.toString()):String(s)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(n,o)=>{let s=n.value;if(r.has(s))return n;return n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}});var Nu=_("$ZodTransform",(e,t)=>{z.init(e,t),e._zod.optin="optional",Q.memoizer?.guard(e),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Ut(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then((i)=>(r.value=i,r));if(o instanceof Promise)throw new be;return r.value=o,r}});function Zc(e,t){return e.value=t.issues.length?void 0:t.value,e}var Eo=_("$ZodOptional",(e,t)=>{z.init(e,t),P(e,"optin",(r)=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",P(e,"values",(r)=>{let n=r.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),P(e,"pattern",(r)=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${Or(n.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(r.value===void 0){if(t.innerType._zod.optin!=="defaulted")return r;let o=t.innerType._zod.run({value:r.value,issues:[]},n);if(o instanceof Promise)return o.then((s)=>Zc(r,s));return Zc(r,o)}return t.innerType._zod.run(r,n)}}),zu=_("$ZodExactOptional",(e,t)=>{Eo.init(e,t),P(e,"values",(r)=>r.def.innerType._zod.values),P(e,"pattern",(r)=>r.def.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),Mu=_("$ZodNullable",(e,t)=>{z.init(e,t),P(e,"optin",(r)=>r.def.innerType._zod.optin),P(e,"optout",(r)=>r.def.innerType._zod.optout),P(e,"pattern",(r)=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${Or(n.source)}|null)$`):void 0}),P(e,"values",(r)=>r.def.innerType._zod.values?new Set([...r.def.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>{if(r.value===null)return r;return t.innerType._zod.run(r,n)}}),Du=_("$ZodDefault",(e,t)=>{z.init(e,t),e._zod.optin="defaulted",P(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>jc(s,t));return jc(o,t)}});function jc(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Lu=_("$ZodPrefault",(e,t)=>{z.init(e,t),e._zod.optin="defaulted",P(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,n)}}),Uu=_("$ZodNonOptional",(e,t)=>{z.init(e,t),P(e,"values",(r)=>{let n=r.def.innerType._zod.values;return n?new Set([...n].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>Fc(s,e));return Fc(o,e)}});function Fc(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 Hc(e,t,r,n){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=r.catchValue({...t,value:e.value,error:{issues:t.issues.map((o)=>xe(o,n,ce()))},input:e.value}),e}var Zu=_("$ZodCatch",(e,t)=>{z.init(e,t),P(e,"optin",(r)=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),P(e,"optout",(r)=>r.def.innerType._zod.optout),P(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run({value:r.value,issues:[]},n);if(o instanceof Promise)return o.then((s)=>Hc(r,s,t,n));return Hc(r,o,t,n)}});var ju=_("$ZodPipe",(e,t)=>{z.init(e,t),P(e,"values",(r)=>r.def.in._zod.values),P(e,"optin",(r)=>r.def.in._zod.optin),P(e,"optout",(r)=>r.def.out._zod.optout),P(e,"propValues",(r)=>r.def.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=t.out._zod.run(r,n);if(s instanceof Promise)return s.then((i)=>Fr(i,t.in,n));return Fr(s,t.in,n)}let o=t.in._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>Fr(s,t.out,n));return Fr(o,t.out,n)}});function Fr(e,t,r){if(e.issues.some((n)=>n.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},r)}var Fu=_("$ZodReadonly",(e,t)=>{z.init(e,t),P(e,"propValues",(r)=>r.def.innerType._zod.propValues),P(e,"values",(r)=>r.def.innerType._zod.values),P(e,"optin",(r)=>r.def.innerType?._zod?.optin),P(e,"optout",(r)=>r.def.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then(Bc);return Bc(o)}});function Bc(e){if(!e.memo)e.value=Object.freeze(e.value);return e}var Hu=_("$ZodCustom",(e,t)=>{V.init(e,t),z.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=(r)=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then((s)=>qc(s,r,n,e));qc(o,r,n,e);return}});function qc(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};if(n._zod.def.params)o.params=n._zod.def.params;t.issues.push(Qe(o))}}class qu extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var ko="~memo",Bu=[];function Gu(e){return e!==null&&typeof e==="object"}function Io(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var Ku=new WeakMap,Ht=0,Wr=1,Bt=2;function Jr(e,t,r){let n=Ku.get(e);if(n!==void 0)return n?Bt:Ht;if(t.has(e))return Bt;t.add(e);let o=Ht,s=(u)=>{if(o!==Bt&&u?._zod){let l=Jr(u,t,r);if(l>o)o=l}},i=(u,l)=>{let p=Ht;for(let f of Reflect.ownKeys(u)){let m=Object.getOwnPropertyDescriptor(u,f);if(l&&!m.enumerable)continue;let y=m.get?Wr:m.value?._zod?Jr(m.value,t,r):Ht;if(y>p)p=y}return p},a=(u)=>{if(u>o)o=u},c=e._zod.def,d=c.type;switch(d){case"object":{let u=Lt(c);a(u?i(u,!0):Wr),s(c.catchall);break}case"array":s(c.element);break;case"tuple":for(let u of c.items)s(u);s(c.rest);break;case"record":case"map":s(c.keyType),s(c.valueType);break;case"set":s(c.valueType);break;case"union":for(let u of c.options)s(u);break;case"intersection":s(c.left),s(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":s(c.innerType);break;case"pipe":s(c.in),s(c.out);break;case"function":s(c.input),s(c.output);break;case"lazy":{let u=c._cachedInner??(r?e._zod.innerType:void 0);a(u?Jr(u,t,!1):Wr);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 u in c){let l=Object.getOwnPropertyDescriptor(c,u);if(!l||l.get)continue;let p=l.value;if(!p||typeof p!=="object")continue;if(p._zod)s(p);else if(Array.isArray(p))for(let f of p)s(f)}}return t.delete(e),Ym(e,o)}function Ym(e,t){if(t!==Wr)Ku.set(e,t===Bt);return t}function Xm(e,t){let r=e.buckets.get(t);if(!r)r=new WeakMap,e.buckets.set(t,r);return r}var Kr,Vr=[],Qm={alloc(e,t,r){let n=Kr;if(!n)return r;Kr=void 0;let o={value:r,issues:null};return n.set(t.value,o),Vr.push(o),r},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let r=e._zod.parse,n=(o,s)=>{if(s.direction!=="backward"&&eg(s,o.value))throw new qu;return r(o,s)};if(e._zod.parse=n,e._zod.run===r)e._zod.run=n})},attach(e){var t;let r,n=!1,o,s;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let i=e._zod.parse,a=(c,d)=>{if(r===void 0){let w=Jr(e,new Set,!1);if(w===Ht){if(e._zod.parse=i,e._zod.run===a)e._zod.run=i;return i(c,d)}if(w===Bt||n)r=!0;else n=!0}let u=c.value;if(!Gu(u))return i(c,d);let l=d[ko];if(!l)l={buckets:new WeakMap,backEdges:void 0},d[ko]=l;let p;if(o===d)p=s;else p=Xm(l,e),o=d,s=p;let f=p.get(u);if(f){if(c.value=f.value,f.issues){if(f.issues.length)c.issues.push(...Io(f.issues))}else c.memo=!0,l.backEdges??(l.backEdges=new WeakSet),l.backEdges.add(f.value);return c}Kr=p;let m=Vr.length,y=i(c,d);Kr=void 0;let g=Vr.length>m?Vr.pop():void 0;if(y instanceof Promise)return y.then((w)=>{if(g)g.issues=w.issues.length?Io(w.issues):Bu;return w});if(g)g.issues=y.issues.length?Io(y.issues):Bu;return y};if(e._zod.parse=a,e._zod.run===i)e._zod.run=a})}};function Vu(){return Qm}function eg(e,t){let r=e[ko]?.backEdges;return r!==void 0&&Gu(t)&&r.has(t)}var tg=()=>{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 r={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"},n={nan:"NaN"};function o(s,i){if(s==="number"&&typeof i==="number"&&!Number.isFinite(i))return String(i);return n[s]??s}return(s)=>{switch(s.code){case"invalid_type":{let i=o(s.expected),a=ka(s.input),c=o(a,s.input);return`Invalid input: expected ${i}, received ${c}`}case"invalid_value":if(s.values.length===1)return`Invalid input: expected ${no(s.values[0])}`;return`Invalid option: expected one of ${eo(s.values,"|")}`;case"too_big":{let i=s.exact?"exactly ":s.inclusive?"<=":"<",a=t(s.origin);if(a)return`Too big: expected ${s.origin??"value"} to have ${i}${s.maximum.toString()} ${a.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?">=":">",a=t(s.origin);if(a)return`Too small: expected ${s.origin} to have ${i}${s.minimum.toString()} ${a.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 ${r[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":""}: ${eo(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((a)=>`'${a}'`).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 Co(){return{localeError:tg()}}var Wu;class Ju{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.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 r={...this.get(t)??{}};delete r.id;let n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function rg(){return new Ju}(Wu=globalThis).__zod_globalRegistry??(Wu.__zod_globalRegistry=rg());var et=globalThis.__zod_globalRegistry;function Yu(e){if(e.checks)e.checks=[...e.checks];return e}function Xu(e,t){return new e(Yu({type:"string",...C(t)}))}function Qu(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...C(t)})}function ed(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...C(t)})}function td(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...C(t)})}function rd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...C(t)})}function nd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...C(t)})}function od(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...C(t)})}function sd(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...C(t)})}function id(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...C(t)})}function ad(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...C(t)})}function cd(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...C(t)})}function ud(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...C(t)})}function dd(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...C(t)})}function ld(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...C(t)})}function fd(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...C(t)})}function hd(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...C(t)})}function pd(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...C(t)})}function md(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...C(t)})}function gd(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...C(t)})}function yd(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...C(t)})}function _d(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...C(t)})}function wd(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...C(t)})}function Sd(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...C(t)})}function vd(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...C(t)})}function xd(e,t){return new e({type:"string",format:"date",check:"string_format",...C(t)})}function bd(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...C(t)})}function Ed(e,t){return new e({type:"string",format:"duration",check:"string_format",...C(t)})}function Id(e,t){return new e(Yu({type:"number",checks:[],...C(t)}))}function kd(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...C(t)})}function Cd(e,t){return new e({type:"boolean",...C(t)})}function Rd(e){return new e({type:"unknown"})}function Od(e,t){return new e({type:"never",...C(t)})}function Yr(e,t){return new go({check:"less_than",...C(t),value:e,inclusive:!1})}function qt(e,t){return new go({check:"less_than",...C(t),value:e,inclusive:!0})}function Xr(e,t){return new yo({check:"greater_than",...C(t),value:e,inclusive:!1})}function Gt(e,t){return new yo({check:"greater_than",...C(t),value:e,inclusive:!0})}function Qr(e,t){return new wc({check:"multiple_of",...C(t),value:e})}function en(e,t){return new vc({check:"max_length",...C(t),maximum:e})}function gt(e,t){return new xc({check:"min_length",...C(t),minimum:e})}function tn(e,t){return new bc({check:"length_equals",...C(t),length:e})}function Ro(e,t){return new Ec({check:"string_format",format:"regex",...C(t),pattern:e})}function Oo(e){return new Ic({check:"string_format",format:"lowercase",...C(e)})}function To(e){return new kc({check:"string_format",format:"uppercase",...C(e)})}function Ao(e,t){return new Cc({check:"string_format",format:"includes",...C(t),includes:e})}function $o(e,t){return new Rc({check:"string_format",format:"starts_with",...C(t),prefix:e})}function Po(e,t){return new Oc({check:"string_format",format:"ends_with",...C(t),suffix:e})}function He(e){return new Tc({check:"overwrite",tx:e})}function No(e){return He((t)=>t.normalize(e))}function zo(){return He((e)=>e.trim())}function Mo(){return He((e)=>e.toLowerCase())}function Do(){return He((e)=>e.toUpperCase())}function Lo(){return He((e)=>wa(e))}function Td(e,t,r){return new e({type:"array",element:t,...C(r)})}function Ad(e,t,r){return new e({type:"custom",check:"custom",fn:t,...C(r)})}function $d(e,t){let r=ng((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Qe(o,n.value,r._zod.def));else{let s=o;if(s.fatal)s.continue=!1;if(s.code??(s.code="custom"),!("input"in s))s.input=n.value;s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(Qe(s))}},e(n.value,n)),t);return r}function ng(e,t){let r=new V({check:"custom",...C(t)});return r._zod.check=e,r}function Kt(e,...t){for(let r of t)for(let n of Reflect.ownKeys(r))if(Object.prototype.propertyIsEnumerable.call(r,n))fe(e,n,r[n]);return e}function Zo(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??et,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 $e(e,t,r,n,o){let s=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:n.path,message:o}):t.unrepresentable;if(s==="any")return!1;if(s===void 0||s==="throw")throw Error(o);return Object.assign(r,s),!0}function j(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,r.schemaPath.includes(e))s.cycle=r.path;return s.schema}let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let u={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,u);else{let p=i.schema,f=t.processors[o.type];if(!f)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);f(e,t,p,u)}let l=e._zod.parent;if(l){if(!i.ref)i.ref=l;j(l,t,u),t.seen.get(l).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)Kt(i.schema,c);if(t.io==="input"&&ee(e))delete i.schema.examples,delete i.schema.default;if(t.io==="input"&&"_prefault"in i.schema)(n=i.schema).default??(n.default=i.schema._prefault);return delete i.schema._prefault,t.seen.get(e).schema}function Pd(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function jo(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let n=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let o=(i)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let l=e.external.registry.get(i[0])?.id,p=e.external.uri??((m)=>m);if(l)return{ref:p(l)};let f=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${Pd(f)}`}}let c="#",d=`${c}/${a}/`;if(i[1]===r&&!i[1].schema.id)return{ref:c};let u=i[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:d+Pd(u)}},s=(i)=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:d}=o(i);if(a.def={...a.schema},d)a.defId=d;let u=a.schema;for(let l in u)delete u[l];u.$ref=c};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
62
62
|
|
|
63
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let d=e.external.registry.get(i[0])?.id;if(t!==i[0]&&d){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1){if(e.reused==="ref")s(i)}}if(e.external)e.sharedDefsExtractedFor=e.external}function Md(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let n of t){if(!n||typeof n!=="object")return;Md(n);let o=Object.keys(n);if(o.length!==1||o[0]!=="type")return;let s=n.type;for(let i of Array.isArray(s)?s:[s]){if(typeof i!=="string")return;if(!r.includes(i))r.push(i)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var Dd=new Set(["type","properties","required","additionalProperties"]),Nd=["oneOf","anyOf"];function zd(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 Uo(e){let t=[];for(let s of e){if(typeof s!=="object"||s.type!=="object")return null;for(let i in s)if(!Dd.has(i))return null;t.push(s)}let r={},n=new Set;for(let s of t){for(let i in s.properties){if(Object.prototype.hasOwnProperty.call(r,i))continue;let a=[];for(let d of t){let u=d.properties?.[i]??zd(d);if(u===null||u===void 0)continue;if(!a.some((l)=>JSON.stringify(l)===JSON.stringify(u)))a.push(u)}let c=a.length===1?a[0]:Uo(a)??{allOf:a};fe(r,i,c)}for(let i of s.required??[])n.add(i)}let o={type:"object",properties:r};if(n.size)o.required=[...n];if(t.every((s)=>s.additionalProperties===!1))o.additionalProperties=!1;else{let s=[];for(let i of t){let a=zd(i);if(a&&!s.some((c)=>JSON.stringify(c)===JSON.stringify(a)))s.push(a)}if(s.length===1)o.additionalProperties=s[0];else if(s.length>1)o.additionalProperties={allOf:s}}return o}function og(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of Dd)if(o in e)return;let r=t.filter((o)=>Nd.some((s)=>Array.isArray(o[s]))),n=null;if(!r.length)n=Uo(t);else{let o=r[0],s=Nd.find((c)=>Array.isArray(o[c]));if(Object.keys(o).length!==1)return;let i=t.filter((c)=>c!==o),a=o[s].map((c)=>Uo([...i,c]));if(a.some((c)=>!c))return;n={[s]:a}}if(!n)return;delete e.allOf,Kt(e,n)}function Fo(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let d=c.def??c.schema,u={...d},l=c.ref;if(c.ref=null,l){n(l);let f=e.seen.get(l),m=f.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))d.allOf=d.allOf??[],d.allOf.push(m);else Kt(d,m);if(Kt(d,u),a._zod.parent===l)for(let g in d){if(g==="$ref"||g==="allOf")continue;if(!(g in u))delete d[g]}if(m.$ref&&f.def)for(let g in d){if(g==="$ref"||g==="allOf")continue;if(g in f.def&&JSON.stringify(d[g])===JSON.stringify(f.def[g]))delete d[g]}}let p=a._zod.parent;if(p&&p!==l){n(p);let f=e.seen.get(p);if(f?.schema.$ref){if(d.$ref=f.schema.$ref,f.def)for(let m in d){if(m==="$ref"||m==="allOf")continue;if(m in f.def&&JSON.stringify(d[m])===JSON.stringify(f.def[m]))delete d[m]}}}e.override({zodSchema:a,jsonSchema:d,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())n(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())Md(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let d of[c.schema,c.def]){let u=d?.allOf;if(!Array.isArray(u))continue;let l=a.get(u);if(l)l.push(d);else a.set(u,[d])}for(let c of e.intersections)for(let d of a.get(c)??[])og(d)}}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 a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Kt(o,r.defId?r.schema:r.def??r.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 a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;fe(i,c.defId,c.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 a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Vt(t,"input",e.processors),output:Vt(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function ee(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return ee(n.element,r);if(n.type==="set")return ee(n.valueType,r);if(n.type==="lazy")return ee(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault"||n.type==="catch")return ee(n.innerType,r);if(n.type==="intersection")return ee(n.left,r)||ee(n.right,r);if(n.type==="record"||n.type==="map")return ee(n.keyType,r)||ee(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return ee(n.in,r)||ee(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(ee(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(ee(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(ee(o,r))return!0;if(n.rest&&ee(n.rest,r))return!0;return!1}return!1}var Ld=(e,t={})=>(r)=>{let n=Zo({...r,processors:t});return j(e,n),jo(n,e),Fo(n,e)},Vt=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:s}=n??{},i=Zo({...o??{},target:s,io:t,processors:r});return j(e,i),jo(i,e),Fo(i,e)};var yt=(e,t,r)=>{if(e[t]===void 0||r>e[t])e[t]=r},_t=(e,t,r)=>{if(e[t]===void 0||r<e[t])e[t]=r},Ud=(e,t)=>{yt(e,"minimum",t),_t(e,"maximum",t)},Hd=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},Bd=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},qd=(e,t)=>{e.mime=e.mime?e.mime.filter((r)=>t.includes(r)):[...t]},Gd=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},Zd=(e,t)=>yt(e,"minimum",t.minimum),jd=(e,t)=>_t(e,"maximum",t.maximum),Fd=(e)=>(t,r)=>{Gd(t,r.format);let[n,o]=e[r.format];yt(t,"minimum",n),_t(t,"maximum",o)},sg={greater_than:(e,t)=>yt(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>_t(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Hd(e,t.value),number_format:Fd(Tr),bigint_format:Fd(oo),min_length:Zd,max_length:jd,length_equals:(e,t)=>Ud(e,t.length),min_size:Zd,max_size:jd,size_equals:(e,t)=>Ud(e,t.size),string_format:(e,t)=>{if(Gd(e,t.format),t.pattern)Bd(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)=>qd(e,t.mime)};function ue(e){let t={},r=e._zod.def,n=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let s of n)sg[s._zod.def.check]?.(t,s._zod.def);let o=e._zod.bag;if(o.minimum!==void 0)yt(t,"minimum",o.minimum);if(o.exclusiveMinimum!==void 0)yt(t,"exclusiveMinimum",o.exclusiveMinimum);if(o.maximum!==void 0)_t(t,"maximum",o.maximum);if(o.exclusiveMaximum!==void 0)_t(t,"exclusiveMaximum",o.exclusiveMaximum);if(o.multipleOf!==void 0)Hd(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)qd(t,o.mime);for(let s of o.patterns??[])Bd(t,s);return t}var ig={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ag=new Map([[vo,ac],[Gr,cc]]),Kd=(e)=>ag.get(e)??e,Vd=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:d,laxFormat:u}=ue(e);if(typeof s==="number")o.minLength=s;if(typeof i==="number")o.maxLength=i;if(a){if(o.format=ig[a]??a,o.format==="")delete o.format;if(a==="time"||u)delete o.format}if(d)o.contentEncoding=d;if(c&&c.size>0){let l=[...c].map(Kd);if(l.length===1)o.pattern=l[0].source;else if(l.length>1)o.allOf=[...l.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},Wd=(e,t,r,n)=>{let o=r,{minimum:s,maximum:i,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:d,isInt:u}=ue(e);o.type=u?"integer":"number";let l=typeof d==="number"&&d>=(s??Number.NEGATIVE_INFINITY),p=typeof c==="number"&&c<=(i??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(l)if(f)o.minimum=d,o.exclusiveMinimum=!0;else o.exclusiveMinimum=d;else if(typeof s==="number")o.minimum=s;if(p)if(f)o.maximum=c,o.exclusiveMaximum=!0;else o.exclusiveMaximum=c;else if(typeof i==="number")o.maximum=i;if(a){let m=new Set;for(let w of a)if(Number.isFinite(w)&&w!==0)m.add(Math.abs(w));else $e(e,t,o,n,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);let[y,...g]=m;if(y!==void 0)o.multipleOf=y;if(g.length)o.allOf=[...o.allOf??[],...g.map((w)=>({multipleOf:w}))]}},Jd=(e,t,r,n)=>{r.type="boolean"};var Yd=(e,t,r,n)=>{r.not={}};var Xd=(e,t,r,n)=>{};var Qd=(e,t,r,n)=>{let o=e._zod.def,s=zt(o.entries);if(s.length===0){r.not={};return}if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";r.enum=s},el=(e,t,r,n)=>{let o=e._zod.def;if(o.values.length===0){r.not={};return}let s=[];for(let i of o.values)if(i===void 0){if($e(e,t,r,n,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i==="bigint"){if($e(e,t,r,n,"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(r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[i];else r.const=i}else{if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";if(s.every((i)=>typeof i==="boolean"))r.type="boolean";if(s.every((i)=>i===null))r.type="null";r.enum=s}};var tl=(e,t,r,n)=>{$e(e,t,r,n,"Custom types cannot be represented in JSON Schema")};var rl=(e,t,r,n)=>{$e(e,t,r,n,"Transforms cannot be represented in JSON Schema")};var nl=(e,t,r,n)=>{let o=r,s=e._zod.def,{minimum:i,maximum:a}=ue(e);if(typeof i==="number")o.minItems=i;if(typeof a==="number")o.maxItems=a;o.type="array",o.items=j(s.element,t,{...n,path:[...n.path,"items"]})};function Wt(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return Wt(t.out);if(t.type==="catch")return Wt(t.innerType);return e._zod.optin}var ol=(e,t,r,n)=>{let o=r,s=e._zod.def,i=s.shape;if(Object.getOwnPropertySymbols(i).length&&$e(e,t,o,n,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(let d in i)fe(o.properties,d,j(i[d],t,{...n,path:[...n.path,"properties",d]}));let c=[];for(let d of Object.keys(i)){let u=s.shape[d];if(t.io==="input"?Wt(u)===void 0:u._zod.optout===void 0)c.push(d)}if(c.length>0)o.required=c;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=j(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})},sl=(e,t,r,n)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>j(a,t,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));if(s)r.oneOf=i;else r.anyOf=i},il=(e,t,r,n)=>{let o=e._zod.def,s=j(o.left,t,{...n,path:[...n.path,"allOf",0]}),i=j(o.right,t,{...n,path:[...n.path,"allOf",1]}),a=(d)=>("allOf"in d)&&Object.keys(d).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c,t.intersections.push(c)},al=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",c=s.items.map((y,g)=>j(y,t,{...n,path:[...n.path,i,g]})),d=s.rest?j(s.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null,u=s.items.length;while(u>0){let y=s.items[u-1];if(!(t.io==="input"?Wt(y)!==void 0:y._zod.optout==="optional"))break;u--}let l=s.items.length,p=!s.rest;if(t.target==="draft-2020-12"){if(o.prefixItems=c,p)o.items=!1;else if(d)o.items=d;if(u>0)o.minItems=u;if(p)o.maxItems=l}else if(t.target==="openapi-3.0"){if(o.items={anyOf:c},d)o.items.anyOf.push(d);if(u>0)o.minItems=u;if(p)o.maxItems=l}else{if(o.items=c,p)o.additionalItems=!1;else if(d)o.additionalItems=d;if(u>0)o.minItems=u;if(p)o.maxItems=l}let{minimum:f,maximum:m}=ue(e);if(typeof f==="number")o.minItems=f;if(typeof m==="number")o.maxItems=m};function Ho(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let m=e.get(t)?.def;if(!m)return t;let y=Ho(e,m,r);return y===m?t:y}for(let m of["anyOf","oneOf"]){let y=t[m];if(!Array.isArray(y))continue;let g=y.map((w)=>Ho(e,w,r));if(g.some((w,b)=>w!==y[b]))t={...t,[m]:g}}let n=Array.isArray(t.type)?t.type:[t.type],o=!n.includes("string")&&n.some((m)=>m==="number"||m==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!s?.some((m)=>typeof m==="number"))return t;let{minimum:i,maximum:a,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:u,format:l,id:p,...f}=t;if(f.enum)f.enum=f.enum.map((m)=>typeof m==="number"?String(m):m);else if(typeof f.const==="number")f.const=String(f.const);if(!o)return f;if(f.type="string",!s)f.pattern=(n.includes("number")?Zt:po).source;return f}var Bo=new WeakMap;function cg(e){let t=new Map;for(let n of e.seen.values())if(n.def&&!t.has(n.schema))t.set(n.schema,n);let r=new Map;for(let n of Bo.get(e)??[]){let o=e.seen.get(n),s=(o?.def??o?.schema)?.propertyNames;if(!s||s===!0||r.has(s))continue;let i=Ho(t,s,new Set);if(i!==s)r.set(s,i)}if(!r.size)return;for(let n of e.seen.values())for(let o of[n.schema,n.def]){let s=o&&r.get(o.propertyNames);if(s)o.propertyNames=s}}var cl=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object";let i=s.keyType,a=ue(i).patterns;if(s.mode==="loose"&&a&&a.size>0){let u=j(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let l of a)fe(o.patternProperties,Kd(l).source,u)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=j(s.keyType,t,{...n,path:[...n.path,"propertyNames"]});let u=Bo.get(t);if(!u)u=[],Bo.set(t,u),t.deferred.push(()=>cg(t));u.push(e)}o.additionalProperties=j(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let c=i._zod.values,d=t.io==="input"&&Wt(s.valueType)!==void 0;if(c&&!s.partial&&!d){let u=[...c].filter((l)=>typeof l==="string"||typeof l==="number");if(u.length>0)o.required=u.map(String)}},ul=(e,t,r,n)=>{let o=e._zod.def,s=j(o.innerType,t,n),i=t.seen.get(e);if(t.target==="openapi-3.0")i.ref=o.innerType,r.nullable=!0;else r.anyOf=[s,{type:"null"}]},dl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},qo=Symbol();function ll(e,t,r,n,o){let s=!1,i=JSON.stringify(e,(a,c)=>{if(typeof c!=="bigint")return c;return s=!0,null});if(!s)return JSON.parse(i);return $e(t,r,n,o,"BigInt defaults cannot be represented in JSON Schema"),qo}var fl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i=ll(o.defaultValue,e,t,r,n);if(i!==qo)r.default=i},hl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);if(s.ref=o.innerType,t.io!=="input")return;let i=ll(o.defaultValue,e,t,r,n);if(i!==qo)r._prefault=i},pl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{$e(e,t,r,n,"Dynamic catch values are not supported in JSON Schema");return}r.default=i},ml=(e,t,r,n)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;j(i,t,n);let a=t.seen.get(e);a.ref=i},gl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0};var Go=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType};var yl=new WeakSet([Object.prototype,Error.prototype]);function rn(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let n=r(this);return Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0})}})}var gg=(e,t)=>{Na.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);if(yl.has(r))return;yl.add(r),rn(r,"format",(n)=>(o)=>Ma(n,o)),rn(r,"flatten",(n)=>(o)=>za(n,o)),rn(r,"addIssue",(n)=>(o)=>{n.issues.push(o),n.message=JSON.stringify(n.issues,Mt,2)}),rn(r,"addIssues",(n)=>(o)=>{n.issues.push(...o),n.message=JSON.stringify(n.issues,Mt,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})};var de=_("ZodError",gg,void 0,{Parent:Error});var _l=Dr(de),wl=Lr(de),Sl=Ur(de),vl=Zr(de),xl=La(de),bl=Ua(de),El=Za(de),Il=ja(de),kl=Fa(de),Cl=Ha(de),Rl=Ba(de),Ol=qa(de);function _g(){if(!Q.localeError)ce(Co())}function Jt(){if(!Q.memoizer)ce({memoizer:Vu()})}var U=_("ZodType",(e,t)=>(_g(),z.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(ae(t,{checks:[...t.checks??[],...e.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Se(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(my(e,t))},superRefine(e,t){return this.check(gy(e,t))},overwrite(e){return this.check(He(e))},optional(){return $l(this)},exactOptional(){return ry(this)},nullable(){return Pl(this)},nullish(){return $l(Pl(this))},nonoptional(e){return cy(this,e)},array(){return K(this)},or(e){return on([this,e])},and(e){return Yg(this,e)},transform(e){return Nl(this,ty(e))},default(e){return sy(this,e)},prefault(e){return ay(this,e)},catch(e){return dy(this,e)},pipe(e){return Nl(this,e)},readonly(){return hy(this)},describe(e){let t=this.clone();return et.add(t,{description:e}),t},meta(...e){if(e.length===0)return et.get(this);let t=this.clone();return et.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 zr(this,"~standard",{...So(this),jsonSchema:{input:Vt(this,"input"),output:Vt(this,"output")}})},set "~standard"(e){Ae(this,"~standard",e)},parse:function e(t,r){return _l(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await wl(this,t,r,{callee:e})},safeParse(e,t){return Sl(this,e,t)},async safeParseAsync(e,t){return vl(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Ae(this,"spa",e)},validate(e,t){return uo(this,e,t)},validateAsync(e,t){return lo(this,e,t)},encode:function e(t,r){return xl(this,t,r,{callee:e})},decode:function e(t,r){return bl(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await El(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await Il(this,t,r,{callee:e})},safeEncode(e,t){return kl(this,e,t)},safeDecode(e,t){return Cl(this,e,t)},async safeEncodeAsync(e,t){return Rl(this,e,t)},async safeDecodeAsync(e,t){return Ol(this,e,t)},toJSONSchema(e){return Ld(this,{})(e)},get description(){return et.get(this)?.description},get _def(){return this._zod.def}}),zl=_("_ZodString",(e,t)=>{qr.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Vd(e,r,n,o)},Ra({format:(e)=>ue(e).format??null,minLength:(e)=>ue(e).minimum??null,maxLength:(e)=>ue(e).maximum??null},{regex(...e){return this.check(Ro(...e))},includes(...e){return this.check(Ao(...e))},startsWith(...e){return this.check($o(...e))},endsWith(...e){return this.check(Po(...e))},min(...e){return this.check(gt(...e))},max(...e){return this.check(en(...e))},length(...e){return this.check(tn(...e))},nonempty(...e){return this.check(gt(1,...e))},lowercase(e){return this.check(Oo(e))},uppercase(e){return this.check(To(e))},trim(){return this.check(zo())},normalize(...e){return this.check(No(...e))},toLowerCase(){return this.check(Mo())},toUpperCase(){return this.check(Do())},slugify(){return this.check(Lo())}})),wg=_("ZodString",(e,t)=>{qr.init(e,t),zl.init(e,t)},{email(e){return this.check(Qu(Eg,e))},url(e){return this.check(sd(kg,e))},jwt(e){return this.check(Sd(jg,e))},emoji(e){return this.check(id(Cg,e))},guid(e){return this.check(ed(Ig,e))},uuid(e){return this.check(td(nn,e))},uuidv4(e){return this.check(rd(nn,e))},uuidv6(e){return this.check(nd(nn,e))},uuidv7(e){return this.check(od(nn,e))},nanoid(e){return this.check(ad(Rg,e))},cuid(e){return this.check(cd(Og,e))},cuid2(e){return this.check(ud(Tg,e))},ulid(e){return this.check(dd(Ag,e))},base64(e){return this.check(yd(Lg,e))},base64url(e){return this.check(_d(Ug,e))},xid(e){return this.check(ld($g,e))},ksuid(e){return this.check(fd(Pg,e))},ipv4(e){return this.check(hd(Ng,e))},ipv6(e){return this.check(pd(zg,e))},cidrv4(e){return this.check(md(Mg,e))},cidrv6(e){return this.check(gd(Dg,e))},e164(e){return this.check(wd(Zg,e))},datetime(e){return this.check(vd(Sg,e))},date(e){return this.check(xd(vg,e))},time(e){return this.check(bd(xg,e))},duration(e){return this.check(Ed(bg,e))}});function S(e){return Xu(wg,e)}var F=_("ZodStringFormat",(e,t)=>{D.init(e,t),zl.init(e,t)}),Sg=_("ZodISODateTime",(e,t)=>{iu.init(e,t),F.init(e,t)}),vg=_("ZodISODate",(e,t)=>{au.init(e,t),F.init(e,t)}),xg=_("ZodISOTime",(e,t)=>{cu.init(e,t),F.init(e,t)}),bg=_("ZodISODuration",(e,t)=>{uu.init(e,t),F.init(e,t)}),Eg=_("ZodEmail",(e,t)=>{Wc.init(e,t),F.init(e,t)});var Ig=_("ZodGUID",(e,t)=>{Kc.init(e,t),F.init(e,t)});var nn=_("ZodUUID",(e,t)=>{Vc.init(e,t),F.init(e,t)});var kg=_("ZodURL",(e,t)=>{Xc.init(e,t),F.init(e,t)});var Cg=_("ZodEmoji",(e,t)=>{Qc.init(e,t),F.init(e,t)});var Rg=_("ZodNanoID",(e,t)=>{eu.init(e,t),F.init(e,t)});var Og=_("ZodCUID",(e,t)=>{tu.init(e,t),F.init(e,t)});var Tg=_("ZodCUID2",(e,t)=>{ru.init(e,t),F.init(e,t)});var Ag=_("ZodULID",(e,t)=>{nu.init(e,t),F.init(e,t)});var $g=_("ZodXID",(e,t)=>{ou.init(e,t),F.init(e,t)});var Pg=_("ZodKSUID",(e,t)=>{su.init(e,t),F.init(e,t)});var Ng=_("ZodIPv4",(e,t)=>{du.init(e,t),F.init(e,t)});var zg=_("ZodIPv6",(e,t)=>{fu.init(e,t),F.init(e,t)});var Mg=_("ZodCIDRv4",(e,t)=>{hu.init(e,t),F.init(e,t)});var Dg=_("ZodCIDRv6",(e,t)=>{pu.init(e,t),F.init(e,t)});var Lg=_("ZodBase64",(e,t)=>{gu.init(e,t),F.init(e,t)});var Ug=_("ZodBase64URL",(e,t)=>{yu.init(e,t),F.init(e,t)});var Zg=_("ZodE164",(e,t)=>{_u.init(e,t),F.init(e,t)});var jg=_("ZodJWT",(e,t)=>{wu.init(e,t),F.init(e,t)});var Ml=_("ZodNumber",(e,t)=>{xo.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Wd(e,r,n,o),e.isFinite=!0},Ra({minValue:(e)=>{let{minimum:t,exclusiveMinimum:r}=ue(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:r}=ue(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:r}=ue(e);return!!t||!!r?.some(Number.isSafeInteger)},format:(e)=>ue(e).format??null},{gt(e,t){return this.check(Xr(e,t))},gte(e,t){return this.check(Gt(e,t))},min(e,t){return this.check(Gt(e,t))},lt(e,t){return this.check(Yr(e,t))},lte(e,t){return this.check(qt(e,t))},max(e,t){return this.check(qt(e,t))},int(e){return this.check(Tl(e))},safe(e){return this.check(Tl(e))},positive(e){return this.check(Xr(0,e))},nonnegative(e){return this.check(Gt(0,e))},negative(e){return this.check(Yr(0,e))},nonpositive(e){return this.check(qt(0,e))},multipleOf(e,t){return this.check(Qr(e,t))},step(e,t){return this.check(Qr(e,t))},finite(){return this}}));function Pe(e){return Id(Ml,e)}var Fg=_("ZodNumberFormat",(e,t)=>{Su.init(e,t),Ml.init(e,t)});function Tl(e){return kd(Fg,e)}var Hg=_("ZodBoolean",(e,t)=>{vu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Jd(e,r,n,o)});function Yt(e){return Cd(Hg,e)}var Bg=_("ZodUnknown",(e,t)=>{xu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Xd(e,r,n,o)});function Ee(){return Rd(Bg)}var qg=_("ZodNever",(e,t)=>{bu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Yd(e,r,n,o)});function Gg(e){return Od(qg,e)}var Kg=_("ZodArray",(e,t)=>{Jt(),Eu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>nl(e,r,n,o),e.element=t.element},{min(e,t){return this.check(gt(e,t))},nonempty(e){return this.check(gt(1,e))},max(e,t){return this.check(en(e,t))},length(e,t){return this.check(tn(e,t))},unwrap(){return this.element}});function K(e,t){return Td(Kg,e,t)}var Vg=_("ZodObject",(e,t)=>{Jt(),Cu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ol(e,r,n,o),Em(e,"shape",(r)=>r._zod.def.shape,!1)},{keyof(){return ne(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(ae(this._zod.def,{catchall:e}))},passthrough(){return this.clone(ae(this._zod.def,{catchall:Ee()}))},loose(){return this.clone(ae(this._zod.def,{catchall:Ee()}))},strict(){return this.clone(ae(this._zod.def,{catchall:Gg()}))},strip(){return this.clone(ae(this._zod.def,{catchall:void 0}))},extend(e){return gm(this,e)},safeExtend(e){return ym(this,e)},merge(e){return _m(this,e)},pick(e){return pm(this,e)},omit(e){return mm(this,e)},partial(...e){return Ea(Wo,this,e[0])},exactPartial(...e){return Ea(Zl,this,e[0],"exactPartial")},required(...e){return wm(jl,this,e[0])}});function k(e,t){let r={type:"object",shape:e??{},...C(t)};return new Vg(r)}var Dl=_("ZodUnion",(e,t)=>{bo.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>sl(e,r,n,o),e.options=t.options});function on(e,t){return new Dl({type:"union",options:e,...C(t)})}var Wg=_("ZodDiscriminatedUnion",(e,t)=>{Dl.init(e,t),Ru.init(e,t)});function Ll(e,t,r){return new Wg({type:"union",options:t,discriminator:e,...C(r)})}var Jg=_("ZodIntersection",(e,t)=>{Ou.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>il(e,r,n,o)});function Yg(e,t){return new Jg({type:"intersection",left:e,right:t})}var Xg=_("ZodTuple",(e,t)=>{Jt(),Tu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>al(e,r,n,o)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map((t)=>new Wo({type:"optional",innerType:t}))})}});function Be(e,t,r){let n=t instanceof z,o=n?r:t;return new Xg({type:"tuple",items:e,rest:n?t:null,...C(o)})}var Al=_("ZodRecord",(e,t)=>{Jt(),Au.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cl(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function Ul(e,t,r){if(!t||!t._zod)return new Al({type:"record",keyType:S(),valueType:e,...C(t)});return new Al({type:"record",keyType:e,valueType:t,...C(r)})}var Vo=_("ZodEnum",(e,t)=>{$u.init(e,t),U.init(e,t),e._zod.processJSONSchema=(n,o,s)=>Qd(e,n,o,s),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=t.entries[i];else throw Error(`Key ${i} not found in enum`);return new Vo({...t,checks:[],...C(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let i of n)if(r.has(i))delete s[i];else throw Error(`Key ${i} not found in enum`);return new Vo({...t,checks:[],...C(o),entries:s})}});function ne(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new Vo({type:"enum",entries:r,...C(t)})}var Qg=_("ZodLiteral",(e,t)=>{Pu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>el(e,r,n,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 H(e,t){return new Qg({type:"literal",values:Array.isArray(e)?e:[e],...C(t)})}var ey=_("ZodTransform",(e,t)=>{Jt(),Nu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rl(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Ut(e.constructor.name);r.addIssue=(s)=>{if(typeof s==="string")r.issues.push(Qe(s,r.value,t));else{let i=s;if(i.fatal)i.continue=!1;if(i.code??(i.code="custom"),!("input"in i))i.input=r.value;i.inst??(i.inst=e),r.issues.push(Qe(i))}};let o=t.transform(r.value,r);if(o instanceof Promise)return o.then((s)=>(r.value=s,r));return r.value=o,r}});function ty(e){return new ey({type:"transform",transform:e})}var Wo=_("ZodOptional",(e,t)=>{Eo.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Go(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function $l(e){return new Wo({type:"optional",innerType:e})}var Zl=_("ZodExactOptional",(e,t)=>{zu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Go(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ry(e){return new Zl({type:"optional",innerType:e})}var ny=_("ZodNullable",(e,t)=>{Mu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ul(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Pl(e){return new ny({type:"nullable",innerType:e})}var oy=_("ZodDefault",(e,t)=>{Du.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>fl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function sy(e,t){return new oy({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():ro(t)}})}var iy=_("ZodPrefault",(e,t)=>{Lu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>hl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ay(e,t){return new iy({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():ro(t)}})}var jl=_("ZodNonOptional",(e,t)=>{Uu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>dl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function cy(e,t){return new jl({type:"nonoptional",innerType:e,...C(t)})}var uy=_("ZodCatch",(e,t)=>{Zu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>pl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function dy(e,t){return new uy({type:"catch",innerType:e,catchValue:typeof t==="function"?t:Oa(t)})}var ly=_("ZodPipe",(e,t)=>{ju.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ml(e,r,n,o),e.in=t.in,e.out=t.out});function Nl(e,t){return new ly({type:"pipe",in:e,out:t})}var fy=_("ZodReadonly",(e,t)=>{Fu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>gl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function hy(e){return new fy({type:"readonly",innerType:e})}var py=_("ZodCustom",(e,t)=>{Hu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>tl(e,r,n,o)});function my(e,t={}){return Ad(py,e,t)}function gy(e,t){return $d(e,t)}var Yo=["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"],cn=524288,ot=262144,yy=1000;function te(e){return new TextEncoder().encode(JSON.stringify(e)).length}var W=S().min(1).max(256),nt=S().min(1).max(1024),_y=S().regex(/^(0|[1-9][0-9]{0,17})$/u),un=k({epoch:W,ordinal:_y}).strict(),rt={workspaceId:W,sourceId:W,hostId:W},wt=k({address:nt,version:W,scope:W,columns:k({title:S().max(4096),state:W,owner:W.nullable(),parent:nt.nullable(),project:nt.nullable(),labels:K(W).max(256),url:S().max(2048).nullable(),updatedAt:S().max(64).nullable()}).strict(),extra:Ee()}).strict(),Xo=k({position:un,change:Ll("op",[k({op:H("upsert"),row:wt}).strict(),k({op:H("delete"),address:nt}).strict()])}).strict(),wy=k({address:nt}).strict(),Sy=k({page:S().min(1).max(4096).optional(),limit:Pe().int().min(1).max(yy)}).strict(),vy=k({address:nt,ownerMemberId:W,expectedOwner:W.nullable(),intentId:W,ifRevision:S().min(1).max(256).optional()}).strict(),xy=k({on:Yt()}).strict(),by=k({memberId:W}).strict(),sn=(e,t)=>k({...rt,caller:by,op:H(e),args:t}).strict(),Hl=Ll("op",[sn("read",wy),sn("list",Sy),sn("assign",vy),sn("watch",xy)]),Ey=k({generation:W,snapshot:W,base:un,rows:K(wt),next:S().min(1).max(4096).nullable(),complete:Yt(),progressAsOf:S().min(1).max(64).optional(),progressStale:k({since:S().min(1).max(64),reason:S().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"}),Iy=k({intentId:W,result:Ee(),observation:Xo,revision:W.nullable().optional()}).strict(),Jo={read:k({observation:Xo}).strict(),list:Ey,assign:Iy,watch:k({on:Yt()}).strict()},Fl=ne(Yo),ky=["OPERATION_NOT_ALLOWLISTED","OPERATION_SHAPE_INVALID"],an=(e)=>on([k({...rt,op:H(e),outcome:ne(["applied","noop"]),body:Jo[e]}).strict(),k({...rt,op:H(e),outcome:ne(["applied","noop"]),code:H("SOURCE_READER_RESTARTING"),body:Jo[e]}).strict(),k({...rt,op:H(e),outcome:H("rejected"),code:Fl,body:Jo[e]}).strict(),k({...rt,op:H(e),outcome:ne(["unknown","refused"]),code:on([Fl.exclude(["ITEM_TOO_LARGE"]),ne(ky)])}).strict(),k({...rt,op:H(e),outcome:H("refused"),code:H("ITEM_TOO_LARGE"),item:nt}).strict()]),Bl=on([an("read"),an("list"),an("assign"),an("watch")]),iI=k({...rt,position:un,observations:K(Xo).min(1)}).strict().refine((e)=>{let{observations:t,position:r}=e,n=t[t.length-1];if(n===void 0||n.position.epoch!==r.epoch||n.position.ordinal!==r.ordinal)return!1;return t.every((o,s)=>o.position.epoch===r.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"}),ql=k({applied:un.nullable(),seq:Pe().int().min(0),relist:Yt()}).strict();var qe="x-hh-records";var Cy=`${qe}/changed`,Ie="assign",dn="records:assign",Gl=k({address:S().min(1).max(1024),ownerMemberId:S().min(1).max(256),expectedOwner:S().min(1).max(256).nullable().optional(),ifRevision:S().min(1).max(256),intentId:S().min(1).max(256)}).strict(),Kl=S().min(1).max(256),Vl=S().min(1).max(1024),Wl=k({address:Vl,revision:S().min(1).max(256),scope:S().min(1).max(256),columns:Ul(S(),Ee()),extra:Ee().optional()}).strict(),uI=k({source:Kl,epoch:S().min(1).max(256),records:K(Wl)}).strict(),Ry=k({type:H(Cy),source:Kl,revision:S().min(1).max(256),address:Vl,deleted:H(!0).optional(),record:Wl.optional()}).strict(),dI=k({channel:S().min(1),serverSeq:Pe().int().min(0).optional(),action:Ry}),Oy=new RegExp(`^${qe}://[^/?#]+$`,"u"),Jl=(e)=>e===`${qe}://`||Oy.test(e);var Ty=k({id:S().min(1),revision:Pe().int().min(0),state:S(),operations:K(S())}).passthrough();var Qo=Pe().int().min(0),hI=k({id:S().min(1),engine:S().min(1),owner:S().min(1),name:S().min(1),description:S().optional(),tags:K(S()).optional(),model:Ee().optional(),config:Ul(S(),Ee()),ifRevision:Qo}).passthrough(),pI=k({id:S().min(1),ifRevision:Qo}).strict(),mI=k({id:S().min(1),ifRevision:Qo}).strict(),Yl=-32602,gI=k({code:H(Yl),message:S(),data:k({staleRevision:Pe().int().min(1),row:Ty})}),yI=k({code:H(Yl),message:S(),data:k({staleRevision:H(0)})});var es=["subscribe","x-ahpd/invokeOperation","resourceRead","listSessions","authenticate"],Ge="x-hh-services://",Ay=`${Ge} and ${qe}://<sourceId>`,Xl=["put","remove","start","stop","restart","accept"];var $y="hh-services://backup",Py="hh-services://changes",Ny=/^(hh-service:\/\/[^/?#]+\/logs|hh-services:\/\/(backup|changes))(\?[^#]*)?$/u;function Ql(e,t){let r=(n)=>typeof t[n]==="string"?JSON.stringify(t[n]):`no ${n}`;switch(e){case"subscribe":{let n=t.channel;if(Object.keys(t).length===1&&typeof n==="string"&&(n===Ge||Jl(n)))return;return`subscribe to ${r("channel")}${Object.keys(t).length>1?" with more than a channel":""} is not one Hightea sends; only ${Ay}`}case"x-ahpd/invokeOperation":{if(t.channel===Ge){if(typeof t.operationId==="string"&&Xl.includes(t.operationId))return;return`x-ahpd/invokeOperation ${r("operationId")} on ${Ge} is not one Hightea sends; only ${Xl.join(", ")}`}if(t.channel===`${qe}://`){if(t.operationId===Ie)return;return`x-ahpd/invokeOperation ${r("operationId")} on ${qe}:// is not one Hightea sends; only ${Ie} (${dn})`}return`x-ahpd/invokeOperation on ${r("channel")} is not one Hightea sends; only ${Ge} and ${qe}://`}case"resourceRead":if(typeof t.uri==="string"&&Ny.test(t.uri))return;return`resourceRead of ${r("uri")} is not one Hightea sends; only hh-service://<name>/logs, ${$y} and ${Py}`;case"listSessions":if(t.channel==="ahp-root://"&&Object.keys(t).length===1)return;return`listSessions on ${r("channel")}${Object.keys(t).length>1?" with more than a channel":""} is not one Hightea sends; only ahp-root://`;case"authenticate":{let n=Object.keys(t).sort().join(",");if(n!=="resource,target,token"&&n!=="expiresIn,resource,target,token")return`authenticate naming ${JSON.stringify(n)} is not one Hightea sends; only target, resource, token and expiresIn`;if(typeof t.token!=="string")return"authenticate names no token";if(typeof t.resource!=="string"||t.resource==="")return`authenticate names ${r("resource")}`;let o=t.expiresIn;if(o!==void 0&&!(typeof o==="number"&&Number.isInteger(o)&&o>0))return"authenticate's expiresIn is not a positive integer of seconds";let s=t.target;if(typeof s!=="object"||s===null||Array.isArray(s))return"authenticate names no target";let i=s;if(Object.keys(i).sort().join(",")!=="customizationId,kind,session")return"authenticate's target carries more than kind, session and customizationId";if(i.kind!=="mcpServer")return`authenticate's target kind is ${JSON.stringify(i.kind)}; only mcpServer`;if(typeof i.session!=="string"||i.session==="")return"authenticate's target names no session";if(typeof i.customizationId!=="string"||i.customizationId==="")return"authenticate's target names no server";return}default:return`${JSON.stringify(e)} is not a host-scoped method; only ${es.join(", ")}`}}var ef=["x-ahpd/agents/list","x-ahpd/agents/put","x-ahpd/agents/remove","x-ahpd/agents/enable","x-ahpd/agents/pause","x-ahpd/agents/disable",...es];function Xt(e){return es.includes(e)}var zy=1e4,Qt=zy-1000,tf="host-request:",rf="1.1.0";var nf="signed-envelopes",of="meta-routing-ids@1",ln="host-frames-slim@1";var sf=k({workspaceId:S().min(1).optional(),hostId:S().min(1).optional(),agentMemberId:S().min(1).optional(),caller:S().min(1).max(256).optional()}).strict(),My=["unmapped","timedOut","outside"],vI=k({reason:ne(My)}).strict();function af(e){if(e.ok)return{result:e.result};if(e.reason==="refused")return{error:{code:e.code,message:e.message,...e.data===void 0?{}:{data:e.data}}};return{error:{code:-32000,message:e.reason,data:{reason:e.reason}}}}var Dy=k({resource:S().min(1),customizationId:S().min(1)}).strict(),er=k({available:Yt(),reason:S().min(1).max(200).optional(),server:Dy.optional()}).strict(),st="ahpd/hostTools",xI=k({resource:S().min(1),_meta:k({"hh/agentMemberId":S().min(1),"hh/hostTools":er.optional()}).strict()}).strict(),bI=k({channel:H("ahp-root://"),session:S().min(1),changes:k({_meta:k({"hh/agentMemberId":S().min(1),"hh/hostTools":er}).strict()}).strict()}).strict();function tr(e,t,r){let n=ye(e)?e:{},o=n["hh/agentMemberId"];if(o!==void 0&&o!==t)return;let s=er.safeParse(n[st]);if(!s.success)return{"hh/agentMemberId":t};let i=s.data.available&&r!==void 0;return{"hh/agentMemberId":t,"hh/hostTools":{available:s.data.available,...s.data.reason===void 0?{}:{reason:s.data.reason},...i?{server:r}:{}}}}function cf(e,t,r){if(!ye(e)||typeof e.resource!=="string"||e.resource==="")return;let n=tr(e._meta,t,r);return n===void 0?void 0:{resource:e.resource,_meta:n}}var EI=k({channel:S().min(1),resource:S().min(1),reason:H("expired")}).strict();function ye(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var ts="event:all",uf="tool:all";var Ly=["session/ready","chat/turnStarted","chat/turnComplete","x-hh/turnFailed"];var rr=["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",...Yo],df=16,lf=49152,ff=262144,Uy=k({id:S().min(1),from:k({memberId:S().min(1)}).strict(),text:S(),replyTo:S().min(1).optional(),deleted:H(!0).optional(),signed:k({keyId:S().min(1),createdAt:S().min(1),signature:S().min(1),clientId:S().min(1),attachmentIds:K(S().min(1))}).strict().optional()}).strict(),Zy=(e)=>new TextEncoder().encode(JSON.stringify(e)).byteLength,jy=K(Uy).min(1).superRefine((e,t)=>{if(e.length>df){t.addIssue({code:"custom",message:`a wake carries at most ${df} triggering envelopes, not ${e.length}`});return}if(new Set(e.map((n)=>n.id)).size!==e.length){t.addIssue({code:"custom",message:"a wake names each triggering message once"});return}let r=0;for(let n of e){let o=Zy(n);if(o>lf){t.addIssue({code:"custom",message:`triggering envelope ${n.id} is ${o} bytes, over the ${lf}-byte limit`});return}r+=o}if(r>ff)t.addIssue({code:"custom",message:`the triggering envelopes take ${r} bytes, over the ${ff}-byte limit`})}),hf=k({workspaceId:S().min(1),deliveryId:S().min(1),turnId:S().min(1).optional(),agentMemberId:S().min(1),threadRef:S().min(1),afterMessageId:S().min(1).optional(),triggeringMessageIds:K(S().min(1)).min(1).refine((e)=>new Set(e).size===e.length).optional(),triggering:jy.optional()}).strict(),fn=k({event:ne(Ly),channel:S().min(1),workspaceId:S().min(1),deliveryId:S().min(1),session:S().min(1),chat:S().min(1),turnId:S().min(1).optional(),clientSeq:Pe().int().min(1).optional(),turnState:ne(["created","running","finished","error"]),statusCode:S().min(1).max(64),errorCode:ne(rr).optional(),errorDetail:S().max(256).optional()}).strict();function pf(e){return fn.parse(e)}var Fy=["session/ready","chat/turnStarted","chat/turnComplete","chat/turnCancelled","chat/error"],OI=k({channel:S().min(1),serverSeq:Pe().int().min(0).optional(),origin:k({clientId:S().min(1),clientSeq:Pe().int().min(1)}).optional(),action:k({type:ne(Fy),turnId:S().min(1).optional(),part:k({error:k({errorType:S().min(1)})}).optional()})});var mf="Hightea-Host",gf="x-hightea-host";import{createHash as zf}from"node:crypto";var Hy=(e,t,r)=>JSON.stringify([e,t,r]),or=/^ahp-session:\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u,By=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u,M=(e)=>({ok:!1,code:e});function nr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function it(e,t,r=[]){let n=new Set([...t,...r]);return t.every((o)=>(o in e))&&Object.keys(e).every((o)=>n.has(o))}function qy(e){let t=hf.safeParse(e._meta);return t.success?t.data:void 0}function yf(e,t){if(!nr(e)||typeof e.method!=="string")return M("OPERATION_SHAPE_INVALID");if(!it(e,["method"],["jsonrpc","id","params"]))return M("OPERATION_SHAPE_INVALID");let r=e.method;if(r!=="createSession"&&r!=="subscribe"&&r!=="dispatchAction")return M("OPERATION_NOT_ALLOWLISTED");let n=e.params;if(!nr(n))return M("OPERATION_SHAPE_INVALID");let o=qy(n);if(o===void 0)return M("OPERATION_SHAPE_INVALID");if(o.workspaceId!==t.workspaceId)return M("WORKSPACE_OR_MEMBER_UNKNOWN");let s=t.agents.get(o.agentMemberId);if(s===void 0)return M("AGENT_NOT_MAPPED");let i=Hy(o.workspaceId,o.agentMemberId,o.threadRef),a=t.sessions.get(i),{triggering:c,...d}=o,u=e.id,l={jsonrpc:"2.0",...u===void 0?{}:{id:u}},p=n.channel;if(r==="createSession"){if(!it(n,["channel","_meta"]))return M("OPERATION_SHAPE_INVALID");if(typeof p!=="string"||!or.test(p))return M("OPERATION_SHAPE_INVALID");if(a!==void 0)return M("OPERATION_SHAPE_INVALID");if(Gy(t,p))return M("FOREIGN_SESSION");return{ok:!0,operation:"createSession",frame:{...l,method:r,params:{channel:p,provider:s.provider,workingDirectories:[s.workingDirectory]}},meta:d,...c===void 0?{}:{triggering:c},sessionKey:i}}if(r==="subscribe"){if(!it(n,["channel","_meta"]))return M("OPERATION_SHAPE_INVALID");if(typeof p!=="string")return M("OPERATION_SHAPE_INVALID");if(a===void 0||a.sessionUri!==p)return M("FOREIGN_SESSION");return{ok:!0,operation:"subscribe",frame:{...l,method:r,params:{channel:p}},meta:d,...c===void 0?{}:{triggering:c},sessionKey:i}}if(!it(n,["channel","clientSeq","action","_meta"]))return M("OPERATION_SHAPE_INVALID");if(typeof n.clientSeq!=="number"||!Number.isInteger(n.clientSeq)||n.clientSeq<1)return M("OPERATION_SHAPE_INVALID");if(typeof p!=="string")return M("OPERATION_SHAPE_INVALID");if(a?.chatUri===void 0||a.chatUri!==p){if(t.parked?.has(i)===!0)return M("AGENT_NOT_MAPPED");return M("FOREIGN_SESSION")}let f=n.action;if(!nr(f)||f.type!=="chat/turnStarted")return M("OPERATION_NOT_ALLOWLISTED");if(!it(f,["type","turnId","message"],["startedAt"]))return M("OPERATION_SHAPE_INVALID");if(typeof f.turnId!=="string"||!By.test(f.turnId))return M("OPERATION_SHAPE_INVALID");if(f.startedAt!==void 0&&typeof f.startedAt!=="number")return M("OPERATION_SHAPE_INVALID");let m=f.message;if(!nr(m)||!it(m,["text","origin"])||typeof m.text!=="string")return M("OPERATION_SHAPE_INVALID");if(!nr(m.origin)||!it(m.origin,["kind"])||m.origin.kind!=="user")return M("OPERATION_SHAPE_INVALID");if(m.text!==`wake ${o.threadRef}`)return M("WAKE_TEXT_NOT_ALLOWED");return{ok:!0,operation:"dispatchAction",frame:{...l,method:r,params:{channel:p,clientSeq:n.clientSeq,action:{type:"chat/turnStarted",turnId:f.turnId,...f.startedAt===void 0?{}:{startedAt:f.startedAt},message:{text:m.text,origin:{kind:"user"}}}}},meta:d,...c===void 0?{}:{triggering:c},sessionKey:i,turnId:f.turnId}}function Gy(e,t){for(let r of e.sessions.values())if(r.sessionUri===t)return!0;return!1}import{fileURLToPath as C_}from"node:url";var Ky="host",hn=(e)=>{if(typeof e!=="object"||e===null)return;let{code:t,message:r}=e;if(typeof t!=="number"||typeof r!=="string")return;let n=e.data;return n===void 0?{code:t,message:r}:{code:t,message:r,data:n}},Vy=(e)=>e.ifRevision===0,pn=(e)=>e instanceof Error&&/timed? ?out|timeout/iu.test(e.message),_f="x-ahpd-agents://";async function Wy(e){let t,r=!1;try{let n=await e.peer.request("subscribe",{channel:Ge},Qt);r=!0;let o=typeof n==="object"&&n!==null?n.snapshot:void 0;if(t=typeof o==="object"&&o!==null?o.state:void 0,typeof t!=="object"||t===null)throw Error("hightea-pipe: the services snapshot holds no state")}catch(n){let o=hn(n);if(o!==void 0)return{ok:!1,reason:"refused",...o};if(e.log.error(`hightea-pipe: ${n instanceof Error?n.message:"the services snapshot is unreadable"}`),pn(n))return{ok:!1,reason:"timedOut"};return{ok:!1,reason:"refused",code:-32603,message:"this host could not read ahpd's services"}}finally{if(r)try{e.peer.notify("unsubscribe",{channel:Ge})}catch(n){e.log.error(`hightea-pipe: dropping the services subscription failed: ${n instanceof Error?n.name:typeof n}`)}}return{ok:!0,result:t}}function Jy(e){let t=typeof e==="object"&&e!==null?e.snapshot:void 0,r=typeof t==="object"&&t!==null?t.state:void 0,n=typeof r==="object"&&r!==null?r.records:void 0;if(!Array.isArray(n))throw Error("hightea-pipe: the agents snapshot holds no records");return n.map((o)=>{if(typeof o!=="object"||o===null)throw Error("hightea-pipe: an agents snapshot entry is not an object");let s=o;if(typeof s.record==="object"&&s.record!==null&&!Array.isArray(s.record)){if(typeof s.id!=="string")throw Error("hightea-pipe: an agents snapshot entry names no id");return{id:s.id,...s.record}}if(typeof s.id!=="string")throw Error("hightea-pipe: an agents snapshot entry names no id");return s})}async function Yy(e){let t=new Set([...e.agents.values()].map((s)=>s.provider)),r,n;try{r=await e.peer.request("subscribe",{channel:_f},Qt),n=Jy(r)}catch(s){let i=hn(s);if(i!==void 0)return{ok:!1,reason:"refused",...i};if(e.log.error(`hightea-pipe: ${s instanceof Error?s.message:"the agents snapshot is unreadable"}`),pn(s))return{ok:!1,reason:"timedOut"};return{ok:!1,reason:"refused",code:-32603,message:"this host could not read ahpd's agent list"}}let o=n.filter((s)=>typeof s.id==="string"&&t.has(s.id));o.sort((s,i)=>String(s.id)<String(i.id)?-1:String(s.id)>String(i.id)?1:0);try{e.peer.notify("unsubscribe",{channel:_f})}catch(s){e.log.error(`hightea-pipe: dropping the agents subscription failed: ${s instanceof Error?s.name:typeof s}`)}return{ok:!0,result:{rows:o}}}async function Xy(e){let t;try{t=await e.peer.request("listSessions",{channel:"ahp-root://"},Qt)}catch(i){let a=hn(i);if(a!==void 0)return{ok:!1,reason:"refused",...a};if(e.log.error(`hightea-pipe: the session list is unreadable: ${i instanceof Error?i.name:typeof i}`),pn(i))return{ok:!1,reason:"timedOut"};return{ok:!1,reason:"refused",code:-32603,message:"this host could not read ahpd's session list"}}let r=rs(t)&&Array.isArray(t.items)?t.items:void 0;if(r===void 0)return e.log.error("hightea-pipe: ahpd's listSessions result holds no items"),{ok:!1,reason:"refused",code:-32603,message:"this host could not read ahpd's session list"};let n=[],o=[];for(let i of r){let a=rs(i)&&typeof i.resource==="string"&&i.resource!==""?i.resource:void 0;if(a===void 0){o.push("a summary with no resource");continue}let c;try{c=e.memberOf(a)}catch(l){o.push(`${a}: ${l instanceof Error?l.message:String(l)}`);continue}if(c===void 0)continue;let d=cf(i,c,e.hostToolsServer(a));if(d===void 0){o.push(`${a}: its summary names another member`);continue}let u=d._meta["hh/hostTools"];if(u!==void 0)e.rememberHostTools?.(a,u);n.push(d)}let s=new Set(n.map((i)=>i.resource));for(let i of e.ownSessions?.()??[]){if(s.has(i))continue;let a=e.memberOf(i);if(a===void 0)continue;let c=e.toolsAnswerOf?.(i);if(c===void 0){o.push(`${i}: provisional, and this pipe holds no tools answer for it yet`);continue}let d=tr({[st]:c},a,e.hostToolsServer(i));if(d===void 0)continue;n.push({resource:i,_meta:d})}if(o.length>0)e.log.error(`hightea-pipe: skipped ${o.length} unreadable session row(s): ${o.join("; ").slice(0,500)}`);return{ok:!0,result:{items:n}}}async function wf(e,t){let r=e_(e.meta);if(r===void 0)return{ok:!1,reason:"outside"};let n=e.method;if(!t_(n)&&!Xt(n))return{ok:!1,reason:"outside"};let o=e.params;if(!rs(o))return{ok:!1,reason:"outside"};let s="agentMemberId"in o;if(s&&(typeof o.agentMemberId!=="string"||o.agentMemberId===""))return{ok:!1,reason:"outside"};let i=s?o.agentMemberId:r.agentMemberId;if(Xt(n)){if(i!==void 0)return{ok:!1,reason:"outside"};let u=Ql(n,o);if(u!==void 0)return t.log.error(`hightea-pipe: refused a host request: ${u}`),{ok:!1,reason:"outside"};if(n==="subscribe")return Wy(t);if(n==="listSessions")return Xy(t);if(n==="authenticate")return r_(t,o);return ns(t,n,o)}if(n==="x-ahpd/agents/list"){if(i!==void 0)return{ok:!1,reason:"outside"};if(Object.keys(o).length!==0)return{ok:!1,reason:"outside"};return Yy(t)}if(i===void 0)return{ok:!1,reason:"outside"};let a=t.agents.get(i);if(a===void 0||a.provider!==o.id)return{ok:!1,reason:"unmapped"};let c=s?Qy(o):o,d=n==="x-ahpd/agents/put"&&Vy(c)?{...c,owner:Ky}:c;return ns(t,n,d)}function Qy(e){let{agentMemberId:t,...r}=e;return r}function e_(e){let t=sf.safeParse(e);return t.success?t.data:void 0}function rs(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function t_(e){return e==="x-ahpd/agents/list"||e==="x-ahpd/agents/put"||e==="x-ahpd/agents/remove"||e==="x-ahpd/agents/enable"||e==="x-ahpd/agents/pause"||e==="x-ahpd/agents/disable"}async function r_(e,t){let r=t.target;if(typeof r.session!=="string"||e.memberOf(r.session)===void 0)return e.log.error("hightea-pipe: refused an authenticate aimed at a session this pipe did not make"),{ok:!1,reason:"outside"};let n=typeof r.session==="string"?e.hostToolsServer(r.session):void 0;if(n===void 0)return e.log.error("hightea-pipe: refused an authenticate: this host serves no Hightea MCP server, or the session has not yet said which customization is ours"),{ok:!1,reason:"outside"};if(r.customizationId!==n.customizationId)return e.log.error("hightea-pipe: refused an authenticate aimed at a server that is not this host's"),{ok:!1,reason:"outside"};if(t.resource!==n.resource)return e.log.error("hightea-pipe: refused an authenticate for a resource that is not this host's server"),{ok:!1,reason:"outside"};return ns(e,"authenticate",t)}async function ns(e,t,r){try{return{ok:!0,result:await e.peer.request(t,r,Qt)??null}}catch(n){let o=hn(n);if(o!==void 0)return{ok:!1,reason:"refused",...o};return e.log.error(`hightea-pipe: host request ${t} ended without an answer`+(pn(n)?" (timed out)":"")+`: ${n instanceof Error?n.name:typeof n}`),{ok:!1,reason:"timedOut"}}}import{createPrivateKey as m_,createPublicKey as g_,generateKeyPairSync as y_,sign as __}from"node:crypto";import{appendFile as w_,chmod as S_,readFile as If,rename as kf,writeFile as Cf}from"node:fs/promises";import{join as is}from"node:path";function n_(e){return JSON.stringify({v:1,workspaceId:e.workspaceId,roomId:e.roomId,rootMessageId:e.rootMessageId,authorMemberId:e.authorMemberId,clientId:e.clientId,body:e.body,attachmentIds:[...e.attachmentIds],createdAt:e.createdAt})}function mn(e){return new TextEncoder().encode(n_(e))}import{createPublicKey as o_,verify as s_}from"node:crypto";var i_=Buffer.from("302a300506032b6570032100","hex");function os(e,t){let r=e.signed;if(r===void 0)return{ok:!1,code:"ASK_UNSIGNED",why:`message ${e.id} carries no signature`};let n=t.keys.find((a)=>a.keyId===r.keyId);if(n===void 0)return{ok:!1,code:"ROOM_ASKS_UNTRUSTED",why:`message ${e.id} is signed by key ${r.keyId}, which this host does not trust yet; its owner approves that browser with \`hightea approve\` and the ask goes through`};let o=mn({workspaceId:t.workspaceId,roomId:t.roomId,rootMessageId:e.replyTo??null,authorMemberId:e.from.memberId,clientId:r.clientId,body:e.text,attachmentIds:r.attachmentIds,createdAt:r.createdAt}),s=Buffer.from(r.signature,"base64url"),i=o_({key:Buffer.concat([i_,Buffer.from(n.publicKey,"base64url")]),format:"der",type:"spki"});if(s.length!==64||!s_(null,o,i,s))return{ok:!1,code:"ASK_UNSIGNED",why:`message ${e.id}'s signature by ${n.name} does not match what the room returned (text, thread, author ${e.from.memberId}, or attachments)`};if(t.ownKeyId!==void 0&&n.keyId===t.ownKeyId&&!t.ownAgents.has(e.from.memberId))return{ok:!1,code:"KEY_NOT_FOR_AUTHOR",why:`message ${e.id} is signed by this host's key but attributed to ${e.from.memberId}, which this host does not run`};return{ok:!0,keyName:n.name,clientId:r.clientId,createdAt:r.createdAt}}function Sf(e,t){let r=(a)=>a.deleted===!0?{id:a.id,deleted:!0}:a,n=(a)=>a.deleted===!0||os(a,t).ok,o=n(e.root),s=e.replies.filter(n).map(r),i=(o?0:1)+e.replies.length-e.replies.filter(n).length;return{...e,root:o?r(e.root):{id:e.root.id,omitted:!0},replies:s,...i===0?{}:{omitted:`${String(i)} unsigned messages omitted`}}}import{createHash as a_}from"node:crypto";import{existsSync as c_,readFileSync as u_}from"node:fs";import{join as d_}from"node:path";var l_="trusted-keys.json",f_=/^(?=.{1,64}$)[A-Za-z0-9][A-Za-z0-9._-]*(?: [A-Za-z0-9._-]+)*$/u,h_=/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/u,p_=(e)=>Buffer.from(e).toString("base64url");function ss(e){if(!h_.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:p_(a_("sha256").update(Buffer.from(e,"base64url")).digest())}}function vf(e){let t=d_(e,l_);if(!c_(t))return{state:"missing",file:t};let r;try{r=JSON.parse(u_(t,"utf8"))}catch(o){throw Error(`TRUST_FILE_UNREADABLE: ${t} is not JSON (${o.message})`)}let n=r;if(typeof r!=="object"||r===null||n.v!==1||!Array.isArray(n.keys))throw Error(`TRUST_FILE_UNREADABLE: ${t} is not a version 1 list of trusted keys`);for(let o of n.keys){let s=o,i=typeof s.publicKey==="string"?ss(s.publicKey):void 0;if(typeof s.name!=="string"||!f_.test(s.name)||i===void 0||"error"in i||s.keyId!==i.keyId||typeof s.addedAt!=="string")throw Error(`TRUST_FILE_UNREADABLE: ${t} holds an entry that is not a valid trusted key: ${JSON.stringify(o)}`)}return{state:"read",file:t,keys:n.keys}}class Z extends Error{code;constructor(e,t){super(`${e}: ${t}`);this.code=e}}var v_="host-signing-key",xf="hightea-acted-asks.jsonl",gn=600000,x_=2592000000,b_=20;async function Rf(e,t=()=>Date.now()){let r=is(e,v_),n;try{n=await If(r,"utf8")}catch(a){if(a.code!=="ENOENT")throw Error(`HOST_KEY_UNREADABLE: ${r} exists but cannot be read (${String(a)}); it is never regenerated, fix or remove it by hand`)}if(n===void 0){let a=y_("ed25519").privateKey.export({format:"pem",type:"pkcs8"}).toString(),c=`${r}.${String(process.pid)}.tmp`;await Cf(c,a,{mode:384,flag:"wx"}),await S_(c,384),await kf(c,r),n=a}let o;try{if(o=m_({key:n,format:"pem"}),o.asymmetricKeyType!=="ed25519")throw Error(`a ${String(o.asymmetricKeyType)} key, not Ed25519`)}catch(a){throw Error(`HOST_KEY_UNREADABLE: ${r} is not an Ed25519 PKCS8 key (${String(a)}); it is never regenerated, fix or remove it by hand`)}let s=g_(o).export({format:"jwk"}).x,i=s===void 0?{error:"no public key"}:ss(s);if("error"in i)throw Error(`HOST_KEY_UNREADABLE: ${r}: ${i.error}`);return{privateKey:o,trusted:{name:"this-host",keyId:i.keyId,publicKey:s,addedAt:new Date(t()).toISOString()}}}function Of(e,t,r=()=>Date.now()){let n=new Date(r()).toISOString(),o=mn({...t,attachmentIds:[],createdAt:n});return{keyId:e.trusted.keyId,createdAt:n,signature:__(null,o,e.privateKey).toString("base64url")}}async function bf(e,t){if(e.configDir===void 0)throw new Z("ROOM_ASKS_UNTRUSTED","this host's ahpd is too old for signed asks (it names no configDir)");let r=await e.hostKey;if(r instanceof Error)throw new Z("ROOM_ASKS_UNTRUSTED",r.message);let n;try{let s=await vf(e.configDir);n=s.state==="read"?s.keys:[]}catch(s){throw new Z("ROOM_ASKS_UNTRUSTED",String(s instanceof Error?s.message:s))}if(n.length===0)throw new Z("ROOM_ASKS_UNTRUSTED","this host trusts no key yet; its owner runs `hightea host trust add`");let o=r?.trusted;return{workspaceId:e.workspaceId,roomId:t,keys:o===void 0||n.some((s)=>s.keyId===o.keyId)?n:[...n,o],...o===void 0?{}:{ownKeyId:o.keyId},ownAgents:e.ownAgents}}function Ef(e){let[t,r,n]=e.split("/");if(!t||!r||n!==void 0)throw new Z("ASK_UNSIGNED",`the wake's thread ref ${e} names no room thread`);return{roomId:t,rootMessageId:r}}function E_(e,t,r){if(t===void 0||t==="")throw new Z("ASK_UNSIGNED",`wake ${r.deliveryId} carries no signed envelopes and this caller has no bearer to read its thread with`);return t}function I_(e,t,r,n){let o=new Map;for(let i of e){let a=i.replyTo??i.id;if(a!==r)throw new Z("ASK_UNSIGNED",`wake ${n.deliveryId} carries message ${i.id} from thread ${a}, not ${n.threadRef}`);o.set(i.id,{id:i.id,from:{memberId:i.from.memberId},text:i.text,...i.replyTo===void 0?{}:{replyTo:i.replyTo},...i.deleted===void 0?{}:{deleted:!0},...i.signed===void 0?{}:{signed:i.signed}})}let s=new Set(o.keys());if(s.size!==t.length||t.some((i)=>!s.has(i)))throw new Z("ASK_UNSIGNED",`wake ${n.deliveryId} froze ${t.length} triggering messages and carried ${s.size}, not the same ones`);return o}class sr{#e;#o;#r=Promise.resolve();constructor(e){this.#e=e}async admit(e,t){let{roomId:r,rootMessageId:n}=Ef(e.threadRef),o=await bf(this.#e,r),s=e.triggering,i=s===void 0?e.triggeringMessageIds:s.map((l)=>l.id);if(i===void 0||i.length===0)throw new Z("ASK_UNSIGNED",`wake ${e.deliveryId} names no triggering message to check`);let a=s===void 0?await this.#s(E_(this.#e,t,e),r,n,e.afterMessageId,new Set(i)):I_(s,i,n,e),c=(this.#e.now??Date.now)(),d=await this.#n(c),u=[];for(let l of i){let p=a.get(l);if(p===void 0)throw new Z("ASK_UNSIGNED",`triggering message ${l} is not in thread ${e.threadRef}`);let f=os(p,o);if(!f.ok)throw new Z(f.code,f.why);let m=d.filter((g)=>g.clientId===f.clientId);if(m.some((g)=>g.deliveryId!==e.deliveryId))throw new Z("ASK_REPLAYED",`the ask signed as ${f.clientId} (message ${l}) was already acted on under another wake`);if(m.length>0){let g=Math.min(...m.map((w)=>w.at));if(c-g>gn)throw new Z("ASK_REPLAYED",`wake ${e.deliveryId} was first admitted at ${new Date(g).toISOString()}, more than 10 minutes ago; a new attempt of it is not admitted`);continue}let y=Date.parse(f.createdAt);if(!Number.isFinite(y)||Math.abs(c-y)>gn)throw new Z("ASK_STALE",`message ${l} was signed at ${f.createdAt}, more than 10 minutes from this host's clock`);u.push({clientId:f.clientId,deliveryId:e.deliveryId,at:c})}if(u.length>0)await this.#c(d,u)}async view(e,t){return Sf(t,await bf(this.#e,Ef(e).roomId))}async#s(e,t,r,n,o){let s=new Map,i=n??r;for(let a=0;a<b_;a++){let c=await this.#e.readThread(e,{roomId:t,messageId:r,after:i});if(!k_(c))throw new Z("ASK_UNSIGNED",`read_thread answered no root and replies for ${t}/${r}`);for(let u of[c.root,...c.replies])if(o.has(u.id))s.set(u.id,u);let d=c.replies.at(-1);if(s.size===o.size||c.more!==!0||d===void 0)break;i=d.id}return s}async#n(e){this.#o??=(async()=>{let r=is(this.#e.configDir,xf),n="";try{n=await If(r,"utf8")}catch(i){if(i.code!=="ENOENT")throw new Z("ROOM_ASKS_UNTRUSTED",`${r} cannot be read: ${String(i)}`)}let o=[];for(let[i,a]of n.split(`
|
|
63
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let d=e.external.registry.get(i[0])?.id;if(t!==i[0]&&d){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1){if(e.reused==="ref")s(i)}}if(e.external)e.sharedDefsExtractedFor=e.external}function Md(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let n of t){if(!n||typeof n!=="object")return;Md(n);let o=Object.keys(n);if(o.length!==1||o[0]!=="type")return;let s=n.type;for(let i of Array.isArray(s)?s:[s]){if(typeof i!=="string")return;if(!r.includes(i))r.push(i)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var Dd=new Set(["type","properties","required","additionalProperties"]),Nd=["oneOf","anyOf"];function zd(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 Uo(e){let t=[];for(let s of e){if(typeof s!=="object"||s.type!=="object")return null;for(let i in s)if(!Dd.has(i))return null;t.push(s)}let r={},n=new Set;for(let s of t){for(let i in s.properties){if(Object.prototype.hasOwnProperty.call(r,i))continue;let a=[];for(let d of t){let u=d.properties?.[i]??zd(d);if(u===null||u===void 0)continue;if(!a.some((l)=>JSON.stringify(l)===JSON.stringify(u)))a.push(u)}let c=a.length===1?a[0]:Uo(a)??{allOf:a};fe(r,i,c)}for(let i of s.required??[])n.add(i)}let o={type:"object",properties:r};if(n.size)o.required=[...n];if(t.every((s)=>s.additionalProperties===!1))o.additionalProperties=!1;else{let s=[];for(let i of t){let a=zd(i);if(a&&!s.some((c)=>JSON.stringify(c)===JSON.stringify(a)))s.push(a)}if(s.length===1)o.additionalProperties=s[0];else if(s.length>1)o.additionalProperties={allOf:s}}return o}function og(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of Dd)if(o in e)return;let r=t.filter((o)=>Nd.some((s)=>Array.isArray(o[s]))),n=null;if(!r.length)n=Uo(t);else{let o=r[0],s=Nd.find((c)=>Array.isArray(o[c]));if(Object.keys(o).length!==1)return;let i=t.filter((c)=>c!==o),a=o[s].map((c)=>Uo([...i,c]));if(a.some((c)=>!c))return;n={[s]:a}}if(!n)return;delete e.allOf,Kt(e,n)}function Fo(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let d=c.def??c.schema,u={...d},l=c.ref;if(c.ref=null,l){n(l);let f=e.seen.get(l),m=f.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))d.allOf=d.allOf??[],d.allOf.push(m);else Kt(d,m);if(Kt(d,u),a._zod.parent===l)for(let g in d){if(g==="$ref"||g==="allOf")continue;if(!(g in u))delete d[g]}if(m.$ref&&f.def)for(let g in d){if(g==="$ref"||g==="allOf")continue;if(g in f.def&&JSON.stringify(d[g])===JSON.stringify(f.def[g]))delete d[g]}}let p=a._zod.parent;if(p&&p!==l){n(p);let f=e.seen.get(p);if(f?.schema.$ref){if(d.$ref=f.schema.$ref,f.def)for(let m in d){if(m==="$ref"||m==="allOf")continue;if(m in f.def&&JSON.stringify(d[m])===JSON.stringify(f.def[m]))delete d[m]}}}e.override({zodSchema:a,jsonSchema:d,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())n(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())Md(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let d of[c.schema,c.def]){let u=d?.allOf;if(!Array.isArray(u))continue;let l=a.get(u);if(l)l.push(d);else a.set(u,[d])}for(let c of e.intersections)for(let d of a.get(c)??[])og(d)}}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 a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Kt(o,r.defId?r.schema:r.def??r.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 a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;fe(i,c.defId,c.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 a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Vt(t,"input",e.processors),output:Vt(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function ee(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return ee(n.element,r);if(n.type==="set")return ee(n.valueType,r);if(n.type==="lazy")return ee(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault"||n.type==="catch")return ee(n.innerType,r);if(n.type==="intersection")return ee(n.left,r)||ee(n.right,r);if(n.type==="record"||n.type==="map")return ee(n.keyType,r)||ee(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return ee(n.in,r)||ee(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(ee(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(ee(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(ee(o,r))return!0;if(n.rest&&ee(n.rest,r))return!0;return!1}return!1}var Ld=(e,t={})=>(r)=>{let n=Zo({...r,processors:t});return j(e,n),jo(n,e),Fo(n,e)},Vt=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:s}=n??{},i=Zo({...o??{},target:s,io:t,processors:r});return j(e,i),jo(i,e),Fo(i,e)};var yt=(e,t,r)=>{if(e[t]===void 0||r>e[t])e[t]=r},_t=(e,t,r)=>{if(e[t]===void 0||r<e[t])e[t]=r},Ud=(e,t)=>{yt(e,"minimum",t),_t(e,"maximum",t)},Hd=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},Bd=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},qd=(e,t)=>{e.mime=e.mime?e.mime.filter((r)=>t.includes(r)):[...t]},Gd=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},Zd=(e,t)=>yt(e,"minimum",t.minimum),jd=(e,t)=>_t(e,"maximum",t.maximum),Fd=(e)=>(t,r)=>{Gd(t,r.format);let[n,o]=e[r.format];yt(t,"minimum",n),_t(t,"maximum",o)},sg={greater_than:(e,t)=>yt(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>_t(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Hd(e,t.value),number_format:Fd(Tr),bigint_format:Fd(oo),min_length:Zd,max_length:jd,length_equals:(e,t)=>Ud(e,t.length),min_size:Zd,max_size:jd,size_equals:(e,t)=>Ud(e,t.size),string_format:(e,t)=>{if(Gd(e,t.format),t.pattern)Bd(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)=>qd(e,t.mime)};function ue(e){let t={},r=e._zod.def,n=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let s of n)sg[s._zod.def.check]?.(t,s._zod.def);let o=e._zod.bag;if(o.minimum!==void 0)yt(t,"minimum",o.minimum);if(o.exclusiveMinimum!==void 0)yt(t,"exclusiveMinimum",o.exclusiveMinimum);if(o.maximum!==void 0)_t(t,"maximum",o.maximum);if(o.exclusiveMaximum!==void 0)_t(t,"exclusiveMaximum",o.exclusiveMaximum);if(o.multipleOf!==void 0)Hd(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)qd(t,o.mime);for(let s of o.patterns??[])Bd(t,s);return t}var ig={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ag=new Map([[vo,ac],[Gr,cc]]),Kd=(e)=>ag.get(e)??e,Vd=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:d,laxFormat:u}=ue(e);if(typeof s==="number")o.minLength=s;if(typeof i==="number")o.maxLength=i;if(a){if(o.format=ig[a]??a,o.format==="")delete o.format;if(a==="time"||u)delete o.format}if(d)o.contentEncoding=d;if(c&&c.size>0){let l=[...c].map(Kd);if(l.length===1)o.pattern=l[0].source;else if(l.length>1)o.allOf=[...l.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},Wd=(e,t,r,n)=>{let o=r,{minimum:s,maximum:i,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:d,isInt:u}=ue(e);o.type=u?"integer":"number";let l=typeof d==="number"&&d>=(s??Number.NEGATIVE_INFINITY),p=typeof c==="number"&&c<=(i??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(l)if(f)o.minimum=d,o.exclusiveMinimum=!0;else o.exclusiveMinimum=d;else if(typeof s==="number")o.minimum=s;if(p)if(f)o.maximum=c,o.exclusiveMaximum=!0;else o.exclusiveMaximum=c;else if(typeof i==="number")o.maximum=i;if(a){let m=new Set;for(let w of a)if(Number.isFinite(w)&&w!==0)m.add(Math.abs(w));else $e(e,t,o,n,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);let[y,...g]=m;if(y!==void 0)o.multipleOf=y;if(g.length)o.allOf=[...o.allOf??[],...g.map((w)=>({multipleOf:w}))]}},Jd=(e,t,r,n)=>{r.type="boolean"};var Yd=(e,t,r,n)=>{r.not={}};var Xd=(e,t,r,n)=>{};var Qd=(e,t,r,n)=>{let o=e._zod.def,s=zt(o.entries);if(s.length===0){r.not={};return}if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";r.enum=s},el=(e,t,r,n)=>{let o=e._zod.def;if(o.values.length===0){r.not={};return}let s=[];for(let i of o.values)if(i===void 0){if($e(e,t,r,n,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i==="bigint"){if($e(e,t,r,n,"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(r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[i];else r.const=i}else{if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";if(s.every((i)=>typeof i==="boolean"))r.type="boolean";if(s.every((i)=>i===null))r.type="null";r.enum=s}};var tl=(e,t,r,n)=>{$e(e,t,r,n,"Custom types cannot be represented in JSON Schema")};var rl=(e,t,r,n)=>{$e(e,t,r,n,"Transforms cannot be represented in JSON Schema")};var nl=(e,t,r,n)=>{let o=r,s=e._zod.def,{minimum:i,maximum:a}=ue(e);if(typeof i==="number")o.minItems=i;if(typeof a==="number")o.maxItems=a;o.type="array",o.items=j(s.element,t,{...n,path:[...n.path,"items"]})};function Wt(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return Wt(t.out);if(t.type==="catch")return Wt(t.innerType);return e._zod.optin}var ol=(e,t,r,n)=>{let o=r,s=e._zod.def,i=s.shape;if(Object.getOwnPropertySymbols(i).length&&$e(e,t,o,n,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(let d in i)fe(o.properties,d,j(i[d],t,{...n,path:[...n.path,"properties",d]}));let c=[];for(let d of Object.keys(i)){let u=s.shape[d];if(t.io==="input"?Wt(u)===void 0:u._zod.optout===void 0)c.push(d)}if(c.length>0)o.required=c;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=j(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})},sl=(e,t,r,n)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>j(a,t,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));if(s)r.oneOf=i;else r.anyOf=i},il=(e,t,r,n)=>{let o=e._zod.def,s=j(o.left,t,{...n,path:[...n.path,"allOf",0]}),i=j(o.right,t,{...n,path:[...n.path,"allOf",1]}),a=(d)=>("allOf"in d)&&Object.keys(d).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c,t.intersections.push(c)},al=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",c=s.items.map((y,g)=>j(y,t,{...n,path:[...n.path,i,g]})),d=s.rest?j(s.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null,u=s.items.length;while(u>0){let y=s.items[u-1];if(!(t.io==="input"?Wt(y)!==void 0:y._zod.optout==="optional"))break;u--}let l=s.items.length,p=!s.rest;if(t.target==="draft-2020-12"){if(o.prefixItems=c,p)o.items=!1;else if(d)o.items=d;if(u>0)o.minItems=u;if(p)o.maxItems=l}else if(t.target==="openapi-3.0"){if(o.items={anyOf:c},d)o.items.anyOf.push(d);if(u>0)o.minItems=u;if(p)o.maxItems=l}else{if(o.items=c,p)o.additionalItems=!1;else if(d)o.additionalItems=d;if(u>0)o.minItems=u;if(p)o.maxItems=l}let{minimum:f,maximum:m}=ue(e);if(typeof f==="number")o.minItems=f;if(typeof m==="number")o.maxItems=m};function Ho(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let m=e.get(t)?.def;if(!m)return t;let y=Ho(e,m,r);return y===m?t:y}for(let m of["anyOf","oneOf"]){let y=t[m];if(!Array.isArray(y))continue;let g=y.map((w)=>Ho(e,w,r));if(g.some((w,b)=>w!==y[b]))t={...t,[m]:g}}let n=Array.isArray(t.type)?t.type:[t.type],o=!n.includes("string")&&n.some((m)=>m==="number"||m==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!s?.some((m)=>typeof m==="number"))return t;let{minimum:i,maximum:a,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:u,format:l,id:p,...f}=t;if(f.enum)f.enum=f.enum.map((m)=>typeof m==="number"?String(m):m);else if(typeof f.const==="number")f.const=String(f.const);if(!o)return f;if(f.type="string",!s)f.pattern=(n.includes("number")?Zt:po).source;return f}var Bo=new WeakMap;function cg(e){let t=new Map;for(let n of e.seen.values())if(n.def&&!t.has(n.schema))t.set(n.schema,n);let r=new Map;for(let n of Bo.get(e)??[]){let o=e.seen.get(n),s=(o?.def??o?.schema)?.propertyNames;if(!s||s===!0||r.has(s))continue;let i=Ho(t,s,new Set);if(i!==s)r.set(s,i)}if(!r.size)return;for(let n of e.seen.values())for(let o of[n.schema,n.def]){let s=o&&r.get(o.propertyNames);if(s)o.propertyNames=s}}var cl=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object";let i=s.keyType,a=ue(i).patterns;if(s.mode==="loose"&&a&&a.size>0){let u=j(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let l of a)fe(o.patternProperties,Kd(l).source,u)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=j(s.keyType,t,{...n,path:[...n.path,"propertyNames"]});let u=Bo.get(t);if(!u)u=[],Bo.set(t,u),t.deferred.push(()=>cg(t));u.push(e)}o.additionalProperties=j(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let c=i._zod.values,d=t.io==="input"&&Wt(s.valueType)!==void 0;if(c&&!s.partial&&!d){let u=[...c].filter((l)=>typeof l==="string"||typeof l==="number");if(u.length>0)o.required=u.map(String)}},ul=(e,t,r,n)=>{let o=e._zod.def,s=j(o.innerType,t,n),i=t.seen.get(e);if(t.target==="openapi-3.0")i.ref=o.innerType,r.nullable=!0;else r.anyOf=[s,{type:"null"}]},dl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},qo=Symbol();function ll(e,t,r,n,o){let s=!1,i=JSON.stringify(e,(a,c)=>{if(typeof c!=="bigint")return c;return s=!0,null});if(!s)return JSON.parse(i);return $e(t,r,n,o,"BigInt defaults cannot be represented in JSON Schema"),qo}var fl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i=ll(o.defaultValue,e,t,r,n);if(i!==qo)r.default=i},hl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);if(s.ref=o.innerType,t.io!=="input")return;let i=ll(o.defaultValue,e,t,r,n);if(i!==qo)r._prefault=i},pl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{$e(e,t,r,n,"Dynamic catch values are not supported in JSON Schema");return}r.default=i},ml=(e,t,r,n)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;j(i,t,n);let a=t.seen.get(e);a.ref=i},gl=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0};var Go=(e,t,r,n)=>{let o=e._zod.def;j(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType};var yl=new WeakSet([Object.prototype,Error.prototype]);function rn(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let n=r(this);return Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0})}})}var gg=(e,t)=>{Na.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);if(yl.has(r))return;yl.add(r),rn(r,"format",(n)=>(o)=>Ma(n,o)),rn(r,"flatten",(n)=>(o)=>za(n,o)),rn(r,"addIssue",(n)=>(o)=>{n.issues.push(o),n.message=JSON.stringify(n.issues,Mt,2)}),rn(r,"addIssues",(n)=>(o)=>{n.issues.push(...o),n.message=JSON.stringify(n.issues,Mt,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})};var de=_("ZodError",gg,void 0,{Parent:Error});var _l=Dr(de),wl=Lr(de),Sl=Ur(de),vl=Zr(de),xl=La(de),bl=Ua(de),El=Za(de),Il=ja(de),kl=Fa(de),Cl=Ha(de),Rl=Ba(de),Ol=qa(de);function _g(){if(!Q.localeError)ce(Co())}function Jt(){if(!Q.memoizer)ce({memoizer:Vu()})}var U=_("ZodType",(e,t)=>(_g(),z.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(ae(t,{checks:[...t.checks??[],...e.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Se(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(my(e,t))},superRefine(e,t){return this.check(gy(e,t))},overwrite(e){return this.check(He(e))},optional(){return $l(this)},exactOptional(){return ry(this)},nullable(){return Pl(this)},nullish(){return $l(Pl(this))},nonoptional(e){return cy(this,e)},array(){return K(this)},or(e){return on([this,e])},and(e){return Yg(this,e)},transform(e){return Nl(this,ty(e))},default(e){return sy(this,e)},prefault(e){return ay(this,e)},catch(e){return dy(this,e)},pipe(e){return Nl(this,e)},readonly(){return hy(this)},describe(e){let t=this.clone();return et.add(t,{description:e}),t},meta(...e){if(e.length===0)return et.get(this);let t=this.clone();return et.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 zr(this,"~standard",{...So(this),jsonSchema:{input:Vt(this,"input"),output:Vt(this,"output")}})},set "~standard"(e){Ae(this,"~standard",e)},parse:function e(t,r){return _l(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await wl(this,t,r,{callee:e})},safeParse(e,t){return Sl(this,e,t)},async safeParseAsync(e,t){return vl(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Ae(this,"spa",e)},validate(e,t){return uo(this,e,t)},validateAsync(e,t){return lo(this,e,t)},encode:function e(t,r){return xl(this,t,r,{callee:e})},decode:function e(t,r){return bl(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await El(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await Il(this,t,r,{callee:e})},safeEncode(e,t){return kl(this,e,t)},safeDecode(e,t){return Cl(this,e,t)},async safeEncodeAsync(e,t){return Rl(this,e,t)},async safeDecodeAsync(e,t){return Ol(this,e,t)},toJSONSchema(e){return Ld(this,{})(e)},get description(){return et.get(this)?.description},get _def(){return this._zod.def}}),zl=_("_ZodString",(e,t)=>{qr.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Vd(e,r,n,o)},Ra({format:(e)=>ue(e).format??null,minLength:(e)=>ue(e).minimum??null,maxLength:(e)=>ue(e).maximum??null},{regex(...e){return this.check(Ro(...e))},includes(...e){return this.check(Ao(...e))},startsWith(...e){return this.check($o(...e))},endsWith(...e){return this.check(Po(...e))},min(...e){return this.check(gt(...e))},max(...e){return this.check(en(...e))},length(...e){return this.check(tn(...e))},nonempty(...e){return this.check(gt(1,...e))},lowercase(e){return this.check(Oo(e))},uppercase(e){return this.check(To(e))},trim(){return this.check(zo())},normalize(...e){return this.check(No(...e))},toLowerCase(){return this.check(Mo())},toUpperCase(){return this.check(Do())},slugify(){return this.check(Lo())}})),wg=_("ZodString",(e,t)=>{qr.init(e,t),zl.init(e,t)},{email(e){return this.check(Qu(Eg,e))},url(e){return this.check(sd(kg,e))},jwt(e){return this.check(Sd(jg,e))},emoji(e){return this.check(id(Cg,e))},guid(e){return this.check(ed(Ig,e))},uuid(e){return this.check(td(nn,e))},uuidv4(e){return this.check(rd(nn,e))},uuidv6(e){return this.check(nd(nn,e))},uuidv7(e){return this.check(od(nn,e))},nanoid(e){return this.check(ad(Rg,e))},cuid(e){return this.check(cd(Og,e))},cuid2(e){return this.check(ud(Tg,e))},ulid(e){return this.check(dd(Ag,e))},base64(e){return this.check(yd(Lg,e))},base64url(e){return this.check(_d(Ug,e))},xid(e){return this.check(ld($g,e))},ksuid(e){return this.check(fd(Pg,e))},ipv4(e){return this.check(hd(Ng,e))},ipv6(e){return this.check(pd(zg,e))},cidrv4(e){return this.check(md(Mg,e))},cidrv6(e){return this.check(gd(Dg,e))},e164(e){return this.check(wd(Zg,e))},datetime(e){return this.check(vd(Sg,e))},date(e){return this.check(xd(vg,e))},time(e){return this.check(bd(xg,e))},duration(e){return this.check(Ed(bg,e))}});function S(e){return Xu(wg,e)}var F=_("ZodStringFormat",(e,t)=>{D.init(e,t),zl.init(e,t)}),Sg=_("ZodISODateTime",(e,t)=>{iu.init(e,t),F.init(e,t)}),vg=_("ZodISODate",(e,t)=>{au.init(e,t),F.init(e,t)}),xg=_("ZodISOTime",(e,t)=>{cu.init(e,t),F.init(e,t)}),bg=_("ZodISODuration",(e,t)=>{uu.init(e,t),F.init(e,t)}),Eg=_("ZodEmail",(e,t)=>{Wc.init(e,t),F.init(e,t)});var Ig=_("ZodGUID",(e,t)=>{Kc.init(e,t),F.init(e,t)});var nn=_("ZodUUID",(e,t)=>{Vc.init(e,t),F.init(e,t)});var kg=_("ZodURL",(e,t)=>{Xc.init(e,t),F.init(e,t)});var Cg=_("ZodEmoji",(e,t)=>{Qc.init(e,t),F.init(e,t)});var Rg=_("ZodNanoID",(e,t)=>{eu.init(e,t),F.init(e,t)});var Og=_("ZodCUID",(e,t)=>{tu.init(e,t),F.init(e,t)});var Tg=_("ZodCUID2",(e,t)=>{ru.init(e,t),F.init(e,t)});var Ag=_("ZodULID",(e,t)=>{nu.init(e,t),F.init(e,t)});var $g=_("ZodXID",(e,t)=>{ou.init(e,t),F.init(e,t)});var Pg=_("ZodKSUID",(e,t)=>{su.init(e,t),F.init(e,t)});var Ng=_("ZodIPv4",(e,t)=>{du.init(e,t),F.init(e,t)});var zg=_("ZodIPv6",(e,t)=>{fu.init(e,t),F.init(e,t)});var Mg=_("ZodCIDRv4",(e,t)=>{hu.init(e,t),F.init(e,t)});var Dg=_("ZodCIDRv6",(e,t)=>{pu.init(e,t),F.init(e,t)});var Lg=_("ZodBase64",(e,t)=>{gu.init(e,t),F.init(e,t)});var Ug=_("ZodBase64URL",(e,t)=>{yu.init(e,t),F.init(e,t)});var Zg=_("ZodE164",(e,t)=>{_u.init(e,t),F.init(e,t)});var jg=_("ZodJWT",(e,t)=>{wu.init(e,t),F.init(e,t)});var Ml=_("ZodNumber",(e,t)=>{xo.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Wd(e,r,n,o),e.isFinite=!0},Ra({minValue:(e)=>{let{minimum:t,exclusiveMinimum:r}=ue(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:r}=ue(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:r}=ue(e);return!!t||!!r?.some(Number.isSafeInteger)},format:(e)=>ue(e).format??null},{gt(e,t){return this.check(Xr(e,t))},gte(e,t){return this.check(Gt(e,t))},min(e,t){return this.check(Gt(e,t))},lt(e,t){return this.check(Yr(e,t))},lte(e,t){return this.check(qt(e,t))},max(e,t){return this.check(qt(e,t))},int(e){return this.check(Tl(e))},safe(e){return this.check(Tl(e))},positive(e){return this.check(Xr(0,e))},nonnegative(e){return this.check(Gt(0,e))},negative(e){return this.check(Yr(0,e))},nonpositive(e){return this.check(qt(0,e))},multipleOf(e,t){return this.check(Qr(e,t))},step(e,t){return this.check(Qr(e,t))},finite(){return this}}));function Pe(e){return Id(Ml,e)}var Fg=_("ZodNumberFormat",(e,t)=>{Su.init(e,t),Ml.init(e,t)});function Tl(e){return kd(Fg,e)}var Hg=_("ZodBoolean",(e,t)=>{vu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Jd(e,r,n,o)});function Yt(e){return Cd(Hg,e)}var Bg=_("ZodUnknown",(e,t)=>{xu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Xd(e,r,n,o)});function Ee(){return Rd(Bg)}var qg=_("ZodNever",(e,t)=>{bu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Yd(e,r,n,o)});function Gg(e){return Od(qg,e)}var Kg=_("ZodArray",(e,t)=>{Jt(),Eu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>nl(e,r,n,o),e.element=t.element},{min(e,t){return this.check(gt(e,t))},nonempty(e){return this.check(gt(1,e))},max(e,t){return this.check(en(e,t))},length(e,t){return this.check(tn(e,t))},unwrap(){return this.element}});function K(e,t){return Td(Kg,e,t)}var Vg=_("ZodObject",(e,t)=>{Jt(),Cu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ol(e,r,n,o),Em(e,"shape",(r)=>r._zod.def.shape,!1)},{keyof(){return ne(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(ae(this._zod.def,{catchall:e}))},passthrough(){return this.clone(ae(this._zod.def,{catchall:Ee()}))},loose(){return this.clone(ae(this._zod.def,{catchall:Ee()}))},strict(){return this.clone(ae(this._zod.def,{catchall:Gg()}))},strip(){return this.clone(ae(this._zod.def,{catchall:void 0}))},extend(e){return gm(this,e)},safeExtend(e){return ym(this,e)},merge(e){return _m(this,e)},pick(e){return pm(this,e)},omit(e){return mm(this,e)},partial(...e){return Ea(Wo,this,e[0])},exactPartial(...e){return Ea(Zl,this,e[0],"exactPartial")},required(...e){return wm(jl,this,e[0])}});function k(e,t){let r={type:"object",shape:e??{},...C(t)};return new Vg(r)}var Dl=_("ZodUnion",(e,t)=>{bo.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>sl(e,r,n,o),e.options=t.options});function on(e,t){return new Dl({type:"union",options:e,...C(t)})}var Wg=_("ZodDiscriminatedUnion",(e,t)=>{Dl.init(e,t),Ru.init(e,t)});function Ll(e,t,r){return new Wg({type:"union",options:t,discriminator:e,...C(r)})}var Jg=_("ZodIntersection",(e,t)=>{Ou.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>il(e,r,n,o)});function Yg(e,t){return new Jg({type:"intersection",left:e,right:t})}var Xg=_("ZodTuple",(e,t)=>{Jt(),Tu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>al(e,r,n,o)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map((t)=>new Wo({type:"optional",innerType:t}))})}});function Be(e,t,r){let n=t instanceof z,o=n?r:t;return new Xg({type:"tuple",items:e,rest:n?t:null,...C(o)})}var Al=_("ZodRecord",(e,t)=>{Jt(),Au.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cl(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function Ul(e,t,r){if(!t||!t._zod)return new Al({type:"record",keyType:S(),valueType:e,...C(t)});return new Al({type:"record",keyType:e,valueType:t,...C(r)})}var Vo=_("ZodEnum",(e,t)=>{$u.init(e,t),U.init(e,t),e._zod.processJSONSchema=(n,o,s)=>Qd(e,n,o,s),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=t.entries[i];else throw Error(`Key ${i} not found in enum`);return new Vo({...t,checks:[],...C(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let i of n)if(r.has(i))delete s[i];else throw Error(`Key ${i} not found in enum`);return new Vo({...t,checks:[],...C(o),entries:s})}});function ne(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new Vo({type:"enum",entries:r,...C(t)})}var Qg=_("ZodLiteral",(e,t)=>{Pu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>el(e,r,n,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 H(e,t){return new Qg({type:"literal",values:Array.isArray(e)?e:[e],...C(t)})}var ey=_("ZodTransform",(e,t)=>{Jt(),Nu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rl(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Ut(e.constructor.name);r.addIssue=(s)=>{if(typeof s==="string")r.issues.push(Qe(s,r.value,t));else{let i=s;if(i.fatal)i.continue=!1;if(i.code??(i.code="custom"),!("input"in i))i.input=r.value;i.inst??(i.inst=e),r.issues.push(Qe(i))}};let o=t.transform(r.value,r);if(o instanceof Promise)return o.then((s)=>(r.value=s,r));return r.value=o,r}});function ty(e){return new ey({type:"transform",transform:e})}var Wo=_("ZodOptional",(e,t)=>{Eo.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Go(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function $l(e){return new Wo({type:"optional",innerType:e})}var Zl=_("ZodExactOptional",(e,t)=>{zu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Go(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ry(e){return new Zl({type:"optional",innerType:e})}var ny=_("ZodNullable",(e,t)=>{Mu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ul(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Pl(e){return new ny({type:"nullable",innerType:e})}var oy=_("ZodDefault",(e,t)=>{Du.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>fl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function sy(e,t){return new oy({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():ro(t)}})}var iy=_("ZodPrefault",(e,t)=>{Lu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>hl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ay(e,t){return new iy({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():ro(t)}})}var jl=_("ZodNonOptional",(e,t)=>{Uu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>dl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function cy(e,t){return new jl({type:"nonoptional",innerType:e,...C(t)})}var uy=_("ZodCatch",(e,t)=>{Zu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>pl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function dy(e,t){return new uy({type:"catch",innerType:e,catchValue:typeof t==="function"?t:Oa(t)})}var ly=_("ZodPipe",(e,t)=>{ju.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ml(e,r,n,o),e.in=t.in,e.out=t.out});function Nl(e,t){return new ly({type:"pipe",in:e,out:t})}var fy=_("ZodReadonly",(e,t)=>{Fu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>gl(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function hy(e){return new fy({type:"readonly",innerType:e})}var py=_("ZodCustom",(e,t)=>{Hu.init(e,t),U.init(e,t),e._zod.processJSONSchema=(r,n,o)=>tl(e,r,n,o)});function my(e,t={}){return Ad(py,e,t)}function gy(e,t){return $d(e,t)}var Yo=["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"],cn=524288,ot=262144,yy=1000;function te(e){return new TextEncoder().encode(JSON.stringify(e)).length}var W=S().min(1).max(256),nt=S().min(1).max(1024),_y=S().regex(/^(0|[1-9][0-9]{0,17})$/u),un=k({epoch:W,ordinal:_y}).strict(),rt={workspaceId:W,sourceId:W,hostId:W},wt=k({address:nt,version:W,scope:W,columns:k({title:S().max(4096),state:W,owner:W.nullable(),parent:nt.nullable(),project:nt.nullable(),labels:K(W).max(256),url:S().max(2048).nullable(),updatedAt:S().max(64).nullable()}).strict(),extra:Ee()}).strict(),Xo=k({position:un,change:Ll("op",[k({op:H("upsert"),row:wt}).strict(),k({op:H("delete"),address:nt}).strict()])}).strict(),wy=k({address:nt}).strict(),Sy=k({page:S().min(1).max(4096).optional(),limit:Pe().int().min(1).max(yy)}).strict(),vy=k({address:nt,ownerMemberId:W,expectedOwner:W.nullable(),intentId:W,ifRevision:S().min(1).max(256).optional()}).strict(),xy=k({on:Yt()}).strict(),by=k({memberId:W}).strict(),sn=(e,t)=>k({...rt,caller:by,op:H(e),args:t}).strict(),Hl=Ll("op",[sn("read",wy),sn("list",Sy),sn("assign",vy),sn("watch",xy)]),Ey=k({generation:W,snapshot:W,base:un,rows:K(wt),next:S().min(1).max(4096).nullable(),complete:Yt(),progressAsOf:S().min(1).max(64).optional(),progressStale:k({since:S().min(1).max(64),reason:S().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"}),Iy=k({intentId:W,result:Ee(),observation:Xo,revision:W.nullable().optional()}).strict(),Jo={read:k({observation:Xo}).strict(),list:Ey,assign:Iy,watch:k({on:Yt()}).strict()},Fl=ne(Yo),ky=["OPERATION_NOT_ALLOWLISTED","OPERATION_SHAPE_INVALID"],an=(e)=>on([k({...rt,op:H(e),outcome:ne(["applied","noop"]),body:Jo[e]}).strict(),k({...rt,op:H(e),outcome:ne(["applied","noop"]),code:H("SOURCE_READER_RESTARTING"),body:Jo[e]}).strict(),k({...rt,op:H(e),outcome:H("rejected"),code:Fl,body:Jo[e]}).strict(),k({...rt,op:H(e),outcome:ne(["unknown","refused"]),code:on([Fl.exclude(["ITEM_TOO_LARGE"]),ne(ky)])}).strict(),k({...rt,op:H(e),outcome:H("refused"),code:H("ITEM_TOO_LARGE"),item:nt}).strict()]),Bl=on([an("read"),an("list"),an("assign"),an("watch")]),iI=k({...rt,position:un,observations:K(Xo).min(1)}).strict().refine((e)=>{let{observations:t,position:r}=e,n=t[t.length-1];if(n===void 0||n.position.epoch!==r.epoch||n.position.ordinal!==r.ordinal)return!1;return t.every((o,s)=>o.position.epoch===r.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"}),ql=k({applied:un.nullable(),seq:Pe().int().min(0),relist:Yt()}).strict();var qe="x-hh-records";var Cy=`${qe}/changed`,Ie="assign",dn="records:assign",Gl=k({address:S().min(1).max(1024),ownerMemberId:S().min(1).max(256),expectedOwner:S().min(1).max(256).nullable().optional(),ifRevision:S().min(1).max(256),intentId:S().min(1).max(256)}).strict(),Kl=S().min(1).max(256),Vl=S().min(1).max(1024),Wl=k({address:Vl,revision:S().min(1).max(256),scope:S().min(1).max(256),columns:Ul(S(),Ee()),extra:Ee().optional()}).strict(),uI=k({source:Kl,epoch:S().min(1).max(256),records:K(Wl)}).strict(),Ry=k({type:H(Cy),source:Kl,revision:S().min(1).max(256),address:Vl,deleted:H(!0).optional(),record:Wl.optional()}).strict(),dI=k({channel:S().min(1),serverSeq:Pe().int().min(0).optional(),action:Ry}),Oy=new RegExp(`^${qe}://[^/?#]+$`,"u"),Jl=(e)=>e===`${qe}://`||Oy.test(e);var Ty=k({id:S().min(1),revision:Pe().int().min(0),state:S(),operations:K(S())}).passthrough();var Qo=Pe().int().min(0),hI=k({id:S().min(1),engine:S().min(1),owner:S().min(1),name:S().min(1),description:S().optional(),tags:K(S()).optional(),model:Ee().optional(),config:Ul(S(),Ee()),ifRevision:Qo}).passthrough(),pI=k({id:S().min(1),ifRevision:Qo}).strict(),mI=k({id:S().min(1),ifRevision:Qo}).strict(),Yl=-32602,gI=k({code:H(Yl),message:S(),data:k({staleRevision:Pe().int().min(1),row:Ty})}),yI=k({code:H(Yl),message:S(),data:k({staleRevision:H(0)})});var es=["subscribe","x-ahpd/invokeOperation","resourceRead","listSessions","authenticate"],Ge="x-hh-services://",Ay=`${Ge} and ${qe}://<sourceId>`,Xl=["put","remove","start","stop","restart","accept"];var $y="hh-services://backup",Py="hh-services://changes",Ny=/^(hh-service:\/\/[^/?#]+\/logs|hh-services:\/\/(backup|changes))(\?[^#]*)?$/u;function Ql(e,t){let r=(n)=>typeof t[n]==="string"?JSON.stringify(t[n]):`no ${n}`;switch(e){case"subscribe":{let n=t.channel;if(Object.keys(t).length===1&&typeof n==="string"&&(n===Ge||Jl(n)))return;return`subscribe to ${r("channel")}${Object.keys(t).length>1?" with more than a channel":""} is not one Hightea sends; only ${Ay}`}case"x-ahpd/invokeOperation":{if(t.channel===Ge){if(typeof t.operationId==="string"&&Xl.includes(t.operationId))return;return`x-ahpd/invokeOperation ${r("operationId")} on ${Ge} is not one Hightea sends; only ${Xl.join(", ")}`}if(t.channel===`${qe}://`){if(t.operationId===Ie)return;return`x-ahpd/invokeOperation ${r("operationId")} on ${qe}:// is not one Hightea sends; only ${Ie} (${dn})`}return`x-ahpd/invokeOperation on ${r("channel")} is not one Hightea sends; only ${Ge} and ${qe}://`}case"resourceRead":if(typeof t.uri==="string"&&Ny.test(t.uri))return;return`resourceRead of ${r("uri")} is not one Hightea sends; only hh-service://<name>/logs, ${$y} and ${Py}`;case"listSessions":if(t.channel==="ahp-root://"&&Object.keys(t).length===1)return;return`listSessions on ${r("channel")}${Object.keys(t).length>1?" with more than a channel":""} is not one Hightea sends; only ahp-root://`;case"authenticate":{let n=Object.keys(t).sort().join(",");if(n!=="resource,target,token"&&n!=="expiresIn,resource,target,token")return`authenticate naming ${JSON.stringify(n)} is not one Hightea sends; only target, resource, token and expiresIn`;if(typeof t.token!=="string")return"authenticate names no token";if(typeof t.resource!=="string"||t.resource==="")return`authenticate names ${r("resource")}`;let o=t.expiresIn;if(o!==void 0&&!(typeof o==="number"&&Number.isInteger(o)&&o>0))return"authenticate's expiresIn is not a positive integer of seconds";let s=t.target;if(typeof s!=="object"||s===null||Array.isArray(s))return"authenticate names no target";let i=s;if(Object.keys(i).sort().join(",")!=="customizationId,kind,session")return"authenticate's target carries more than kind, session and customizationId";if(i.kind!=="mcpServer")return`authenticate's target kind is ${JSON.stringify(i.kind)}; only mcpServer`;if(typeof i.session!=="string"||i.session==="")return"authenticate's target names no session";if(typeof i.customizationId!=="string"||i.customizationId==="")return"authenticate's target names no server";return}default:return`${JSON.stringify(e)} is not a host-scoped method; only ${es.join(", ")}`}}var ef=["x-ahpd/agents/list","x-ahpd/agents/put","x-ahpd/agents/remove","x-ahpd/agents/enable","x-ahpd/agents/pause","x-ahpd/agents/disable",...es];function Xt(e){return es.includes(e)}var zy=1e4,Qt=zy-1000,tf="host-request:",rf="1.1.0";var nf="signed-envelopes",of="meta-routing-ids@1",ln="host-frames-slim@1";var sf=k({workspaceId:S().min(1).optional(),hostId:S().min(1).optional(),agentMemberId:S().min(1).optional(),caller:S().min(1).max(256).optional()}).strict(),My=["unmapped","timedOut","outside"],vI=k({reason:ne(My)}).strict();function af(e){if(e.ok)return{result:e.result};if(e.reason==="refused")return{error:{code:e.code,message:e.message,...e.data===void 0?{}:{data:e.data}}};return{error:{code:-32000,message:e.reason,data:{reason:e.reason}}}}var Dy=k({resource:S().min(1),customizationId:S().min(1)}).strict(),er=k({available:Yt(),reason:S().min(1).max(200).optional(),server:Dy.optional()}).strict(),st="ahpd/hostTools",xI=k({resource:S().min(1),_meta:k({"hh/agentMemberId":S().min(1),"hh/hostTools":er.optional()}).strict()}).strict(),bI=k({channel:H("ahp-root://"),session:S().min(1),changes:k({_meta:k({"hh/agentMemberId":S().min(1),"hh/hostTools":er}).strict()}).strict()}).strict();function tr(e,t,r){let n=ye(e)?e:{},o=n["hh/agentMemberId"];if(o!==void 0&&o!==t)return;let s=er.safeParse(n[st]);if(!s.success)return{"hh/agentMemberId":t};let i=s.data.available&&r!==void 0;return{"hh/agentMemberId":t,"hh/hostTools":{available:s.data.available,...s.data.reason===void 0?{}:{reason:s.data.reason},...i?{server:r}:{}}}}function cf(e,t,r){if(!ye(e)||typeof e.resource!=="string"||e.resource==="")return;let n=tr(e._meta,t,r);return n===void 0?void 0:{resource:e.resource,_meta:n}}var EI=k({channel:S().min(1),resource:S().min(1),reason:H("expired")}).strict();function ye(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var ts="event:all",uf="tool:all";var Ly=["session/ready","chat/turnStarted","chat/turnComplete","x-hh/turnFailed"];var rr=["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",...Yo],df=16,lf=49152,ff=262144,Uy=k({id:S().min(1),from:k({memberId:S().min(1)}).strict(),text:S(),replyTo:S().min(1).optional(),deleted:H(!0).optional(),signed:k({keyId:S().min(1),createdAt:S().min(1),signature:S().min(1),clientId:S().min(1),attachmentIds:K(S().min(1))}).strict().optional()}).strict(),Zy=(e)=>new TextEncoder().encode(JSON.stringify(e)).byteLength,jy=K(Uy).min(1).superRefine((e,t)=>{if(e.length>df){t.addIssue({code:"custom",message:`a wake carries at most ${df} triggering envelopes, not ${e.length}`});return}if(new Set(e.map((n)=>n.id)).size!==e.length){t.addIssue({code:"custom",message:"a wake names each triggering message once"});return}let r=0;for(let n of e){let o=Zy(n);if(o>lf){t.addIssue({code:"custom",message:`triggering envelope ${n.id} is ${o} bytes, over the ${lf}-byte limit`});return}r+=o}if(r>ff)t.addIssue({code:"custom",message:`the triggering envelopes take ${r} bytes, over the ${ff}-byte limit`})}),hf=k({workspaceId:S().min(1),deliveryId:S().min(1),turnId:S().min(1).optional(),agentMemberId:S().min(1),threadRef:S().min(1),afterMessageId:S().min(1).optional(),triggeringMessageIds:K(S().min(1)).min(1).refine((e)=>new Set(e).size===e.length).optional(),triggering:jy.optional()}).strict(),fn=k({event:ne(Ly),channel:S().min(1),workspaceId:S().min(1),deliveryId:S().min(1),session:S().min(1),chat:S().min(1),turnId:S().min(1).optional(),clientSeq:Pe().int().min(1).optional(),turnState:ne(["created","running","finished","error"]),statusCode:S().min(1).max(64),errorCode:ne(rr).optional(),errorDetail:S().max(256).optional()}).strict();function pf(e){return fn.parse(e)}var Fy=["session/ready","chat/turnStarted","chat/turnComplete","chat/turnCancelled","chat/error"],OI=k({channel:S().min(1),serverSeq:Pe().int().min(0).optional(),origin:k({clientId:S().min(1),clientSeq:Pe().int().min(1)}).optional(),action:k({type:ne(Fy),turnId:S().min(1).optional(),part:k({error:k({errorType:S().min(1)})}).optional()})});var mf="Hightea-Host",gf="x-hightea-host";import{createHash as zf}from"node:crypto";var Hy=(e,t,r)=>JSON.stringify([e,t,r]),or=/^ahp-session:\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u,By=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u,M=(e)=>({ok:!1,code:e});function nr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function it(e,t,r=[]){let n=new Set([...t,...r]);return t.every((o)=>(o in e))&&Object.keys(e).every((o)=>n.has(o))}function qy(e){let t=hf.safeParse(e._meta);return t.success?t.data:void 0}function yf(e,t){if(!nr(e)||typeof e.method!=="string")return M("OPERATION_SHAPE_INVALID");if(!it(e,["method"],["jsonrpc","id","params"]))return M("OPERATION_SHAPE_INVALID");let r=e.method;if(r!=="createSession"&&r!=="subscribe"&&r!=="dispatchAction")return M("OPERATION_NOT_ALLOWLISTED");let n=e.params;if(!nr(n))return M("OPERATION_SHAPE_INVALID");let o=qy(n);if(o===void 0)return M("OPERATION_SHAPE_INVALID");if(o.workspaceId!==t.workspaceId)return M("WORKSPACE_OR_MEMBER_UNKNOWN");let s=t.agents.get(o.agentMemberId);if(s===void 0)return M("AGENT_NOT_MAPPED");let i=Hy(o.workspaceId,o.agentMemberId,o.threadRef),a=t.sessions.get(i),{triggering:c,...d}=o,u=e.id,l={jsonrpc:"2.0",...u===void 0?{}:{id:u}},p=n.channel;if(r==="createSession"){if(!it(n,["channel","_meta"]))return M("OPERATION_SHAPE_INVALID");if(typeof p!=="string"||!or.test(p))return M("OPERATION_SHAPE_INVALID");if(a!==void 0)return M("OPERATION_SHAPE_INVALID");if(Gy(t,p))return M("FOREIGN_SESSION");return{ok:!0,operation:"createSession",frame:{...l,method:r,params:{channel:p,provider:s.provider,workingDirectories:[s.workingDirectory]}},meta:d,...c===void 0?{}:{triggering:c},sessionKey:i}}if(r==="subscribe"){if(!it(n,["channel","_meta"]))return M("OPERATION_SHAPE_INVALID");if(typeof p!=="string")return M("OPERATION_SHAPE_INVALID");if(a===void 0||a.sessionUri!==p)return M("FOREIGN_SESSION");return{ok:!0,operation:"subscribe",frame:{...l,method:r,params:{channel:p}},meta:d,...c===void 0?{}:{triggering:c},sessionKey:i}}if(!it(n,["channel","clientSeq","action","_meta"]))return M("OPERATION_SHAPE_INVALID");if(typeof n.clientSeq!=="number"||!Number.isInteger(n.clientSeq)||n.clientSeq<1)return M("OPERATION_SHAPE_INVALID");if(typeof p!=="string")return M("OPERATION_SHAPE_INVALID");if(a?.chatUri===void 0||a.chatUri!==p){if(t.parked?.has(i)===!0)return M("AGENT_NOT_MAPPED");return M("FOREIGN_SESSION")}let f=n.action;if(!nr(f)||f.type!=="chat/turnStarted")return M("OPERATION_NOT_ALLOWLISTED");if(!it(f,["type","turnId","message"],["startedAt"]))return M("OPERATION_SHAPE_INVALID");if(typeof f.turnId!=="string"||!By.test(f.turnId))return M("OPERATION_SHAPE_INVALID");if(f.startedAt!==void 0&&typeof f.startedAt!=="number")return M("OPERATION_SHAPE_INVALID");let m=f.message;if(!nr(m)||!it(m,["text","origin"])||typeof m.text!=="string")return M("OPERATION_SHAPE_INVALID");if(!nr(m.origin)||!it(m.origin,["kind"])||m.origin.kind!=="user")return M("OPERATION_SHAPE_INVALID");if(m.text!==`wake ${o.threadRef}`)return M("WAKE_TEXT_NOT_ALLOWED");return{ok:!0,operation:"dispatchAction",frame:{...l,method:r,params:{channel:p,clientSeq:n.clientSeq,action:{type:"chat/turnStarted",turnId:f.turnId,...f.startedAt===void 0?{}:{startedAt:f.startedAt},message:{text:m.text,origin:{kind:"user"}}}}},meta:d,...c===void 0?{}:{triggering:c},sessionKey:i,turnId:f.turnId}}function Gy(e,t){for(let r of e.sessions.values())if(r.sessionUri===t)return!0;return!1}import{fileURLToPath as C_}from"node:url";var Ky="host",hn=(e)=>{if(typeof e!=="object"||e===null)return;let{code:t,message:r}=e;if(typeof t!=="number"||typeof r!=="string")return;let n=e.data;return n===void 0?{code:t,message:r}:{code:t,message:r,data:n}},Vy=(e)=>e.ifRevision===0,pn=(e)=>e instanceof Error&&/timed? ?out|timeout/iu.test(e.message),_f="x-ahpd-agents://";async function Wy(e){let t,r=!1;try{let n=await e.peer.request("subscribe",{channel:Ge},Qt);r=!0;let o=typeof n==="object"&&n!==null?n.snapshot:void 0;if(t=typeof o==="object"&&o!==null?o.state:void 0,typeof t!=="object"||t===null)throw Error("hightea-pipe: the services snapshot holds no state")}catch(n){let o=hn(n);if(o!==void 0)return{ok:!1,reason:"refused",...o};if(e.log.error(`hightea-pipe: ${n instanceof Error?n.message:"the services snapshot is unreadable"}`),pn(n))return{ok:!1,reason:"timedOut"};return{ok:!1,reason:"refused",code:-32603,message:"this host could not read ahpd's services"}}finally{if(r)try{e.peer.notify("unsubscribe",{channel:Ge})}catch(n){e.log.error(`hightea-pipe: dropping the services subscription failed: ${n instanceof Error?n.name:typeof n}`)}}return{ok:!0,result:t}}function Jy(e){let t=typeof e==="object"&&e!==null?e.snapshot:void 0,r=typeof t==="object"&&t!==null?t.state:void 0,n=typeof r==="object"&&r!==null?r.records:void 0;if(!Array.isArray(n))throw Error("hightea-pipe: the agents snapshot holds no records");return n.map((o)=>{if(typeof o!=="object"||o===null)throw Error("hightea-pipe: an agents snapshot entry is not an object");let s=o;if(typeof s.record==="object"&&s.record!==null&&!Array.isArray(s.record)){if(typeof s.id!=="string")throw Error("hightea-pipe: an agents snapshot entry names no id");return{id:s.id,...s.record}}if(typeof s.id!=="string")throw Error("hightea-pipe: an agents snapshot entry names no id");return s})}async function Yy(e){let t=new Set([...e.agents.values()].map((s)=>s.provider)),r,n;try{r=await e.peer.request("subscribe",{channel:_f},Qt),n=Jy(r)}catch(s){let i=hn(s);if(i!==void 0)return{ok:!1,reason:"refused",...i};if(e.log.error(`hightea-pipe: ${s instanceof Error?s.message:"the agents snapshot is unreadable"}`),pn(s))return{ok:!1,reason:"timedOut"};return{ok:!1,reason:"refused",code:-32603,message:"this host could not read ahpd's agent list"}}let o=n.filter((s)=>typeof s.id==="string"&&t.has(s.id));o.sort((s,i)=>String(s.id)<String(i.id)?-1:String(s.id)>String(i.id)?1:0);try{e.peer.notify("unsubscribe",{channel:_f})}catch(s){e.log.error(`hightea-pipe: dropping the agents subscription failed: ${s instanceof Error?s.name:typeof s}`)}return{ok:!0,result:{rows:o}}}async function Xy(e){let t;try{t=await e.peer.request("listSessions",{channel:"ahp-root://"},Qt)}catch(i){let a=hn(i);if(a!==void 0)return{ok:!1,reason:"refused",...a};if(e.log.error(`hightea-pipe: the session list is unreadable: ${i instanceof Error?i.name:typeof i}`),pn(i))return{ok:!1,reason:"timedOut"};return{ok:!1,reason:"refused",code:-32603,message:"this host could not read ahpd's session list"}}let r=rs(t)&&Array.isArray(t.items)?t.items:void 0;if(r===void 0)return e.log.error("hightea-pipe: ahpd's listSessions result holds no items"),{ok:!1,reason:"refused",code:-32603,message:"this host could not read ahpd's session list"};let n=[],o=[];for(let i of r){let a=rs(i)&&typeof i.resource==="string"&&i.resource!==""?i.resource:void 0;if(a===void 0){o.push("a summary with no resource");continue}let c;try{c=e.memberOf(a)}catch(l){o.push(`${a}: ${l instanceof Error?l.message:String(l)}`);continue}if(c===void 0)continue;let d=cf(i,c,e.hostToolsServer(a));if(d===void 0){o.push(`${a}: its summary names another member`);continue}let u=d._meta["hh/hostTools"];if(u!==void 0)e.rememberHostTools?.(a,u);n.push(d)}let s=new Set(n.map((i)=>i.resource));for(let i of e.ownSessions?.()??[]){if(s.has(i))continue;let a=e.memberOf(i);if(a===void 0)continue;let c=e.toolsAnswerOf?.(i);if(c===void 0){o.push(`${i}: provisional, and this pipe holds no tools answer for it yet`);continue}let d=tr({[st]:c},a,e.hostToolsServer(i));if(d===void 0)continue;n.push({resource:i,_meta:d})}if(o.length>0)e.log.error(`hightea-pipe: skipped ${o.length} unreadable session row(s): ${o.join("; ").slice(0,500)}`);return{ok:!0,result:{items:n}}}async function wf(e,t){let r=e_(e.meta);if(r===void 0)return{ok:!1,reason:"outside"};let n=e.method;if(!t_(n)&&!Xt(n))return{ok:!1,reason:"outside"};let o=e.params;if(!rs(o))return{ok:!1,reason:"outside"};let s="agentMemberId"in o;if(s&&(typeof o.agentMemberId!=="string"||o.agentMemberId===""))return{ok:!1,reason:"outside"};let i=s?o.agentMemberId:r.agentMemberId;if(Xt(n)){if(i!==void 0)return{ok:!1,reason:"outside"};let u=Ql(n,o);if(u!==void 0)return t.log.error(`hightea-pipe: refused a host request: ${u}`),{ok:!1,reason:"outside"};if(n==="subscribe")return Wy(t);if(n==="listSessions")return Xy(t);if(n==="authenticate")return r_(t,o);return ns(t,n,o)}if(n==="x-ahpd/agents/list"){if(i!==void 0)return{ok:!1,reason:"outside"};if(Object.keys(o).length!==0)return{ok:!1,reason:"outside"};return Yy(t)}if(i===void 0)return{ok:!1,reason:"outside"};let a=t.agents.get(i);if(a===void 0||a.provider!==o.id)return{ok:!1,reason:"unmapped"};let c=s?Qy(o):o,d=n==="x-ahpd/agents/put"&&Vy(c)?{...c,owner:Ky}:c;return ns(t,n,d)}function Qy(e){let{agentMemberId:t,...r}=e;return r}function e_(e){let t=sf.safeParse(e);return t.success?t.data:void 0}function rs(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function t_(e){return e==="x-ahpd/agents/list"||e==="x-ahpd/agents/put"||e==="x-ahpd/agents/remove"||e==="x-ahpd/agents/enable"||e==="x-ahpd/agents/pause"||e==="x-ahpd/agents/disable"}async function r_(e,t){let r=t.target;if(typeof r.session!=="string"||e.memberOf(r.session)===void 0)return e.log.error("hightea-pipe: refused an authenticate aimed at a session this pipe did not make"),{ok:!1,reason:"outside"};let n=typeof r.session==="string"?e.hostToolsServer(r.session):void 0;if(n===void 0)return e.log.error("hightea-pipe: refused an authenticate: this host serves no Hightea MCP server, or the session has not yet said which customization is ours"),{ok:!1,reason:"outside"};if(r.customizationId!==n.customizationId)return e.log.error("hightea-pipe: refused an authenticate aimed at a server that is not this host's"),{ok:!1,reason:"outside"};if(t.resource!==n.resource)return e.log.error("hightea-pipe: refused an authenticate for a resource that is not this host's server"),{ok:!1,reason:"outside"};return ns(e,"authenticate",t)}async function ns(e,t,r){try{return{ok:!0,result:await e.peer.request(t,r,Qt)??null}}catch(n){let o=hn(n);if(o!==void 0)return{ok:!1,reason:"refused",...o};return e.log.error(`hightea-pipe: host request ${t} ended without an answer`+(pn(n)?" (timed out)":"")+`: ${n instanceof Error?n.name:typeof n}`),{ok:!1,reason:"timedOut"}}}import{createPrivateKey as m_,createPublicKey as g_,generateKeyPairSync as y_,sign as __}from"node:crypto";import{appendFile as w_,chmod as S_,readFile as If,rename as kf,writeFile as Cf}from"node:fs/promises";import{join as is}from"node:path";function n_(e){return JSON.stringify({v:1,workspaceId:e.workspaceId,roomId:e.roomId,rootMessageId:e.rootMessageId,authorMemberId:e.authorMemberId,clientId:e.clientId,body:e.body,attachmentIds:[...e.attachmentIds],createdAt:e.createdAt})}function mn(e){return new TextEncoder().encode(n_(e))}import{createPublicKey as o_,verify as s_}from"node:crypto";var i_=Buffer.from("302a300506032b6570032100","hex");function os(e,t){let r=e.signed;if(r===void 0)return{ok:!1,code:"ASK_UNSIGNED",why:`message ${e.id} carries no signature`};let n=t.keys.find((a)=>a.keyId===r.keyId);if(n===void 0)return{ok:!1,code:"ROOM_ASKS_UNTRUSTED",why:`message ${e.id} is signed by key ${r.keyId}, which this host does not trust yet; its owner approves that browser with \`hightea approve\` and the ask goes through`};let o=mn({workspaceId:t.workspaceId,roomId:t.roomId,rootMessageId:e.replyTo??null,authorMemberId:e.from.memberId,clientId:r.clientId,body:e.text,attachmentIds:r.attachmentIds,createdAt:r.createdAt}),s=Buffer.from(r.signature,"base64url"),i=o_({key:Buffer.concat([i_,Buffer.from(n.publicKey,"base64url")]),format:"der",type:"spki"});if(s.length!==64||!s_(null,o,i,s))return{ok:!1,code:"ASK_UNSIGNED",why:`message ${e.id}'s signature by ${n.name} does not match what the room returned (text, thread, author ${e.from.memberId}, or attachments)`};if(t.ownKeyId!==void 0&&n.keyId===t.ownKeyId&&!t.ownAgents.has(e.from.memberId))return{ok:!1,code:"KEY_NOT_FOR_AUTHOR",why:`message ${e.id} is signed by this host's key but attributed to ${e.from.memberId}, which this host does not run`};return{ok:!0,keyName:n.name,clientId:r.clientId,createdAt:r.createdAt}}function Sf(e,t){let r=(a)=>a.deleted===!0?{id:a.id,deleted:!0}:a,n=(a)=>a.deleted===!0||os(a,t).ok,o=n(e.root),s=e.replies.filter(n).map(r),i=(o?0:1)+e.replies.length-e.replies.filter(n).length;return{...e,root:o?r(e.root):{id:e.root.id,omitted:!0},replies:s,...i===0?{}:{omitted:`${String(i)} unsigned messages omitted`}}}import{createHash as a_}from"node:crypto";import{existsSync as c_,readFileSync as u_}from"node:fs";import{join as d_}from"node:path";var l_="trusted-keys.json",f_=/^(?=.{1,64}$)[A-Za-z0-9][A-Za-z0-9._-]*(?: [A-Za-z0-9._-]+)*$/u,h_=/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/u,p_=(e)=>Buffer.from(e).toString("base64url");function ss(e){if(!h_.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:p_(a_("sha256").update(Buffer.from(e,"base64url")).digest())}}function vf(e){let t=d_(e,l_);if(!c_(t))return{state:"missing",file:t};let r;try{r=JSON.parse(u_(t,"utf8"))}catch(o){throw Error(`TRUST_FILE_UNREADABLE: ${t} is not JSON (${o.message})`)}let n=r;if(typeof r!=="object"||r===null||n.v!==1||!Array.isArray(n.keys))throw Error(`TRUST_FILE_UNREADABLE: ${t} is not a version 1 list of trusted keys`);for(let o of n.keys){let s=o,i=typeof s.publicKey==="string"?ss(s.publicKey):void 0;if(typeof s.name!=="string"||!f_.test(s.name)||i===void 0||"error"in i||s.keyId!==i.keyId||typeof s.addedAt!=="string")throw Error(`TRUST_FILE_UNREADABLE: ${t} holds an entry that is not a valid trusted key: ${JSON.stringify(o)}`)}return{state:"read",file:t,keys:n.keys}}class Z extends Error{code;constructor(e,t){super(`${e}: ${t}`);this.code=e}}var v_="host-signing-key",xf="hightea-acted-asks.jsonl",gn=600000,x_=2592000000,b_=20;async function Rf(e,t=()=>Date.now()){let r=is(e,v_),n;try{n=await If(r,"utf8")}catch(a){if(a.code!=="ENOENT")throw Error(`HOST_KEY_UNREADABLE: ${r} exists but cannot be read (${String(a)}); it is never regenerated, fix or remove it by hand`)}if(n===void 0){let a=y_("ed25519").privateKey.export({format:"pem",type:"pkcs8"}).toString(),c=`${r}.${String(process.pid)}.tmp`;await Cf(c,a,{mode:384,flag:"wx"}),await S_(c,384),await kf(c,r),n=a}let o;try{if(o=m_({key:n,format:"pem"}),o.asymmetricKeyType!=="ed25519")throw Error(`a ${String(o.asymmetricKeyType)} key, not Ed25519`)}catch(a){throw Error(`HOST_KEY_UNREADABLE: ${r} is not an Ed25519 PKCS8 key (${String(a)}); it is never regenerated, fix or remove it by hand`)}let s=g_(o).export({format:"jwk"}).x,i=s===void 0?{error:"no public key"}:ss(s);if("error"in i)throw Error(`HOST_KEY_UNREADABLE: ${r}: ${i.error}`);return{privateKey:o,trusted:{name:"this-host",keyId:i.keyId,publicKey:s,addedAt:new Date(t()).toISOString()}}}function Of(e,t,r=()=>Date.now()){let n=new Date(r()).toISOString(),o=mn({...t,attachmentIds:[],createdAt:n});return{keyId:e.trusted.keyId,createdAt:n,signature:__(null,o,e.privateKey).toString("base64url")}}async function bf(e,t){if(e.configDir===void 0)throw new Z("ROOM_ASKS_UNTRUSTED","this host's ahpd is too old for signed asks (it names no configDir)");let r=await e.hostKey;if(r instanceof Error)throw new Z("ROOM_ASKS_UNTRUSTED",r.message);let n;try{let s=await vf(e.configDir);n=s.state==="read"?s.keys:[]}catch(s){throw new Z("ROOM_ASKS_UNTRUSTED",String(s instanceof Error?s.message:s))}if(n.length===0)throw new Z("ROOM_ASKS_UNTRUSTED","this host trusts no key yet; its owner runs `hightea host trust add`");let o=r?.trusted;return{workspaceId:e.workspaceId,roomId:t,keys:o===void 0||n.some((s)=>s.keyId===o.keyId)?n:[...n,o],...o===void 0?{}:{ownKeyId:o.keyId},ownAgents:e.ownAgents}}function Ef(e){let[t,r,n]=e.split("/");if(!t||!r||n!==void 0)throw new Z("ASK_UNSIGNED",`the wake's thread ref ${e} names no room thread`);return{roomId:t,rootMessageId:r}}function E_(e,t,r){if(t===void 0||t==="")throw new Z("ASK_UNSIGNED",`wake ${r.deliveryId} carries no signed envelopes and this caller has no bearer to read its thread with`);return t}function I_(e,t,r,n){let o=new Map;for(let i of e){let a=i.replyTo??i.id;if(a!==r)throw new Z("ASK_UNSIGNED",`wake ${n.deliveryId} carries message ${i.id} from thread ${a}, not ${n.threadRef}`);o.set(i.id,{id:i.id,from:{memberId:i.from.memberId},text:i.text,...i.replyTo===void 0?{}:{replyTo:i.replyTo},...i.deleted===void 0?{}:{deleted:!0},...i.signed===void 0?{}:{signed:i.signed}})}let s=new Set(o.keys());if(s.size!==t.length||t.some((i)=>!s.has(i)))throw new Z("ASK_UNSIGNED",`wake ${n.deliveryId} froze ${t.length} triggering messages and carried ${s.size}, not the same ones`);return o}class sr{#e;#o;#r=Promise.resolve();constructor(e){this.#e=e}async admit(e,t){let{roomId:r,rootMessageId:n}=Ef(e.threadRef),o=await bf(this.#e,r),s=e.triggering,i=s===void 0?e.triggeringMessageIds:s.map((l)=>l.id);if(i===void 0||i.length===0)throw new Z("ASK_UNSIGNED",`wake ${e.deliveryId} names no triggering message to check`);let a=s===void 0?await this.#s(E_(this.#e,t,e),r,n,e.afterMessageId,new Set(i)):I_(s,i,n,e),c=(this.#e.now??Date.now)(),d=await this.#n(c),u=[];for(let l of i){let p=a.get(l);if(p===void 0)throw new Z("ASK_UNSIGNED",`triggering message ${l} is not in thread ${e.threadRef}`);let f=os(p,o);if(!f.ok)throw new Z(f.code,f.why);let m=d.filter((g)=>g.clientId===f.clientId);if(m.some((g)=>g.deliveryId!==e.deliveryId))throw new Z("ASK_REPLAYED",`the ask signed as ${f.clientId} (message ${l}) was already acted on under another wake`);if(m.length>0){let g=Math.min(...m.map((w)=>w.at));if(c-g>gn)throw new Z("ASK_REPLAYED",`wake ${e.deliveryId} was first admitted at ${new Date(g).toISOString()}, more than 10 minutes ago; a new attempt of it is not admitted`);continue}let y=Date.parse(f.createdAt);if(!Number.isFinite(y)||Math.abs(c-y)>gn)throw new Z("ASK_STALE",`message ${l} was signed at ${f.createdAt}, more than 10 minutes from this host's clock`);u.push({clientId:f.clientId,deliveryId:e.deliveryId,at:c})}if(u.length>0)await this.#c(d,u)}async view(e,t){return Sf(t,await bf(this.#e,Ef(e).roomId))}async#s(e,t,r,n,o){let s=new Map,i=n??r;for(let a=0;a<b_;a++){let c=await this.#e.readThread(e,{roomId:t,messageId:r,after:i});if(!k_(c))throw new Z("ASK_UNSIGNED",`thread_read answered no root and replies for ${t}/${r}`);for(let u of[c.root,...c.replies])if(o.has(u.id))s.set(u.id,u);let d=c.replies.at(-1);if(s.size===o.size||c.more!==!0||d===void 0)break;i=d.id}return s}async#n(e){this.#o??=(async()=>{let r=is(this.#e.configDir,xf),n="";try{n=await If(r,"utf8")}catch(i){if(i.code!=="ENOENT")throw new Z("ROOM_ASKS_UNTRUSTED",`${r} cannot be read: ${String(i)}`)}let o=[];for(let[i,a]of n.split(`
|
|
64
64
|
`).entries()){if(a.trim()==="")continue;let c=JSON.parse(a);if(typeof c.clientId!=="string"||typeof c.deliveryId!=="string"||typeof c.at!=="number")throw new Z("ROOM_ASKS_UNTRUSTED",`${r} line ${String(i+1)} is not an acted ask; fix or remove the file by hand`);o.push(c)}let s=o.filter((i)=>e-i.at<x_);if(s.length<o.length)await this.#d(r,s);return s})();let t=this.#o;return t.catch(()=>{if(this.#o===t)this.#o=void 0}),t}async#d(e,t){let r=`${e}.${String(process.pid)}.tmp`;await Cf(r,t.map((n)=>`${JSON.stringify(n)}
|
|
65
65
|
`).join(""),{mode:384}),await kf(r,e)}async#c(e,t){e.push(...t);let r=is(this.#e.configDir,xf),n=this.#r.then(()=>w_(r,t.map((o)=>`${JSON.stringify(o)}
|
|
66
66
|
`).join(""),{mode:384}));this.#r=n.catch(()=>{return}),await n}}function k_(e){if(e===null||typeof e!=="object")return!1;let t=e,r=(n)=>n!==null&&typeof n==="object"&&typeof n.id==="string";return r(t.root)&&Array.isArray(t.replies)&&t.replies.every(r)}class vt extends Error{}class us extends Error{}function R_(e,t){if(!ef.includes(e))return!1;return!Xt(e)||typeof t==="string"&&t.startsWith(tf)}function O_(e){let t=e.params.clientSeq;if(typeof t!=="number"||!Number.isInteger(t)||t<1)throw new us("ahp-host: a dispatch names no clientSeq");return t}var T_=[/No agent provider registered for: /u,/: this conversation has no matching configured ACP process authority/u];function Tf(e){if(e instanceof Z)return e.code;if(e instanceof us)return"OPERATION_SHAPE_INVALID";if(e instanceof vt)return"AGENT_NOT_MAPPED";let t=e instanceof Error?e.message:String(e);if(T_.some((r)=>r.test(t)))return"AGENT_NOT_MAPPED";return"WAKE_NOT_SENT"}var St=rf,as=15000,A_="x-hh/actions";function $_(e,t={}){let r=t.startedAtMs??Date.now(),n=Math.max(0,Date.now()-r),o=e.turnId===void 0||e.turnId===""?{}:{turnId:e.turnId};if(e.event==="session/ready")return{channel:e.session,action:{type:"session/ready",...o}};if(e.event==="chat/turnStarted")return{channel:e.chat,action:{type:"chat/turnStarted",...o,startedAt:new Date(r).toISOString()},...e.clientSeq===void 0?{}:{origin:{clientId:t.clientId??"hightea-gateway",clientSeq:e.clientSeq}}};if(e.event==="chat/turnComplete")return{channel:e.chat,action:{type:"chat/turnComplete",...o,duration:n}};let s=e.errorCode??"OPERATION_SHAPE_INVALID";if(s==="TURN_CANCELLED")return{channel:e.chat,action:{type:"chat/turnCancelled",...o,duration:n}};return{channel:e.chat,action:{type:"chat/error",...o,duration:n,part:{kind:"error",error:{errorType:s,message:""}}}}}var ir=(e,t)=>JSON.stringify([e,t]);function P_(e){let t;for(let r of e.triggering??[]){let n=r.signed===void 0?Number.NaN:Date.parse(r.signed.createdAt);if(!Number.isFinite(n))continue;if(t===void 0||n>t)t=n}return t}var ak=k({sessions:K(Be([S().min(1),k({sessionUri:S().min(1),chatUri:S().min(1).optional()}).strict()])),dispatched:K(Be([S().min(1),K(S().min(1))])),lastStatus:K(Be([S().min(1),fn]))}).strict(),N_=k({event:ne(["session.created","turn.started","turn.finished","turn.error"]),houseId:S().min(1),deliveryId:S().min(1),sessionId:S().min(1),chatId:S().min(1),turnId:S().min(1).optional(),turnState:ne(["created","running","finished","error"]),statusCode:S().min(1).max(64),errorCode:ne(rr).optional(),errorDetail:S().max(256).optional()}).strict(),z_={"session.created":"session/ready","turn.started":"chat/turnStarted","turn.finished":"chat/turnComplete","turn.error":"x-hh/turnFailed"};function M_(e){return{event:z_[e.event],channel:e.event==="session.created"?e.sessionId:e.chatId,workspaceId:e.houseId,deliveryId:e.deliveryId,session:e.sessionId,chat:e.chatId,...e.turnId===void 0?{}:{turnId:e.turnId},turnState:e.turnState,statusCode:e.statusCode,...e.errorCode===void 0?{}:{errorCode:e.errorCode},...e.errorDetail===void 0?{}:{errorDetail:e.errorDetail}}}var D_=k({sessions:K(Be([S().min(1),k({sessionUri:S().min(1),chatUri:S().min(1).optional()}).strict()])),dispatched:K(Be([S().min(1),K(S().min(1))])),lastStatus:K(Ee())}).strict(),L_=(e)=>e.turnId===void 0?e.deliveryId:ir(e.deliveryId,e.turnId);function cs(e){return`${e.issues.slice(0,3).map((r)=>`${r.path.join(".")||"(record)"} ${r.message}`).join("; ")}${e.issues.length>3?`; and ${e.issues.length-3} more`:""}`}function Af(e){let t=Array.isArray(e)?e[1]:e;if(typeof t==="object"&&t!==null){let r=t.event;if(typeof r==="string")return`event=${r}`}return Array.isArray(e)?`a frame of ${typeof t}`:`${e===null?"null":typeof e}`}function ds(e,t){let r=D_.safeParse(e);if(!r.success)throw Error(`ahp-host: invalid durable state: ${cs(r.error)}`);let n=[],o=0,s=0;if(r.data.lastStatus.forEach((a,c)=>{let d=Be([S().min(1),Ee()]).safeParse(a),u=d.success?d.data[0]:"",l=d.success?fn.safeParse(d.data[1]):void 0,p=d.success&&l?.success===!1?N_.safeParse(d.data[1]):void 0,f=l?.success===!0?l.data:p?.success===!0?M_(p.data):void 0;if(f===void 0){s+=1;let m=d.success&&typeof d.data[1]==="object"&&d.data[1]!==null&&"houseId"in d.data[1],y=p?.success===!1&&m?`pre-0.1.11 shape: ${cs(p.error)}`:l?.success===!1?cs(l.error):"not a [key, frame] entry";t.error(`ahp-host: dropped durable status frame lastStatus[${c}] (${Af(a)}): ${y}`);return}if(L_(f)!==u){s+=1,t.error(`ahp-host: dropped durable status frame lastStatus[${c}] (event=${f.event}): its key names a different delivery or turn`);return}if(l?.success!==!0)o+=1,t.error(`ahp-host: upgraded durable status frame lastStatus[${c}] (${Af(a)} -> event=${f.event}) from the pre-0.1.11 shape`);n.push([u,f])}),o>0||s>0)t.error(`ahp-host: durable state repaired: ${o} status frame(s) upgraded from the pre-0.1.11 shape, ${s} dropped; the pipe starts and rewrites the state`);return{sessions:r.data.sessions.map(([a,c])=>[a,{sessionUri:c.sessionUri,...c.chatUri===void 0?{}:{chatUri:c.chatUri}}]),dispatched:r.data.dispatched,lastStatus:n}}class ls{#e=new Map;#o=new Map;#r=new Map;#s=[];#n=new Map;#d=new Set;#c=new Map;#l=new Map;#u=new Map;#f=new Map;#a=new Map;#g=Promise.resolve();#h;#y=!1;#w=0;#v=0;#S=!1;#m="";peer;cloud;options;constructor(e,t,r){this.peer=e,this.cloud=t,this.options=r,e.onMessage((n)=>{this.#p(n).catch((o)=>{if(o!==this.#h)this.options.log.error(`ahp-host: local turn handling failed: ${String(o)}`)})})}get registry(){return{workspaceId:this.options.workspaceId,agents:this.options.agents,sessions:this.#e,parked:this.#l}}agentMemberOf(e){for(let[t,r]of this.#e){if(r.sessionUri!==e)continue;let n;try{n=JSON.parse(t)}catch(o){throw Error(`ahp-host: session key ${t} of ${e} is not a session key: ${String(o)}`)}if(!Array.isArray(n)||typeof n[1]!=="string"||n[1]==="")throw Error(`ahp-host: session key ${t} of ${e} names no member`);return n[1]}return}async start(e){this.#y=!1;let t=await this.peer.request("initialize",{channel:"ahp-root://",protocolVersions:[St],clientId:e},as);if(t?.protocolVersion!==St)throw Error(`ahp-host: the local ahpd answered protocol ${String(t?.protocolVersion)}, not ${St}`);let r=await this.options.store?.load();if(r===void 0){this.#x();return}let n=ds(r,this.options.log);for(let[a,c]of n.sessions){if(c.chatUri!==void 0){this.#e.set(a,{sessionUri:c.sessionUri,chatUri:c.chatUri});continue}let d;try{d=await this.#N(c.sessionUri)}catch(u){if(Tf(u)==="AGENT_NOT_MAPPED"){this.#k(a,c.sessionUri,u);continue}throw u}this.#d.delete(c.sessionUri),this.peer.notify("unsubscribe",{channel:c.sessionUri}),this.#e.set(a,{sessionUri:c.sessionUri,chatUri:d})}let o=[],s=this.#e,i=new Map(n.lastStatus);for(let[a,c]of n.dispatched)for(let d of c){let u;try{u=Be([S().min(1),S().min(1)]).parse(JSON.parse(d))}catch{throw Error("ahp-host: invalid durable state attempt")}let[l,p]=u,f=i.get(d);if(f!==void 0&&(f.deliveryId!==l||f.turnId!==p))throw Error("ahp-host: invalid durable state attempt status");if(f?.event==="chat/turnComplete"||f?.event==="x-hh/turnFailed")continue;let m=s.get(a);if(m?.chatUri===void 0)throw Error("ahp-host: invalid durable state attempt session");o.push({event:"x-hh/turnFailed",workspaceId:this.options.workspaceId,deliveryId:l,turnId:p,channel:m.chatUri,session:m.sessionUri,chat:m.chatUri,turnState:"error",statusCode:"HOST_RESTARTED",errorCode:"HOST_RESTARTED"})}for(let[a,c]of n.dispatched)this.#o.set(a,new Set(c));for(let[a,c]of n.lastStatus)this.#a.set(a,c);for(let a of o)await this.#t(a);await this.#b(),this.#x()}#x(){this.#y=!0;for(let e of this.#s.splice(0))this.#O(e)}#k(e,t,r){let n=r instanceof Error?r.message:String(r);this.#l.set(e,n),this.#e.set(e,{sessionUri:t}),this.options.log.error(`hightea-pipe: saved session ${t} is parked: ahpd will not resume it and its agent is not mapped (AGENT_NOT_MAPPED), so its wakes are refused by name; every other agent on this host carries on: ${n}`)}#R(e,t){if(!(typeof t==="object"&&t!==null&&Array.isArray(t.protocolVersions)?t.protocolVersions.filter((s)=>typeof s==="string"):[]).includes(St)){this.cloud.reply(e,{error:{code:-32005,message:"UnsupportedProtocolVersion",data:{supportedVersions:[St]}}});return}let n=t._meta;if(typeof n==="object"&&n!==null&&n[A_]===!0)this.#S=!0;let o=t.clientId;if(typeof o==="string"&&o!=="")this.#m=o;if(!this.#y){this.#s.push(e);return}this.#O(e)}#O(e){let t=this.options.handshake,r=t?.sources?.(),n=t?.capabilities?.filter((s)=>s!==ln||this.#S),o={...t===void 0?{}:{ahpd:t.ahpd},...n===void 0||n.length===0?{}:{capabilities:n},...r===void 0||r.length===0?{}:{sources:r}};this.cloud.reply(e,{result:{protocolVersion:St,serverSeq:0,...t?.plugin===void 0?{}:{serverInfo:t.plugin},...Object.keys(o).length===0?{}:{_meta:o},snapshots:[]}})}#b(){let e={sessions:[...this.#e],dispatched:[...this.#o].map(([t,r])=>[t,[...r]]),lastStatus:[...this.#a]};return this.#g=this.#g.then(()=>this.options.store?.save(e)).catch((t)=>{if(this.#h===void 0){this.#h=Error("ahp-host: durable state write failed",{cause:t});for(let r of this.#r.values())r.cancelled=!0;this.options.log.error(`${this.#h.message}: ${String(t)}`)}throw this.#h}),this.#g}async#U(e,t){if(!(typeof t==="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).sort().join(",")==="agentMemberId,workspaceId"&&t.workspaceId===this.options.workspaceId&&typeof t.agentMemberId==="string")){if(e!==void 0)this.cloud.answer(e,{ok:!1,code:"OPERATION_SHAPE_INVALID"});return}let n=t.agentMemberId;for(let s of this.#r.values())if(s.workspaceId===this.options.workspaceId&&s.agentMemberId===n)s.cancelled=!0;let o=[];for(let[s,i]of this.#n){let a=i.filter((d)=>d.meta.agentMemberId!==n),c=this.#e.get(s);for(let d of i.filter((u)=>u.meta.agentMemberId===n))o.push(this.#t({event:"x-hh/turnFailed",workspaceId:d.meta.workspaceId,deliveryId:d.meta.deliveryId,channel:c?.chatUri??"",session:c?.sessionUri??"",chat:c?.chatUri??"",turnId:d.turnId,turnState:"error",statusCode:"GRANT_REVOKED",errorCode:"TOKEN_EXPIRED_OR_REVOKED"}));this.#n.set(s,a)}if(await Promise.all(o),e!==void 0)this.cloud.answer(e,{ok:!0})}async fromCloud(e){let t=e?.id;if(e?.method==="initialize"){if(t===void 0){this.options.log.error("hightea-pipe: an initialize frame carries no id; nothing to answer");return}this.#R(t,e.params);return}if(!this.#y||this.#h!==void 0){if(t!==void 0)this.cloud.answer(t,{ok:!1,code:"WAKE_NOT_SENT"});return}let r=typeof e?.method==="string"?e.method:void 0;if(r!==void 0&&R_(r,t)){let o=String(t??""),s=await wf({method:r,params:e.params,meta:e._meta},{agents:this.options.agents,memberOf:(i)=>this.agentMemberOf(i),peer:this.peer,log:this.options.log,hostToolsServer:(i)=>this.#E(i),rememberHostTools:(i,a)=>this.#f.set(i,a),ownSessions:()=>[...this.#e.values()].map((i)=>i.sessionUri),toolsAnswerOf:(i)=>this.#f.get(i)});this.cloud.hostRequestAnswer(o,s);return}if(e?.method==="x-hightea/revoke")return this.#U(t,e.params).catch(()=>{if(t!==void 0)this.cloud.answer(t,{ok:!1,code:"OPERATION_SHAPE_INVALID"})});let n=yf(e,this.registry);if(!n.ok){if(n.code==="WAKE_TEXT_NOT_ALLOWED")this.options.log.error(`hightea: refused turn ${String(t??"")}: its text is not the delivery's own wake (WAKE_TEXT_NOT_ALLOWED); nothing reached the agent`);if(t===void 0){let o=e?.params?._meta,s=typeof o?.deliveryId==="string"?o.deliveryId:"unknown";this.options.log.error(`hightea-pipe: refused ${String(e.method)} for delivery ${s}: ${n.code}; nothing reached the agent`)}else this.cloud.answer(t,n);return}try{let o;if(n.operation==="createSession"){let s=this.options.agents.get(n.meta.agentMemberId);if(s===void 0)throw new vt("ahp-host: local agent mapping disappeared");let i,a;try{a=await this.options.startSession({owner:this.options.owner,provider:s.provider,workingDirectory:C_(s.workingDirectory),tools:this.options.tools,...s.settings===void 0?{}:{config:s.settings}},async(d)=>{if(this.options.store?.reserve!==void 0){let u=await this.options.store.reserve(n.sessionKey,d);if(this.#e.set(n.sessionKey,{sessionUri:u}),u!==d)throw i=u,Error("ahp-host: durable session mapping already won by an existing URI");await this.#b();return}this.#e.set(n.sessionKey,{sessionUri:d}),await this.#b()})}catch(d){if(i===void 0)throw d;a=i}if(this.#e.get(n.sessionKey)?.sessionUri!==a)throw Error("ahp-host: created session differs from its durable reservation");let c=i!==void 0?await this.#N(a):await this.#Z(a);this.#e.set(n.sessionKey,{sessionUri:a,chatUri:c}),this.#c.set(a,Promise.resolve()),await this.#b(),await this.#t({event:"session/ready",workspaceId:n.meta.workspaceId,deliveryId:n.meta.deliveryId,...n.meta.turnId===void 0?{}:{turnId:n.meta.turnId},channel:c,session:a,chat:c,turnState:"created",statusCode:"SESSION_CREATED"})}else if(n.operation==="subscribe"){let s=n.frame.params.channel,i=this.#e.get(n.sessionKey);if(i?.sessionUri!==s||i.chatUri===void 0)throw Error("ahp-host: a subscribe reached a session this host has no chat for");o={snapshot:{resource:s,state:{defaultChat:i.chatUri}}}}else await this.#T(n.sessionKey,n.frame,{...n.meta,...n.triggering===void 0?{}:{triggering:n.triggering}},n.turnId);if(t!==void 0)if(o===void 0)this.cloud.answer(t,{ok:!0});else this.cloud.reply(t,{result:o})}catch(o){let s=Tf(o);if(this.options.log.error(`ahp-host: cloud operation ${n.operation} failed (${s}): ${String(o)}`),t!==void 0)this.cloud.answer(t,{ok:!1,code:s})}}async#P(e,t){let r=this.#c.get(e);if(r===void 0)r=this.#N(e).then((n)=>{if(n!==t)throw Error("ahp-host: saved session answered a different chat")}),this.#c.set(e,r),r.catch(()=>{if(this.#c.get(e)===r)this.#c.delete(e)});await r}async#N(e){let t=await this.options.startSession({owner:this.options.owner,resume:e});if(t!==e)throw Error(`ahp-host: resumed session ${t} differs from ${e}`);return this.#Z(e)}async#Z(e){let t=await this.peer.request("subscribe",{channel:e},as);this.#d.add(e),this.#F(e,t?.snapshot?.state?.customizations),this.#H(e,t?.snapshot?.state);let r=t?.snapshot?.state?.defaultChat;if(typeof r!=="string"||r.length===0)throw Error(`ahp-host: ${e} answered no defaultChat`);return r}async#T(e,t,r,n){let o=this.#e.get(e);if(o?.chatUri===void 0||n===void 0)throw Error("ahp-host: a turn reached dispatch without its mapping or turn id");let s=this.#o.get(e)??new Set,i=ir(r.deliveryId,n);if(s.has(i)){let c=this.#a.get(i);if(await this.#g,c!==void 0)this.#D(c);return}if(this.options.admitTurn!==void 0)await this.options.admitTurn(r);await this.#P(o.sessionUri,o.chatUri);let a=this.#r.get(e);if(a!==void 0){if(a.deliveryId===r.deliveryId)a.cancelled=!0;let c=this.#n.get(e)??[];for(let u of c)if(u.meta.deliveryId===r.deliveryId&&u.turnId!==n)s.add(ir(u.meta.deliveryId,u.turnId));s.add(i),this.#o.set(e,s);let d=c.filter((u)=>u.meta.deliveryId!==r.deliveryId||u.turnId===n);if(!d.some((u)=>u.meta.deliveryId===r.deliveryId))d.push({frame:t,meta:r,turnId:n});this.#n.set(e,d),await this.#b();return}await this.#C(e,t,r,n)}async#C(e,t,r,n){let o=this.#e.get(e);if(o?.chatUri===void 0)throw Error("ahp-host: dispatch has no mapped chat");if(this.#A(o.sessionUri,o.chatUri).length>0)throw Error("ahp-host: wake already active for this session and chat");let s={key:e,deliveryId:r.deliveryId,workspaceId:r.workspaceId,agentMemberId:r.agentMemberId,sessionUri:o.sessionUri,chatUri:o.chatUri,turnId:n,startedAtMs:Date.now(),clientSeq:O_(t),cancelled:!1,stopReason:void 0,finishing:!1},i=this.#o.get(e)??new Set;if(i.add(ir(r.deliveryId,n)),this.#o.set(e,i),this.#r.set(e,s),await this.#b(),s.cancelled){this.#r.delete(e),await this.#t({event:"x-hh/turnFailed",workspaceId:r.workspaceId,deliveryId:r.deliveryId,channel:o.chatUri,session:o.sessionUri,chat:o.chatUri,turnId:n,turnState:"error",statusCode:"QUEUED_WAKE_NOT_RUN",errorCode:"TOKEN_EXPIRED_OR_REVOKED"}),await this.#M(s);return}if(!this.#d.has(o.chatUri))this.#d.add(o.chatUri),this.peer.request("subscribe",{channel:o.chatUri},as);this.peer.notify("dispatchAction",{...t.params,clientSeq:++this.#w})}#A(e,t){return[...this.#r.values()].filter((r)=>r.sessionUri===e&&r.chatUri===t)}#_(e){this.#B(e)}#j(e,t){let r=this.#E(e);if(r===void 0||t.id!==r.customizationId)return;if(e===""||this.agentMemberOf(e)===void 0)return;let n=ye(t.state)?t.state:void 0;if(n?.kind!=="authRequired"||n.reason!=="expired")return;this.cloud.authRequired({channel:e,resource:r.resource,reason:"expired"})}#E(e){let t=this.options.hostTools;if(t===void 0)return;let r=this.#u.get(e);return r===void 0?void 0:{resource:t.resource,customizationId:r}}#F(e,t){let r=this.options.hostTools;if(r===void 0||!Array.isArray(t))return;let n=t.find((s)=>ye(s)&&s.type==="mcpServer"&&s.name===r.name),o=n!==void 0&&typeof n.id==="string"&&n.id!==""?n.id:void 0;if(o===void 0)this.#u.delete(e);else this.#u.set(e,o);if(o===void 0)this.#f.set(e,{available:!1,reason:"its backend published no Hightea MCP server"});else this.#f.set(e,{available:!0})}#H(e,t){if(this.options.hostTools===void 0)return;let r=ye(t)?ye(t._meta)?t._meta:t:void 0,n=er.safeParse(r?.[st]);if(n.success)this.#f.set(e,n.data)}#z(e){let t=this.agentMemberOf(e),r=this.#f.get(e);if(t===void 0||r===void 0)return;let n=this.#E(e),o={available:r.available,...r.reason===void 0?{}:{reason:r.reason},...r.available&&n!==void 0?{server:n}:{}};this.cloud.sessionChanged({channel:"ahp-root://",session:e,changes:{_meta:{"hh/agentMemberId":t,"hh/hostTools":o}}})}#B(e){if(!ye(e)){this.options.log.error("hightea-pipe: a root/sessionSummaryChanged carries no params object");return}let t=e.session;if(typeof t!=="string"||t===""){this.options.log.error("hightea-pipe: a root/sessionSummaryChanged names no session");return}let r=this.agentMemberOf(t);if(r===void 0)return;let n=ye(e.changes)?e.changes:void 0,o=n!==void 0&&ye(n._meta)?n._meta:void 0,s=tr(o,r,this.#E(t));if(s===void 0){this.options.log.error(`hightea-pipe: ${t} changed under another member's name; nothing was sent`);return}let i=s["hh/hostTools"];if(i===void 0){if(o?.[st]!==void 0)this.options.log.error(`hightea-pipe: ${t} changed ${st} to a shape this host does not read`);return}this.#f.set(t,i),this.cloud.sessionChanged({channel:"ahp-root://",session:t,changes:{_meta:{"hh/agentMemberId":s["hh/agentMemberId"],"hh/hostTools":i}}})}async#p(e){let t=e?.params;if(t?.action?.type==="session/customizationsChanged"){if(typeof t.channel==="string"&&this.agentMemberOf(t.channel)!==void 0){let i=this.#u.get(t.channel);if(this.#F(t.channel,t.action.customizations),this.#u.get(t.channel)!==i)this.#z(t.channel)}return}if(t?.action?.type==="session/mcpServerStateChanged"){this.#j(typeof t.channel==="string"?t.channel:"",t.action);return}if(ye(e)&&e.method==="root/sessionSummaryChanged")return this.#_(e.params);let r=e?.params,n=r?.action;if(n===void 0||typeof r?.channel!=="string")return;if(n.type==="session/inputNeededSet"){let i=n.request,a=i?.kind==="toolConfirmation"&&i.toolCall?.status==="pending-confirmation",c=i?.kind==="chatInput";if(!a&&!c)return;let d=typeof i.request?.id==="string"&&i.request.id!==""?i.request.id:typeof i.id==="string"&&i.id!==""?i.id:"unknown",u=typeof i.chat==="string"?i.chat:"",l=r.channel,p=this.#A(l,u),f=a&&typeof i.turnId==="string"?i.turnId:"",m=p.filter((w)=>!w.cancelled&&!w.finishing&&w.stopReason===void 0),y=a&&f==="",g=f!==""?p.find((w)=>w.turnId===f):m.length===1?m[0]:void 0;if(g===void 0||y){this.#v++;let w=f!==""?"INPUT_REQUEST_UNMATCHED_TURN":"INPUT_REQUEST_UNATTRIBUTED";this.options.log.error(`hightea-pipe: ${w} ${JSON.stringify({sessionId:l,chatId:u,kind:i.kind,requestId:d,droppedCount:this.#v,...f===""?{liveWakeCount:m.length}:{turnId:f}})}`)}if(g===void 0||g.cancelled||g.finishing||g.stopReason!==void 0)return;if(g.stopReason=y?"OPERATION_SHAPE_INVALID":c?"INPUT_REQUIRED":"APPROVAL_REQUIRED",a&&!y){let w=typeof i?.toolCall?.toolName==="string"?i.toolCall.toolName:"",b=/^[A-Za-z0-9_.:-]{1,64}$/u.test(w)?`tool ${w}`:w===""?"a tool it did not name":`tool name withheld (${w.length} chars)`;(this.options.log.warn??this.options.log.error)(`hightea-pipe: turn ${g.turnId} needs approval for ${b}`)}if(g.stopStatusCode=y?"INPUT_REQUEST_UNATTRIBUTED":g.stopReason,y)g.stopDetail=`INPUT_REQUEST_UNATTRIBUTED:${d}`.slice(0,256);this.peer.notify("dispatchAction",{channel:g.chatUri,clientSeq:++this.#w,action:{type:"chat/turnCancelled",turnId:g.turnId,duration:Math.max(0,Date.now()-g.startedAtMs)}});return}let o=[...this.#r.values()].find((i)=>i.chatUri===r.channel&&i.turnId===n.turnId);if(o===void 0||o.finishing)return;let s={workspaceId:o.workspaceId,deliveryId:o.deliveryId,channel:o.chatUri,session:o.sessionUri,chat:o.chatUri,turnId:o.turnId,clientSeq:o.clientSeq};if(n.type==="chat/turnStarted"){if(o.stopReason!==void 0)return;await this.#t({event:"chat/turnStarted",...s,turnState:"running",statusCode:"TURN_RUNNING"},o.startedAtMs)}else if(n.type==="chat/turnComplete"||n.type==="chat/turnCancelled"||n.type==="chat/error"){o.finishing=!0;let i=n.type==="chat/turnComplete"&&o.stopReason===void 0,a=n.type==="chat/turnCancelled"&&o.stopReason===void 0,c=o.stopReason??(a?"TURN_CANCELLED":"OPERATION_SHAPE_INVALID"),d=o.stopStatusCode??o.stopReason??(a?"TURN_CANCELLED":"TURN_ENDED");await this.#t(i?{event:"chat/turnComplete",...s,turnState:"finished",statusCode:"TURN_FINISHED"}:{event:"x-hh/turnFailed",...s,turnState:"error",statusCode:d,errorCode:c,...o.stopDetail===void 0?{}:{errorDetail:o.stopDetail}},o.startedAtMs),this.#r.delete(o.key),await this.#M(o)}}async#M(e){if(this.#r.has(e.key))return;let r=(this.#n.get(e.key)??[]).shift();if(r===void 0){this.#d.delete(e.chatUri),this.#d.delete(e.sessionUri),this.peer.notify("unsubscribe",{channel:e.chatUri}),this.peer.notify("unsubscribe",{channel:e.sessionUri}),this.#c.delete(e.sessionUri);return}let n=P_(r.meta),o=n===void 0,s=n!==void 0&&Date.now()-n>gn;if(!s&&!o)try{await this.#C(e.key,r.frame,r.meta,r.turnId);return}catch(a){if(this.#h!==void 0)throw a}if(s||o)this.options.log.error(`ahp-host: queued wake ${r.meta.deliveryId} retired before dispatch (${n===void 0?"ASK_UNSIGNED: no signed triggering envelope":`ASK_STALE: newest trigger signed at ${new Date(n).toISOString()}`})`);let i=this.#e.get(e.key);await this.#t({event:"x-hh/turnFailed",workspaceId:r.meta.workspaceId,deliveryId:r.meta.deliveryId,channel:i?.chatUri??e.chatUri,session:i?.sessionUri??e.sessionUri,chat:i?.chatUri??e.chatUri,turnId:r.turnId,turnState:"error",statusCode:"QUEUED_WAKE_NOT_RUN",errorCode:o?"ASK_UNSIGNED":"ASK_STALE"}),await this.#M(e)}#t(e,t){let r=pf(e);if(this.#a.set(r.turnId===void 0?r.deliveryId:ir(r.deliveryId,r.turnId),r),this.options.store===void 0)return this.#D(r,t),Promise.resolve();return this.#b().then(()=>{this.#D(r,t)})}#D(e,t){if(!this.#S)return this.cloud.status(e);this.cloud.action($_(e,{...this.#m===""?{}:{clientId:this.#m},...t===void 0?{}:{startedAtMs:t}}))}}var yn=Be([S().min(1),S().min(1),S().min(1)]),U_=k({id:S(),version:H(1),tuple:yn,owner:S().min(1),sessionUri:S().regex(or)}).strict(),$f=(e)=>`session-${zf("sha256").update(e).digest("hex").slice(0,32)}`,Pf=k({id:S(),version:H(1),tuple:yn,sessionUri:S().regex(or),chatUri:S().min(1)}).strict(),Nf=(e)=>`chat-${zf("sha256").update(e).digest("hex").slice(0,32)}`;function Mf(e,t,r,n,o){let s=new Map,i=new Map,a=async(f,m)=>{if(o===void 0||m.chatUri===void 0||i.get(f)===m.chatUri)return;let y=yn.parse(JSON.parse(f)),g=Nf(f);try{await o.put({id:g,version:1,tuple:y,sessionUri:m.sessionUri,chatUri:m.chatUri},{createOnly:!0})}catch(w){if(w?.code!==-32010)throw w;let b=Pf.safeParse(await o.get(g));if(!b.success||b.data.sessionUri!==m.sessionUri||b.data.chatUri!==m.chatUri)throw Error("ahp-host: conflicting durable session chat",{cause:w})}i.set(f,m.chatUri)},c=async()=>{let f=new Map;for(let m of await o?.list()??[]){let y=Pf.safeParse(m);if(!y.success)throw Error("ahp-host: invalid durable session chat");let g=JSON.stringify(y.data.tuple);if(y.data.id!==Nf(g))throw Error("ahp-host: durable session chat has a different key");f.set(g,{sessionUri:y.data.sessionUri,chatUri:y.data.chatUri})}return f},d=(f)=>{let m=U_.safeParse(f);if(!m.success)throw Error("ahp-host: invalid durable session mapping");let y=m.data,g=JSON.stringify(y.tuple);if(y.id!==$f(g)||y.owner!==t)throw Error("ahp-host: durable session mapping has a different key or owner");return[g,{sessionUri:y.sessionUri}]},u=async(f,m)=>{let y=yn.parse(JSON.parse(f));if(JSON.stringify(y)!==f||!or.test(m))throw Error("ahp-host: invalid session mapping to publish");let g=s.get(f);if(g!==void 0)return g.sessionUri;let w=$f(f),b=m;try{await e.put({id:w,version:1,tuple:y,owner:t,sessionUri:m},{createOnly:!0})}catch(v){if(v?.code!==-32010)throw v;let x=await e.get(w);if(x===void 0)throw v;let[I,R]=d(x);if(I!==f)throw Error("ahp-host: conflicting durable session mapping",{cause:v});if(R.sessionUri!==m&&await r(R.sessionUri)!==t)throw Error("ahp-host: durable session belongs to an unknown or different owner",{cause:v});b=R.sessionUri}return s.set(f,{sessionUri:b}),b},l=async(f,m)=>{if(await u(f,m.sessionUri)!==m.sessionUri)throw Error("ahp-host: conflicting durable session mapping")},p=(f)=>e.put({id:"state",version:2,state:{dispatched:f.dispatched,lastStatus:f.lastStatus}});return{reserve:u,load:async()=>{let f=await e.get("state"),m={sessions:[],dispatched:[],lastStatus:[]};if(f!==void 0){if(f.id!=="state"||f.version!==1&&f.version!==2||!("state"in f))throw Error("ahp-host: invalid durable state record");let g=f.version===1?f.state:typeof f.state==="object"&&f.state!==null?{sessions:[],...f.state}:f.state,w=ds(g,n);if(f.version===2&&w.sessions.length!==0)throw Error("ahp-host: invalid durable state: a version 2 record holds no session mappings");m=w}let y=new Map;for(let g of await e.list()){if(g.id==="state")continue;let[w,b]=d(g);if(await r(b.sessionUri)!==t)throw Error("ahp-host: durable session belongs to an unknown or different owner");y.set(w,b)}s.clear();for(let[g,w]of y)s.set(g,w);for(let[,g]of m.sessions)if(await r(g.sessionUri)!==t)throw Error("ahp-host: legacy session belongs to an unknown or different owner");for(let[g,w]of m.sessions)await l(g,w),y.set(g,w);if(f?.version===1)await p(m);i.clear();for(let[g,w]of await c()){let b=y.get(g);if(b===void 0||b.sessionUri!==w.sessionUri)throw Error("ahp-host: durable session chat names no mapping or a different session");y.set(g,{sessionUri:b.sessionUri,chatUri:w.chatUri}),i.set(g,w.chatUri)}return{sessions:[...y],dispatched:m.dispatched,lastStatus:m.lastStatus}},save:async(f)=>{for(let[m,y]of f.sessions)await l(m,y),await a(m,y);await p(f)}}}import{randomUUID as Z_}from"node:crypto";var j_=15000,F_=(e)=>{if(e===null||typeof e!=="object")return;let t=e.message;return typeof t==="string"&&rr.includes(t)?t:void 0};function Df(e){let{log:t,receive:r}=e,n=!1,o=1000,s,i,a=new Map,c=(g,w=!0)=>{if(w)t.error(`hightea-pipe: ${g}`);for(let b of a.values())clearTimeout(b.timer),b.reject(Error(g));a.clear()},d=(g,w)=>{if(!n&&g!==void 0&&g===i&&g.live&&g.socket?.readyState===1)try{return g.socket.send(JSON.stringify(w)),!0}catch{}return t.error("hightea-pipe: CONTROL_SOCKET_UNAVAILABLE"),!1},u=(g)=>d(i,g),l=(g,w,b)=>{if(g===void 0||g.readyState>=2)return;try{if(w===void 0)g.close();else g.close(w,b)}catch{t.error("hightea-pipe: CONTROL_SOCKET_CLOSE_FAILED")}},p=(g,w)=>{if(n)return;if(n=!0,s!==void 0)clearTimeout(s);if(s=void 0,i!==void 0)i.live=!1;c("CONTROL_SOCKET_CLOSED",!1),l(i?.socket,g,w)},f=(g,w)=>{let b;try{b=JSON.parse(String(g.data))}catch{t.error("hightea-pipe: CONTROL_FRAME_INVALID");return}if(b!==null&&typeof b==="object"&&!Array.isArray(b)){let v=b;if(v.method===void 0&&(("result"in v)||("error"in v))){let x=typeof v.id==="string"?a.get(v.id):void 0;if(x===void 0){t.error("hightea-pipe: CONTROL_RESPONSE_UNKNOWN");return}if(a.delete(v.id),clearTimeout(x.timer),v.jsonrpc==="2.0"&&"result"in v&&!("error"in v))x.resolve(v.result);else{let I="error"in v?F_(v.error):void 0;t.error(`hightea-pipe: CONTROL_REQUEST_REFUSED${I===void 0?"":` ${I}`}`),x.reject(Error(I===void 0?"CONTROL_REQUEST_REFUSED":`CONTROL_REQUEST_REFUSED ${I}`))}return}}r(b,w)},m=()=>{if(n)return;let g={live:!0,opened:!1};i=g;let w=()=>{if(n||s!==void 0)return;let x=o;o=Math.min(o*2,60000),s=setTimeout(()=>{s=void 0,m()},x)},b=(x)=>{if(n||i!==g||!g.live)return;g.live=!1,c(x),l(g.socket),w()},v=(x,I)=>{if(n||i!==g)return;t.error(`${I===void 0||I===""?`hightea-pipe: CONTROL_SOCKET_REFUSED:${x}`:`hightea-pipe: CONTROL_SOCKET_REFUSED:${x}: ${I}`}`),p()};try{let x=e.dial((E)=>{if(E===401||E===403)v(E);else b("CONTROL_SOCKET_ERROR")});g.socket=x;let I={send:(E)=>d(g,E),close:(E,A)=>p(E,A)};x.addEventListener("message",(E)=>{if(!n&&i===g&&g.live)f(E,I)}),x.addEventListener("error",()=>b("CONTROL_SOCKET_ERROR")),x.addEventListener("close",(E)=>{if(E.code===4003||E.code===4004)v(E.code,E.reason);else b("CONTROL_SOCKET_CLOSED")});let R=()=>{if(n||i!==g||!g.live||g.opened)return;g.opened=!0,o=1000,e.opened?.(I)};if(x.addEventListener("open",R),n||!g.live)l(x);else if(x.readyState===1)R()}catch{b("CONTROL_SOCKET_ERROR")}},y=(g,w,b)=>new Promise((v,x)=>{let I=setTimeout(()=>{a.delete(g),t.error("hightea-pipe: CONTROL_REQUEST_TIMEOUT"),x(Error("CONTROL_REQUEST_TIMEOUT"))},j_);if(a.set(g,{resolve:v,reject:x,timer:I}),!u({jsonrpc:"2.0",id:g,method:w,params:b}))a.delete(g),clearTimeout(I),x(Error("CONTROL_SOCKET_UNAVAILABLE"))});return queueMicrotask(m),{send:u,close:p,answer:(g,w)=>u(w.ok?{jsonrpc:"2.0",id:g,result:null}:{jsonrpc:"2.0",id:g,error:{code:-32000,message:w.code}}),reply:(g,w)=>u("result"in w?{jsonrpc:"2.0",id:g,result:w.result}:{jsonrpc:"2.0",id:g,error:w.error}),status:(g)=>u({jsonrpc:"2.0",method:"x-hightea/status",params:g}),sessionChanged:(g)=>void u({jsonrpc:"2.0",method:"root/sessionSummaryChanged",params:g}),action:(g)=>u({jsonrpc:"2.0",method:"action",params:g}),authRequired:(g)=>u({jsonrpc:"2.0",method:"auth/required",params:g}),sourcePush:(g)=>y(`push:${Z_()}`,"x-hightea/source/push",g),hostRequestAnswer:(g,w)=>void u({jsonrpc:"2.0",id:g,...af(w)})}}import{spawn as J_}from"node:child_process";import{createHash as Vf}from"node:crypto";import{createInterface as Y_}from"node:readline";import{randomUUID as Lf}from"node:crypto";var _n=1e4,H_=1024;function B_(e,t,r){let n=0;while(n<e.length&&t+te(e[n])>r)n++;let o=[],s=t;for(let i=n;i<e.length;i++){let a=e[i],c=te(a)+(o.length===0?0:1);if(o.length>0&&s+c>r)break;o.push(a),s+=c}return{dropped:e.slice(0,n),batch:o}}class ar{sourceId;#e="e_"+Lf();#o=0n;#r=[];#s=!1;#n;#d=-1/0;#c=0;#l=-1/0;#u=!0;#f=new AbortController;#a;#g;#h;#y;#w;#v=!1;constructor(e){this.#a=e,this.sourceId=e.sourceId,this.#g=e.coalesceMs??2000;let t=e.soonMs??500;if(!(Number.isFinite(t)&&t>=0))throw Error(`soonMs must be a finite number of milliseconds, 0 or more, not ${String(t)}`);this.#h=t,this.#y=e.now??Date.now,this.#w=e.unackedMax??_n}get epoch(){return this.#e}get ordinal(){return this.#o}get watching(){return this.#u}get unacknowledged(){return this.#r.length}get stopped(){return this.#f.signal.aborted}#S(){return this.#o++,{epoch:this.#e,ordinal:String(this.#o)}}next(){return this.#S()}watch(e){if(this.#u=e,!e){if(this.#n!==void 0)clearTimeout(this.#n),this.#n=void 0;return}this.#m()}enqueue(e,t){if(this.#r.push(...e),this.#r.length>this.#w){this.#a.log.error(`hightea-source: ${this.sourceId} has more than ${this.#w} unacknowledged observations; starting a new epoch`),this.#r.length=0,this.#e="e_"+Lf(),this.#o=0n,this.#a.onOverflow();return}if(t?.soon===!0){if(this.#v=!0,this.#n!==void 0)clearTimeout(this.#n),this.#n=void 0}if(this.#m(),this.#r.length===0)this.#v=!1}#m(){if(!this.#u||this.#s||this.#r.length===0||this.#n!==void 0||this.#f.signal.aborted)return;let e=this.#l-this.#y();if(e>0){this.#n=setTimeout(()=>{this.#n=void 0,this.#m()},e);return}let t=this.#v?Math.min(this.#g,this.#h):this.#g,r=this.#d+t-this.#y();if(r>0){this.#n=setTimeout(()=>{this.#n=void 0,this.#m()},r);return}let n=cn-H_,o=te({workspaceId:this.#a.workspaceId,sourceId:this.sourceId,hostId:this.#a.hostId,position:{epoch:this.#e,ordinal:"0"},observations:[]}),{dropped:s,batch:i}=B_(this.#r,o,n);if(s.length>0){this.#r.splice(0,s.length);for(let d of s)this.#a.onOmit?.(d.change.op==="upsert"?d.change.row.address:d.change.address,`${te(d)} bytes cannot fit a ${n}-byte push frame even alone; a later change to that row is what reports it`)}if(i.length===0)return;let a=i[i.length-1],c=this.#e;this.#s=!0,this.#d=this.#y(),this.#v=!1,this.#a.push({workspaceId:this.#a.workspaceId,sourceId:this.sourceId,hostId:this.#a.hostId,position:a.position,observations:i}).then((d)=>{if(this.#c>0)this.#a.log.info?.(`hightea-source: a push of ${this.sourceId} is answered again after ${this.#c} refusal(s)`),this.#c=0,this.#l=-1/0;let u=ql.safeParse(d);if(!u.success){this.#a.log.error(`hightea-source: the workspace answered a push of ${this.sourceId} outside its schema`);return}let l=u.data.applied;if(l===null||l.epoch!==c||l.epoch!==this.#e)return;let p=BigInt(l.ordinal),f=0;while(f<this.#r.length&&BigInt(this.#r[f].position.ordinal)<=p)f++;this.#r.splice(0,f)},(d)=>{this.#c++;let u=Math.min(this.#g*2**Math.min(this.#c-1,5),60000);if(this.#l=this.#y()+u,this.#c===1){let l=d instanceof Error?d.message:String(d);this.#a.log.error(`hightea-source: a push of ${this.sourceId} was not answered: ${l}; retrying with backoff, next in ${Math.round(u/1000)} s`)}}).finally(()=>{this.#s=!1,this.#m()})}stop(){if(this.#f.abort(),this.#n!==void 0)clearTimeout(this.#n),this.#n=void 0}}import{spawn as q_}from"node:child_process";import{createInterface as G_}from"node:readline";var Uf=65536,K_=2000,Zf=16777216,V_=8,W_=5000;class pe extends Error{code;constructor(e,t){super(t);this.code=e}}function wn(e,t){if(e.pid===void 0)return;try{process.kill(-e.pid,t)}catch{}}function xt(e){let t=e.stderr.trim().split(`
|
|
@@ -76,5 +76,5 @@ hightea-page-serve: ${v.message}`});let w=new Promise((v)=>{o.on("close",(x,I)=>
|
|
|
76
76
|
`).map((r)=>r.trim()).find((r)=>r!=="")??"";return t.length>Yf?`${t.slice(0,Yf)}…`:t}function Iw(e,t){if(typeof e.info==="function")e.info(t);else e.error(t)}class ws{sourceId;#e;#o;#r;#s;#n;#d;#c=0;#l;#u;#f=new Map;#a;#g=new AbortController;constructor(e){let{config:t}=e;if(t.command.length===0)throw Error(`the command source ${t.sourceId} declares no command`);if(t.key.trim()==="")throw Error(`the command source ${t.sourceId} declares an empty key field`);let r=t.intervalMs;if(!(Number.isFinite(r)&&r>0))throw Error(`the command source ${t.sourceId} needs a positive intervalMs, not ${String(r)}`);this.#e=e,this.sourceId=t.sourceId,this.#o=e.run??ys,this.#r=e.now??Date.now,this.#n=r,this.#d=e.childTimeoutMs??Ew,this.#s=new ar({sourceId:t.sourceId,workspaceId:e.workspaceId,hostId:e.hostId,push:(n)=>e.push(n),log:e.log,now:this.#r,...e.coalesceMs===void 0?{}:{coalesceMs:e.coalesceMs},onOmit:(n,o)=>e.log.error(`hightea-source: ${t.sourceId} row ${n} omitted: ${o}`),onOverflow:()=>this.#x()})}get epoch(){return this.#s.epoch}start(){this.#h()}async stop(){if(this.#g.abort(),this.#s.stop(),this.#a!==void 0)clearTimeout(this.#a),this.#a=void 0;await this.#u?.catch(()=>{return})}#h(){if(this.#g.signal.aborted)return;this.#w().catch((e)=>this.#e.log.error(`hightea-source: reading ${this.sourceId} failed; keeping the last good dataset: ${It(e)}`)).finally(()=>this.#y())}#y(){if(this.#g.signal.aborted||this.#a!==void 0)return;this.#a=setTimeout(()=>{this.#a=void 0,this.#h()},this.#n)}async#w(){let e=this.#u;if(e!==void 0)return await e;let t=this.#v().finally(()=>{this.#u=void 0});return this.#u=t,await t}async#v(){let{config:e}=this.#e,t;try{t=await this.#o(e.command,{timeoutMs:this.#d,signal:this.#g.signal})}catch(n){throw Error(`the command ${e.command[0]??"(none)"} could not run: ${It(n)}`)}if(t.code!==0)throw Error(`the command exited ${t.code===null?"on a signal":t.code}${_s(t.stderr)===""?"":`: ${_s(t.stderr)}`}`);if(t.stderr.trim()!=="")Iw(this.#e.log,`hightea-source: ${this.sourceId} read warned: ${_s(t.stderr)}`);let r=this.#S(t.stdout);return this.#m(r)}#S(e){let{key:t}=this.#e.config,r=e.split(`
|
|
77
77
|
`),n=new Map;for(let[o,s]of r.entries()){let i=s.trim();if(i==="")continue;let a=`line ${o+1}`,c;try{c=JSON.parse(i)}catch(f){throw Error(`${a} is not JSON: ${It(f)}`)}if(c===null||typeof c!=="object"||Array.isArray(c))throw Error(`${a} is not an object`);let d=c;for(let f of Object.keys(d))if(f!==t&&f!=="columns"&&f!=="extra"&&f!=="version")throw Error(`${a} carries an unknown field "${f}"; a line is {${t}, columns, extra?, version?}`);let u=d[t];if(typeof u!=="string"||u.trim()==="")throw Error(`${a} has no "${t}"; every row needs an address`);let l=d.version??xw("sha256").update(JSON.stringify([d.columns??null,d.extra??null])).digest("hex");if(typeof l!=="string"||l==="")throw Error(`${a} carries an unusable "version"`);let p=wt.safeParse({address:u,version:l,scope:bw,columns:d.columns,extra:d.extra??null});if(!p.success){let f=p.error.issues.slice(0,3).map((m)=>`${m.path.join(".")||"row"}: ${m.message}`).join("; ");throw Error(`${a} is not a row: ${f}`)}if(n.has(u))throw Error(`${a} repeats the address ${u}; one line per row`);n.set(u,{key:u,row:p.data})}return n}#m(e){let t=this.#l,r=new Map,n=[],o=[...new Set([...e.keys(),...t?.byAddress.keys()??[]])].sort();for(let i of o){let a=e.get(i),c=t?.byAddress.get(i);if(a===void 0){n.push({position:this.#s.next(),change:{op:"delete",address:i}});continue}if(c===void 0||c.row.version!==a.row.version){let d=this.#s.next();n.push({position:d,change:{op:"upsert",row:a.row}}),r.set(i,{row:a.row,at:BigInt(d.ordinal)})}else r.set(i,{row:a.row,at:c.at})}this.#f=e;let s={generation:`${this.#s.epoch}.${++this.#c}`,epoch:this.#s.epoch,base:this.#s.ordinal,rows:[...r.values()],byAddress:r,at:this.#r()};return this.#l=s,this.#s.enqueue(n),s}#x(){let e=this.#f.size;if(e>_n){this.#e.log.error(`hightea-source: ${this.sourceId} holds ${e} rows, more than the ${_n} one push may carry; shorten the command's answer`);return}if(this.#l=void 0,e===0){this.#w().catch((t)=>this.#e.log.error(`hightea-source: reading ${this.sourceId} after an overflow failed: ${It(t)}`));return}this.#m(this.#f)}async#k(){return this.#l??await this.#w()}#R(e,t){let r=e.byAddress.get(t);if(r===void 0)return{position:{epoch:e.epoch,ordinal:String(e.base)},change:{op:"delete",address:t}};return{position:{epoch:e.epoch,ordinal:String(r.at)},change:{op:"upsert",row:r.row}}}#O(e,t,r){let n=e.page===void 0?0:Number(e.page);if(!Number.isSafeInteger(n)||n<0||n>r.rows.length)throw Error(`the list token ${String(e.page)} does not name a page of this read`);let o=(c,d)=>({generation:r.generation,snapshot:r.generation,base:{epoch:r.epoch,ordinal:String(r.base)},rows:d,next:c>=r.rows.length?null:String(c),complete:c>=r.rows.length}),s=[],i=0,a=n;while(a<r.rows.length&&s.length<e.limit){let c=r.rows[a].row,d=te(c);if(te({...t,op:"list",outcome:"applied",body:o(a+1,[])})+i+d+s.length>ot){if(s.length===0)throw Error(`ITEM_TOO_LARGE: ${c.address}`);break}s.push(c),i+=d,a++}return o(a,s)}async handle(e){let t={workspaceId:e.workspaceId,sourceId:e.sourceId,hostId:e.hostId},r=(n,o="refused")=>({...t,op:e.op,outcome:o,code:n});if(e.sourceId!==this.sourceId)return r("SOURCE_UNBOUND");try{switch(e.op){case"watch":if(this.#s.watch(e.args.on),e.args.on&&this.#l===void 0)this.#w().catch((n)=>this.#e.log.error(`hightea-source: reading ${this.sourceId} on a watcher's first subscribe failed: ${It(n)}`));return{...t,op:"watch",outcome:"applied",body:{on:this.#s.watching}};case"list":return{...t,op:"list",outcome:"applied",body:this.#O(e.args,t,await this.#k())};case"read":return{...t,op:"read",outcome:"applied",body:{observation:this.#R(await this.#k(),e.args.address)}};case"assign":return this.#e.log.error(`hightea-source: ${this.sourceId} cannot assign ${e.args.address}: a command source has no write`),r("SOURCE_UNAVAILABLE")}}catch(n){let o=It(n);if(this.#e.log.error(`hightea-source: ${e.op} on ${this.sourceId} failed: ${o}`),o.startsWith("ITEM_TOO_LARGE: "))return{...t,op:e.op,outcome:"refused",code:"ITEM_TOO_LARGE",item:o.slice(16)};return r("SOURCE_UNAVAILABLE","unknown")}}}function Qf(e,t=0){return e.flatMap((r)=>{if(t>=3||r.errors===void 0||r.errors.length===0)return[r];return r.errors.map((n)=>Qf(n,t+1)).reduce((n,o)=>o.length<n.length?o:n)})}var kw="x-hightea/source/request";function eh(e){let{log:t}=e,r=(i,a,c)=>i.send({jsonrpc:"2.0",id:a,error:{code:-32000,message:c}}),n=(i,a,c,d,u)=>o(i,a,c,{workspaceId:c.workspaceId,sourceId:c.sourceId,hostId:c.hostId,op:c.op,outcome:d,code:u}),o=(i,a,c,d)=>{let u={jsonrpc:"2.0",id:a,result:d};if(te(u)>cn)return t.error(`hightea-source: FRAME_TOO_LARGE for ${c.op} on ${c.sourceId}`),n(i,a,c,"unknown","FRAME_TOO_LARGE");return i.send(u)},s=async(i,a,c)=>{let{handler:d}=e;if(d===void 0)return n(i,a,c,"refused","SOURCE_UNAVAILABLE");let u;try{u=await d.handle(c)}catch{return t.error(`hightea-source: ${c.op} on ${c.sourceId} failed in its handler`),n(i,a,c,"unknown","SOURCE_UNAVAILABLE")}let l=Bl.safeParse(u);if(!l.success){let p=Qf(l.error.issues).slice(0,3).map((f)=>`${f.path.join(".")||"answer"}: ${f.message}`).join("; ").slice(0,400);return t.error(`hightea-source: ${c.op} on ${c.sourceId} returned an answer outside its schema: ${p}`),n(i,a,c,"unknown","SOURCE_UNAVAILABLE")}if(l.data.workspaceId!==c.workspaceId||l.data.sourceId!==c.sourceId||l.data.hostId!==c.hostId||l.data.op!==c.op)return t.error(`hightea-source: ${c.op} on ${c.sourceId} was answered for another binding: ${l.data.op} on ${l.data.sourceId} in ${l.data.workspaceId} for ${l.data.hostId}`),n(i,a,c,"unknown","SOURCE_UNAVAILABLE");return o(i,a,c,l.data)};return{receive(i,a){if(i===null||typeof i!=="object"||i.method!==kw)return!1;let{id:c,params:d}=i;if(typeof c!=="string"||!c.startsWith("source:")||c.length>300)return r(a,c??null,"OPERATION_SHAPE_INVALID"),!0;let u=Hl.safeParse(d);if(!u.success)return r(a,c,"OPERATION_NOT_ALLOWLISTED"),!0;let l=u.data;if(l.workspaceId!==e.workspaceId||l.hostId!==e.hostId||!e.bindings().has(l.sourceId))return n(a,c,l,"refused","SOURCE_UNBOUND"),!0;return s(a,c,l),!0}}}var th="x-hh-records";var rh="records",Cw=(e)=>{if(!e.startsWith("x-hh-records://"))return;let t=e.slice(15);if(t===""||t.includes("/")||t.includes("?"))return;return decodeURIComponent(t)};function nh(e){let t=new Map,r,n=(a)=>{let c=t.get(a);if(c!==void 0)return c;let d=new Map;return t.set(a,d),d},o=(a)=>[...n(a).values()];return{channel:{grant:"records:read",snapshot:(a)=>{let c=Cw(a);if(c===void 0)return{sources:e.sources().map((p)=>({...p,count:n(p.source).size}))};let d=e.sources().find((l)=>l.source===c);if(d===void 0)return{source:c,epoch:"",records:[],error:`this host offers no source ${c}; x-hh-records:// lists the ones it does`};return{source:c,epoch:d.epoch,records:o(c)}},describe:()=>({title:"Records",description:"Each board source's records, one URI per source: x-hh-records://<sourceId>."}),operations:{operations:()=>[{id:Ie,kind:"records",label:"Assign",description:"Sets one record's owner, against the revision the caller read; a stale revision is refused and nothing is written.",scopes:["records"],grant:dn,status:"idle",input:{type:"object",properties:{address:{type:"string",minLength:1,maxLength:1024},ownerMemberId:{type:"string",minLength:1,maxLength:256},expectedOwner:{type:["string","null"]},ifRevision:{type:"string",minLength:1,maxLength:256},intentId:{type:"string",minLength:1,maxLength:256}},required:["address","ownerMemberId","ifRevision","intentId"],additionalProperties:!1}}],run:async(a,c,d,u,l)=>{if(a.id!==Ie)throw Error(`x-hh-records:// offers no operation ${a.id}; only ${Ie}`);let p=Gl.safeParse(d??{});if(!p.success)throw Error(`${Ie} on x-hh-records://: ${p.error.issues.map((f)=>`${f.path.join(".")} ${f.message}`).join("; ")}`);if(e.assign===void 0)throw Error("x-hh-records:// has no source to assign on this host");return e.assign(p.data,l)}}},bind:(a)=>{r=a},held:o,observe:(a,c)=>{let d=n(a);for(let u of c){if(u.op==="delete"){if(d.get(u.address)===void 0)continue;d.delete(u.address),i(a,{type:"x-hh-records/changed",source:a,deleted:!0,address:u.address,revision:u.revision});continue}let l={address:u.address,revision:u.revision,scope:u.scope??a,columns:u.columns??{},...u.extra===void 0?{}:{extra:u.extra}},p=d.get(u.address);if(p!==void 0&&p.revision===l.revision)continue;d.set(u.address,l),i(a,{type:"x-hh-records/changed",source:a,record:l,revision:l.revision})}}};function i(a,c){if(r===void 0)return;try{r.publish(`x-hh-records://${encodeURIComponent(a)}`,c)}catch(d){e.log.error(`hightea-records: publishing on x-hh-records://${a} failed: ${d instanceof Error?d.message:String(d)}`)}}}import{readFileSync as Rw,renameSync as oh,unlinkSync as Ow,writeFileSync as sh}from"node:fs";import{join as Ss}from"node:path";var Tw="pipe-connected.json",ih="pipe-refused.json";function ah(e=new URL("./plugin.json",import.meta.url)){let t;try{t=JSON.parse(Rw(e,"utf8"))}catch(r){return{error:`cannot read ${e.pathname}: ${r.message}`}}if(typeof t!=="object"||t===null||!("version"in t)||typeof t.version!=="string"||t.version==="")return{error:`${e.pathname} states no version`};return{version:t.version}}function ch(e,t,r=new Date){let n=Ss(e,Tw),o=`${n}.${process.pid}.tmp`;sh(o,`${JSON.stringify({version:t,at:r.toISOString()},null,2)}
|
|
78
78
|
`,{mode:384}),oh(o,n)}function uh(e,t,r,n=new Date){let o=Ss(e,ih),s=`${o}.${process.pid}.tmp`,i={...r===void 0?{}:{version:r},at:n.toISOString(),error:t};sh(s,`${JSON.stringify(i,null,2)}
|
|
79
|
-
`,{mode:384}),oh(s,o)}function dh(e){try{Ow(Ss(e,ih))}catch(t){if(t.code!=="ENOENT")throw t}}function kt(e){return{authorization:`Bearer ${e}`,"content-type":"application/json",accept:"application/json, text/event-stream"}}function Aw(e,t,r){if(r===void 0)return Error(`HOUSE_ANSWER_UNREADABLE ${e}: HTTP ${t.status} ${t.statusText===""?"":`${t.statusText} `}— the answer was not JSON`);let n=r.error?.message?.trim()??"",o=r.error?.code===void 0?"":` code ${r.error.code}`,s=/scope="([^"]*)"/u.exec(t.headers.get("www-authenticate")??"")?.[1],i=`HTTP ${t.status}${t.statusText===""?"":` ${t.statusText}`}`;return Error(`HOUSE_REFUSED ${e}: ${i}${o} — ${n===""?"the house gave no message":n}${s===void 0?"":` — the token needs ${s}`}`)}async function bn(e,t,r,n){let o=JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:r,arguments:n}});for(let s=0;;s++){let i,a;try{i=await fetch(e,{method:"POST",headers:t,body:o}),a=await i.text()}catch(d){if(s>=1)throw Error(`HOUSE_UNREACHABLE: ${String(d)}`);continue}let c;try{c=JSON.parse(a)}catch{c=void 0}if(!i.ok||c===void 0||c.error!==void 0)throw Aw(r,i,c);return c}}function lh(e){let t=e??{},r=t.pageId;if(typeof r!=="string"||r.trim().length===0)throw Error("page_screenshot requires a non-empty string pageId");let n={pageId:r};for(let o of["version","width","height"]){let s=t[o];if(s===void 0)continue;if(typeof s!=="number"||!Number.isFinite(s))throw Error(`page_screenshot ${o} must be a number`);n[o]=s}if(t.format!==void 0){if(t.format!=="png"&&t.format!=="webp")throw Error("page_screenshot format is png or webp");n.format=t.format}return n}var ur=[{name:"hightea_thread_read",description:"You were woken by a mention in a Hightea room thread. Read that thread's recent messages first.",inputSchema:{type:"object",properties:{},additionalProperties:!1},readOnly:!0,toHouse:()=>({tool:"
|
|
80
|
-
`)}function Nw(e){let r=e.result?.structuredContent?.turn,n=(d)=>{let u=r?.[d];return typeof u==="string"&&u!==""?u:void 0},o=r?.triggeringMessageIds,s=n("roomId"),i=n("messageId"),a=n("deliveryId"),c=n("memberId");if(s===void 0||i===void 0||a===void 0||c===void 0||!Array.isArray(o)||o.some((d)=>typeof d!=="string"))throw new Ke("TURN_FACTS_UNAVAILABLE","the house's answer for this bearer carries no turn (roomId, messageId, deliveryId, memberId, triggeringMessageIds); nothing room-shaped is served rather than inventing one");return{threadRef:`${s}/${i}`,deliveryId:a,member:c,triggeringMessageIds:o}}var gh=/^[A-Za-z0-9_.:-]{1,200}$/u,zw=/^[A-Z_]{1,64}$/u;function yh(e){if(typeof e!=="object"||e===null)return null;if(e.method!=="x-hightea/source/declared")return null;let r=e.params;if(typeof r!=="object"||r===null)return{bound:[],refused:[],dropped:0};let n=(i)=>Array.isArray(i)?i.filter((a)=>typeof a==="string"&&gh.test(a)).slice(0,64):[],o=(i)=>{if(!Array.isArray(i))return[];let a=[];for(let c of i){if(typeof c!=="object"||c===null)continue;let{sourceId:d,code:u,message:l}=c;if(typeof d!=="string"||!gh.test(d)||typeof u!=="string"||!zw.test(u))continue;if(a.push({sourceId:d,code:u,message:typeof l==="string"?l.slice(0,200):""}),a.length===64)break}return a},s=r.dropped;return{bound:n(r.bound),refused:o(r.refused),dropped:typeof s==="number"&&Number.isSafeInteger(s)&&s>=0?s:0}}function _h(e){let t=e.refused.length===0?"none refused":`${String(e.refused.length)} refused: ${e.refused.map((o)=>`${o.sourceId}=${o.code}${o.message===""?"":` (${o.message})`}`).join(", ")}`,r=e.bound.length===0?"none bound":`bound ${e.bound.join(", ")}`,n=e.dropped===0?"":`; ${String(e.dropped)} declared id(s) were not readable`;return`hightea-source: declared sources — ${r}; ${t}${n}`}import{createServer as Mw}from"node:http";function Dw(e){let t=e.headers.get("authorization");if(t===null)return;let[r,...n]=t.split(" ");if(r?.toLowerCase()!=="bearer"||n.length===0)return;let o=n.join(" ").trim();return o===""?void 0:o}function Lw(e){return new Response(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32001,message:"Hightea token required"}}),{status:401,headers:{"content-type":"application/json","www-authenticate":`Bearer resource_metadata="${e.resourceMetadataUrl}"`}})}function Uw(e,t,r){let n=e.requiredScopes?.(t)??[];if(n.length===0)return;let o=r.scopes??[],s=n.filter((i)=>!o.includes(i));if(s.length===0)return;return new Response(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32002,message:`insufficient_scope: ${s.join(" ")}`,error:"insufficient_scope"}}),{status:403,headers:{"content-type":"application/json","www-authenticate":`Bearer error="insufficient_scope", scope="${n.join(" ")}", resource_metadata="${e.resourceMetadataUrl}"`}})}var wh=4194304;function Zw(e,t){return async(r)=>{if(r.method!=="POST")return new Response("Method Not Allowed",{status:405,headers:{allow:"POST"}});let n;try{n=await r.json()}catch{return new Response(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32700,message:"the frame is not JSON"}}),{status:400,headers:{"content-type":"application/json"}})}let o=Dw(r),s=o===void 0?void 0:mh(o);if(n.method==="tools/call"){if(s===void 0)return Lw(t);let d=n.params?.name;if(typeof d==="string"){let u=Uw(t,d,s);if(u!==void 0)return u}}let i=r.headers.get("mcp-session-id")??(n.method==="initialize"?crypto.randomUUID():void 0),a=await e.handleRpc(n,s,i),c={"content-type":"application/json"};if(i!==void 0)c["mcp-session-id"]=i;return new Response(JSON.stringify(a),{status:200,headers:c})}}function Sh(e,t){let r=t.hostname??"127.0.0.1",n=Zw(e,t),o=t.log??{error:(a)=>console.error(a)},s=Mw((a,c)=>void jw(a,c,n,o)),i=new Promise((a,c)=>{let d=(u)=>c(u);s.once("error",d),s.listen(t.port,r,()=>{s.off("error",d),a()})});return i.catch(()=>{return}),{get url(){let a=s.address(),c=typeof a==="object"&&a!==null?a.port:t.port;return`http://${r}:${String(c)}/mcp`},ready:i,stop:()=>{s.closeAllConnections(),s.close()}}}async function jw(e,t,r,n){try{let o=[],s=0;for await(let u of e){if(s+=u.length,s>wh){n.error(`hightea-mcp: a request body over ${String(wh)} bytes was refused (413)`),t.writeHead(413,{"content-type":"application/json"}),t.end(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32600,message:"this server refuses a request body this large"}})),e.destroy();return}o.push(Buffer.from(u))}let i=new Headers;for(let[u,l]of Object.entries(e.headers)){if(l===void 0)continue;if(Array.isArray(l))for(let p of l)i.append(u,p);else i.set(u,l)}let a=Buffer.concat(o),c=await r(new Request(`http://${e.headers.host??"127.0.0.1"}${e.url??"/"}`,{method:e.method??"GET",headers:i,...a.length===0?{}:{body:a}})),d=Buffer.from(await c.arrayBuffer());t.writeHead(c.status,Object.fromEntries(c.headers)),t.end(d)}catch(o){n.error(`hightea-mcp: a request could not be answered: ${o instanceof Error?o.name:typeof o}`),t.writeHead(500,{"content-type":"application/json"}),t.end(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32603,message:"the Hightea MCP server could not answer this request"}}))}}var Fw=(e)=>e.change.op==="delete"?{op:"delete",address:e.change.address,revision:`${e.position.epoch}#${e.position.ordinal}`}:{op:"upsert",address:e.change.row.address,revision:e.change.row.version,scope:e.change.row.scope,columns:e.change.row.columns,extra:e.change.row.extra},Y="hightea-pipe",vh=`plugin:${Y}`,Hw=ur.map((e)=>e.name);function Bw(e){let t=[];return e.onMessage((r)=>{for(let n of t)n(r)}),{request:(r,n,o)=>e.request(r,n,o),notify:(r,n)=>e.notify(r,n),onMessage:(r)=>void t.push(r),close:()=>e.close()}}function qw(e){let t=e instanceof Error?e.message:String(e);if(/wants to be signed in|set the authenticate option/u.test(t))return`AGENT_SIGN_IN_REQUIRED: sign in to ${/^([a-z][a-z0-9_-]{0,19}): /u.exec(t)?.[1]??"the agent backend"}`;if(e instanceof vt||/no matching configured ACP process authority/u.test(t))return"AGENT_START_REFUSED: the agent is not mapped on this host";if(/durable state|invalid durable|RECORD_READ_FAILED/u.test(t))return"HOST_STATE_UNREADABLE: the host's saved state could not be read";if(/answered protocol|initialize|local ahpd/u.test(t))return"AHPD_INIT_FAILED: the local daemon did not answer";return"AGENT_START_REFUSED: the agent could not start"}function Gw(e){let t=e.headers;if(typeof t!=="object"||t===null||Array.isArray(t))throw Error(`${Y}: the plugin entry names no headers (headers), so this host cannot say which Hightea host it is`);return t}function Kw(e,t,r){let n=t.houseId;if(typeof t.workspaceId!=="string"||t.workspaceId===""){if(typeof n!=="string"||n==="")throw Error("hightea-pipe: the plugin entry names no workspace (workspaceId)");t={...t,workspaceId:n}}let o=Gw(t),s=typeof t.pluginVersion==="string"&&t.pluginVersion!==""?{version:t.pluginVersion}:ah(),i="version"in s?s.version:void 0,a=(E)=>{if(e.configDir===void 0)return;try{uh(e.configDir,String(E),i)}catch(A){e.log.error(`${Y}: could not record the refused start in ${e.configDir}: ${String(A)}`)}};if(!("version"in s))e.log.error(`${Y}: hello will name no plugin version: ${s.error}`);let c=!1,d,u=!1,l,p,f=new Map,m,y=new Map,g,w=nh({sources:()=>[...f.values()].map((E)=>({source:E.sourceId,epoch:E.epoch})),log:e.log,assign:async(E,A)=>{if(g===void 0)throw Error("records:assign: no source is listening on this host yet");return g(E,A)}});w.bind(e.registerChannel(th,w.channel)),e.registerGrants(rh,{title:"Board records",description:"Each board source's records as a channel: reading them, and assigning one record's owner against the revision that was read.",operations:[Ie]});let b=async()=>{if(u=!0,l!==void 0)clearTimeout(l);l=void 0,p?.close(),await Promise.all([...y.values()].map((E)=>E.stop?.()))};e.registerClose(b),e.registerClose(()=>m?.stop());let v=e.configDir===void 0?Promise.resolve(void 0):Rf(e.configDir).catch((E)=>{let A=E instanceof Error?E:Error(String(E));return e.log.error(`${Y}: ${A.message}`),A}),x=new sr({configDir:e.configDir,workspaceId:t.workspaceId,ownAgents:new Set(t.agents.map(([E])=>E)),hostKey:v,readThread:async(E,A)=>{if(t.mcpUrl===void 0)throw new Z("ROOM_ASKS_UNTRUSTED","this host has no house MCP endpoint to read the ask from");return(await bn(t.mcpUrl,kt(E),"read_thread",A)).result?.structuredContent}}),I=r.askGate??x;if(e.registerSessionMeta===void 0)e.log.error(`${Y}: this ahpd cannot publish a session's member (registerSessionMeta is absent), so Hightea page rows for its sessions will name none`);else e.registerSessionMeta("hh/agentMemberId",(E)=>d?.agentMemberOf(E));e.on("listening",()=>{if(u||l!==void 0||p!==void 0)return;l=setTimeout(()=>{l=void 0,R().catch((E)=>{e.log.error(`${Y}: the host could not start its connections: ${String(E)}`),a(E)})},100)});async function R(){if(u)return;let E,A=o[mf]??o[gf]??"";f=new Map,y=new Map;for(let T of t.sources??[]){if(Xf(T)){y.set(T.sourceId,new ws({config:T,workspaceId:t.workspaceId,hostId:A,log:e.log,push:(N)=>Ne.sourcePush(N),...r.sourceChildren===void 0?{}:{run:r.sourceChildren.run}}));continue}if(T.kind!==void 0&&T.kind!=="km")throw Error(`${Y}: the plugin entry names a source kind it cannot construct (${JSON.stringify(T.kind)}) for ${T.sourceId}, so this start is refused rather than offering it as km`);let L=new gs({config:T,workspaceId:t.workspaceId,hostId:A,log:e.log,...r.sourceChildren,onRecords:(N)=>w.observe(T.sourceId,N.map(Fw)),serviceIdentityEnvironment:(N)=>{if(typeof e.serviceIdentityEnvironment!=="function")throw Error("SERVICE_IDENTITY_UNAVAILABLE: native host callback missing");return e.serviceIdentityEnvironment(N)},push:(N)=>Ne.sourcePush(N)});f.set(T.sourceId,L),y.set(T.sourceId,L)}g=async(T,L)=>{let N=[...f.values()].find((xh)=>T.address.startsWith(`issue:${xh.sourceId}/`));if(N===void 0)return{outcome:"refused",code:"INVALID_ADDRESS"};let Ct=L?.owner?.id??`client:${L?.client??"unknown"}`;return N.assign(T,{workspaceId:t.workspaceId,sourceId:N.sourceId,hostId:A},Ct)};let q=new Set(y.keys()),ke=eh({workspaceId:t.workspaceId,hostId:A,bindings:()=>q,log:e.log,handler:{handle:(T)=>{let L=y.get(T.sourceId);if(L===void 0)return e.log.error(`hightea-source: no handler for ${T.sourceId} although it is bound here`),Promise.resolve({workspaceId:T.workspaceId,sourceId:T.sourceId,hostId:T.hostId,op:T.op,outcome:"refused",code:"SOURCE_UNAVAILABLE"});return L.handle(T)}}}),re;if(t.hostToolsPort!==void 0&&t.mcpUrl!==void 0)try{let T=new xs({mcpUrl:t.mcpUrl,workspaceId:t.workspaceId,configDir:e.configDir,ownAgents:new Set(t.agents.map(([N])=>N)),hostKey:v,gate:I}),L=Sh(T,{port:t.hostToolsPort,resourceMetadataUrl:`http://127.0.0.1:${String(t.hostToolsPort)}/.well-known/oauth-protected-resource`,log:e.log,requiredScopes:fh});if(await L.ready,u){L.stop();return}m=L,re={resource:L.url,name:hh}}catch(T){e.log.error(`${Y}: the Hightea MCP server could not listen on 127.0.0.1:${String(t.hostToolsPort)} (another process may hold it), so no session is offered Hightea tools: ${String(T)}`)}let Ne=Df({dial:(T)=>{let L=new ki(t.cloudUrl,{headers:o,handshakeTimeout:15000,followRedirects:!1});return L.on("unexpected-response",(N,Ct)=>{T(Ct.statusCode??0),Ct.resume(),L.terminate()}),L},receive:(T,L)=>{let N=yh(T);if(N!==null){(e.log.info??e.log.error).call(e.log,_h(N));return}if(ke.receive(T,L))return;En.fromCloud(T)},log:e.log,opened:(T)=>{E??=En.start(Y);let L=()=>{if(u)return;if(e.configDir!==void 0)try{dh(e.configDir)}catch(N){e.log.error(`${Y}: could not clear the refused-start stamp in ${e.configDir}: ${String(N)}`)}if(c||i===void 0||e.configDir===void 0)return;c=!0;try{ch(e.configDir,i)}catch(N){e.log.error(`${Y}: could not stamp this bundle's first connection in ${e.configDir}: ${String(N)}`)}};E.then(L,(N)=>{if(u)return;if(N instanceof vt&&f.size>0){e.log.error(`${Y}: agent conversations unavailable; declared sources remain connected: ${String(N)}`),L();return}if(e.log.error(`${Y}: could not start on the local ahpd: ${String(N)}`),a(N),T.close===void 0)e.log.error(`${Y}: this connection cannot be closed by name`);else T.close(4001,qw(N));b()})}});p=Ne;for(let T of y.values())T.start?.();let dr=Bw(e.connect()),En=new ls(r.peer===void 0?dr:r.peer(dr),Ne,{workspaceId:t.workspaceId,agents:new Map(t.agents),owner:vh,tools:t.mcpUrl===void 0?[]:Hw,...re===void 0?{}:{hostTools:re},startSession:(T,L)=>e.startSession(T,L),log:e.log,store:Mf(e.records("hightea"),vh,(T)=>e.sessionOwner(T),e.log,e.records("hightea/chats")),admitTurn:(T)=>I.admit(T),handshake:{...i===void 0?{}:{plugin:{name:Y,version:i}},ahpd:t.ahpdVersion,capabilities:[nf,of,ln],sources:()=>[...y.keys()]}});d=En}}function _0(e,t){Kw(e,t,{})}export{ls as WakePipe,_0 as apply,Kw as applyWith,Y as name,lh as pageScreenshotArgs,Mf as recordsPipeStore,Bw as shareListener,qw as startFailureReason};
|
|
79
|
+
`,{mode:384}),oh(s,o)}function dh(e){try{Ow(Ss(e,ih))}catch(t){if(t.code!=="ENOENT")throw t}}function kt(e){return{authorization:`Bearer ${e}`,"content-type":"application/json",accept:"application/json, text/event-stream"}}function Aw(e,t,r){if(r===void 0)return Error(`HOUSE_ANSWER_UNREADABLE ${e}: HTTP ${t.status} ${t.statusText===""?"":`${t.statusText} `}— the answer was not JSON`);let n=r.error?.message?.trim()??"",o=r.error?.code===void 0?"":` code ${r.error.code}`,s=/scope="([^"]*)"/u.exec(t.headers.get("www-authenticate")??"")?.[1],i=`HTTP ${t.status}${t.statusText===""?"":` ${t.statusText}`}`;return Error(`HOUSE_REFUSED ${e}: ${i}${o} — ${n===""?"the house gave no message":n}${s===void 0?"":` — the token needs ${s}`}`)}async function bn(e,t,r,n){let o=JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:r,arguments:n}});for(let s=0;;s++){let i,a;try{i=await fetch(e,{method:"POST",headers:t,body:o}),a=await i.text()}catch(d){if(s>=1)throw Error(`HOUSE_UNREACHABLE: ${String(d)}`);continue}let c;try{c=JSON.parse(a)}catch{c=void 0}if(!i.ok||c===void 0||c.error!==void 0)throw Aw(r,i,c);return c}}function lh(e){let t=e??{},r=t.pageId;if(typeof r!=="string"||r.trim().length===0)throw Error("page_screenshot requires a non-empty string pageId");let n={pageId:r};for(let o of["version","width","height"]){let s=t[o];if(s===void 0)continue;if(typeof s!=="number"||!Number.isFinite(s))throw Error(`page_screenshot ${o} must be a number`);n[o]=s}if(t.format!==void 0){if(t.format!=="png"&&t.format!=="webp")throw Error("page_screenshot format is png or webp");n.format=t.format}return n}var ur=[{name:"hightea_thread_read",description:"You were woken by a mention in a Hightea room thread. Read that thread's recent messages first.",inputSchema:{type:"object",properties:{},additionalProperties:!1},readOnly:!0,toHouse:()=>({tool:"thread_read",args:{}})},{name:"hightea_thread_post",description:"Post your reply to the Hightea room thread you were woken in. Call it once with your answer.",inputSchema:{type:"object",properties:{text:{type:"string"}},required:["text"],additionalProperties:!1},toHouse:(e)=>({tool:"room_post",args:{text:String(e.text??"")}})},{name:"hightea_page_read",description:"Read a Hightea page: its current version and content.",inputSchema:{type:"object",properties:{pageId:{type:"string"}},required:["pageId"],additionalProperties:!1},readOnly:!0,toHouse:(e)=>({tool:"page_read",args:{pageId:String(e.pageId??"")}})},{name:"hightea_page_write",description:"Replace a Hightea page's content. Pass the version you read as ifVersion; a stale write is refused.",inputSchema:{type:"object",properties:{pageId:{type:"string"},ifVersion:{type:"number"},content:{type:"string"}},required:["pageId","ifVersion","content"],additionalProperties:!1},toHouse:(e)=>{let t=e;return{tool:"page_write",args:{pageId:String(t.pageId??""),ifVersion:Number(t.ifVersion),content:String(t.content??"")}}}},{name:"hightea_page_screenshot",description:"Capture a Hightea page as a stored image at its live version, then mention the page in your reply so a person sees the capture on the page card. A version that is not the live one is refused by name.",inputSchema:{type:"object",properties:{pageId:{type:"string"},version:{type:"number",description:"Optional expected version; any version that is not live is refused (VERSION_NOT_CURRENT)."},width:{type:"number",description:"Capture width in CSS pixels (16..2400)."},height:{type:"number",description:"Minimum capture height in CSS pixels (16..2400)."},format:{type:"string",enum:["png","webp"]}},required:["pageId"],additionalProperties:!1},toHouse:(e)=>({tool:"page_screenshot",args:lh(e)})}];function vs(e){return ur.find((t)=>t.name===e)}function fh(e){return vs(e)?.readOnly===!0?[ts]:[ts,uf]}var hh="hightea";class Ke extends Error{code;constructor(e,t){super(`${e}: ${t}`);this.code=e}}function $w(e){let t=e.startsWith("hightea://thread/")?e.slice(17):e,r=t.indexOf("?"),n=r<0?t:t.slice(0,r),[o,s,i]=n.split("/");if(!o||!s||i!==void 0)throw new Ke("THREAD_REF_INVALID",`${JSON.stringify(e)} names no room thread (expected hightea://thread/<roomId>/<rootMessageId>)`);return{roomId:o,rootMessageId:s}}function mh(e){let t=e.split("."),r={};if(t.length===3)try{let o=JSON.parse(Buffer.from(t[1]??"","base64url").toString("utf8"));if(o!==null&&typeof o==="object")r=o}catch{r={}}let n=typeof r.scope==="string"?r.scope.split(" ").filter((o)=>o!==""):void 0;return{token:e,...n===void 0?{}:{scopes:n}}}class xs{#e;#o;#r=new Map;#s;constructor(e){this.#e=e,this.#o=e.house??bn}listTools(){return ur.map((e)=>({name:e.name,description:e.description,inputSchema:e.inputSchema,...e.readOnly===!0?{annotations:{readOnlyHint:!0}}:{}}))}async handleRpc(e,t,r){let n=e.id??null;switch(e.method){case"initialize":return{jsonrpc:"2.0",id:n,result:{protocolVersion:String(e.params?.protocolVersion??"2025-06-18"),capabilities:{tools:{}},serverInfo:{name:"hightea",version:"0.1.0"}}};case"ping":return{jsonrpc:"2.0",id:n,result:null};case"tools/list":return{jsonrpc:"2.0",id:n,result:{tools:this.listTools()}};case"tools/call":{let o=e.params?.name;if(typeof o!=="string")return{jsonrpc:"2.0",id:n,error:{code:-32602,message:"tools/call needs a tool name"}};try{if(t===void 0)throw new Ke("TOKEN_EXPIRED_OR_REVOKED","no Hightea token on this request");let s=await this.callTool(o,e.params?.arguments??{},t,r??"");return{jsonrpc:"2.0",id:n,result:s}}catch(s){if(s instanceof Ke||s instanceof Z)return{jsonrpc:"2.0",id:n,result:{content:[{type:"text",text:s.message}],isError:!0}};return{jsonrpc:"2.0",id:n,error:{code:-32603,message:s instanceof Error?s.message:String(s)}}}}default:return{jsonrpc:"2.0",id:n,error:{code:-32601,message:`no method ${String(e.method)}`}}}}async callTool(e,t,r,n){let o=vs(e);if(o===void 0)throw new Ke("TOOL_UNKNOWN",`no Hightea tool is named ${JSON.stringify(e)}`);let{tool:s,args:i}=o.toHouse(t),a=kt(r.token);if(s==="thread_read"||s==="room_post"){let d=await this.#n(r.token),u=$w(d.threadRef),l=`${u.roomId}/${u.rootMessageId}`,p=`${n}|${l}`;if(s==="thread_read"){await this.#c().admit({deliveryId:d.deliveryId,threadRef:l,triggeringMessageIds:d.triggeringMessageIds??[d.deliveryId]},r.token);let g=this.#r.get(p),w=await this.#o(this.#e.mcpUrl,a,"thread_read",{roomId:u.roomId,messageId:u.rootMessageId,...g===void 0?{}:{after:g}}),b=Pw(w),v=b.replies.at(-1)?.id;if(v!==void 0)this.#r.set(p,v);return{content:[{type:"text",text:JSON.stringify(await this.#c().view(l,b))}]}}let f=await this.#e.hostKey;if(f===void 0||f instanceof Error)throw new Ke("HOST_KEY_UNAVAILABLE",`this host cannot sign its agent's post${f instanceof Error?`: ${f.message}`:" (its ahpd names no configDir)"}`);let m=String(i.text??"");a["idempotency-key"]=d.deliveryId;let y=await this.#o(this.#e.mcpUrl,a,"room_post",{text:m,roomId:u.roomId,deliveryId:d.deliveryId,replyId:d.deliveryId,sig:Of(f,{workspaceId:this.#e.workspaceId,roomId:u.roomId,rootMessageId:u.rootMessageId,authorMemberId:d.member,clientId:d.deliveryId,body:m})});return{content:[{type:"text",text:ph(y)}]}}let c=await this.#o(this.#e.mcpUrl,a,s,i);return{content:[{type:"text",text:ph(c)}]}}async#n(e){return(this.#e.turnFacts??((t)=>this.#d(t)))(e)}async#d(e){let t=await this.#o(this.#e.mcpUrl,kt(e),"thread_read",{limit:1});return Nw(t)}#c(){if(this.#e.gate!==void 0)return this.#e.gate;if(this.#s===void 0)this.#s=new sr({configDir:this.#e.configDir,workspaceId:this.#e.workspaceId,ownAgents:this.#e.ownAgents,hostKey:this.#e.hostKey,readThread:async(e,t)=>(await this.#o(this.#e.mcpUrl,kt(e),"thread_read",t)).result?.structuredContent,now:this.#e.now??Date.now});return this.#s}}function Pw(e){let t=e.result?.structuredContent,r=t?.root,n=t?.replies;if(!(t!==void 0&&t!==null&&typeof t==="object"&&r!==void 0&&r!==null&&typeof r==="object"&&typeof r.id==="string"&&r.id!==""&&Array.isArray(n)&&n.every((s)=>s!==null&&typeof s==="object"&&typeof s.id==="string")))throw new Ke("READ_THREAD_INVALID","thread_read returned no valid root/replies paging result");return t}function ph(e){return(e.result?.content??[]).map((t)=>t.text).join(`
|
|
80
|
+
`)}function Nw(e){let r=e.result?.structuredContent?.turn,n=(d)=>{let u=r?.[d];return typeof u==="string"&&u!==""?u:void 0},o=r?.triggeringMessageIds,s=n("roomId"),i=n("messageId"),a=n("deliveryId"),c=n("memberId");if(s===void 0||i===void 0||a===void 0||c===void 0||!Array.isArray(o)||o.some((d)=>typeof d!=="string"))throw new Ke("TURN_FACTS_UNAVAILABLE","the house's answer for this bearer carries no turn (roomId, messageId, deliveryId, memberId, triggeringMessageIds); nothing room-shaped is served rather than inventing one");return{threadRef:`${s}/${i}`,deliveryId:a,member:c,triggeringMessageIds:o}}var gh=/^[A-Za-z0-9_.:-]{1,200}$/u,zw=/^[A-Z_]{1,64}$/u;function yh(e){if(typeof e!=="object"||e===null)return null;if(e.method!=="x-hightea/source/declared")return null;let r=e.params;if(typeof r!=="object"||r===null)return{bound:[],refused:[],dropped:0};let n=(i)=>Array.isArray(i)?i.filter((a)=>typeof a==="string"&&gh.test(a)).slice(0,64):[],o=(i)=>{if(!Array.isArray(i))return[];let a=[];for(let c of i){if(typeof c!=="object"||c===null)continue;let{sourceId:d,code:u,message:l}=c;if(typeof d!=="string"||!gh.test(d)||typeof u!=="string"||!zw.test(u))continue;if(a.push({sourceId:d,code:u,message:typeof l==="string"?l.slice(0,200):""}),a.length===64)break}return a},s=r.dropped;return{bound:n(r.bound),refused:o(r.refused),dropped:typeof s==="number"&&Number.isSafeInteger(s)&&s>=0?s:0}}function _h(e){let t=e.refused.length===0?"none refused":`${String(e.refused.length)} refused: ${e.refused.map((o)=>`${o.sourceId}=${o.code}${o.message===""?"":` (${o.message})`}`).join(", ")}`,r=e.bound.length===0?"none bound":`bound ${e.bound.join(", ")}`,n=e.dropped===0?"":`; ${String(e.dropped)} declared id(s) were not readable`;return`hightea-source: declared sources — ${r}; ${t}${n}`}import{createServer as Mw}from"node:http";function Dw(e){let t=e.headers.get("authorization");if(t===null)return;let[r,...n]=t.split(" ");if(r?.toLowerCase()!=="bearer"||n.length===0)return;let o=n.join(" ").trim();return o===""?void 0:o}function Lw(e){return new Response(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32001,message:"Hightea token required"}}),{status:401,headers:{"content-type":"application/json","www-authenticate":`Bearer resource_metadata="${e.resourceMetadataUrl}"`}})}function Uw(e,t,r){let n=e.requiredScopes?.(t)??[];if(n.length===0)return;let o=r.scopes??[],s=n.filter((i)=>!o.includes(i));if(s.length===0)return;return new Response(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32002,message:`insufficient_scope: ${s.join(" ")}`,error:"insufficient_scope"}}),{status:403,headers:{"content-type":"application/json","www-authenticate":`Bearer error="insufficient_scope", scope="${n.join(" ")}", resource_metadata="${e.resourceMetadataUrl}"`}})}var wh=4194304;function Zw(e,t){return async(r)=>{if(r.method!=="POST")return new Response("Method Not Allowed",{status:405,headers:{allow:"POST"}});let n;try{n=await r.json()}catch{return new Response(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32700,message:"the frame is not JSON"}}),{status:400,headers:{"content-type":"application/json"}})}let o=Dw(r),s=o===void 0?void 0:mh(o);if(n.method==="tools/call"){if(s===void 0)return Lw(t);let d=n.params?.name;if(typeof d==="string"){let u=Uw(t,d,s);if(u!==void 0)return u}}let i=r.headers.get("mcp-session-id")??(n.method==="initialize"?crypto.randomUUID():void 0),a=await e.handleRpc(n,s,i),c={"content-type":"application/json"};if(i!==void 0)c["mcp-session-id"]=i;return new Response(JSON.stringify(a),{status:200,headers:c})}}function Sh(e,t){let r=t.hostname??"127.0.0.1",n=Zw(e,t),o=t.log??{error:(a)=>console.error(a)},s=Mw((a,c)=>void jw(a,c,n,o)),i=new Promise((a,c)=>{let d=(u)=>c(u);s.once("error",d),s.listen(t.port,r,()=>{s.off("error",d),a()})});return i.catch(()=>{return}),{get url(){let a=s.address(),c=typeof a==="object"&&a!==null?a.port:t.port;return`http://${r}:${String(c)}/mcp`},ready:i,stop:()=>{s.closeAllConnections(),s.close()}}}async function jw(e,t,r,n){try{let o=[],s=0;for await(let u of e){if(s+=u.length,s>wh){n.error(`hightea-mcp: a request body over ${String(wh)} bytes was refused (413)`),t.writeHead(413,{"content-type":"application/json"}),t.end(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32600,message:"this server refuses a request body this large"}})),e.destroy();return}o.push(Buffer.from(u))}let i=new Headers;for(let[u,l]of Object.entries(e.headers)){if(l===void 0)continue;if(Array.isArray(l))for(let p of l)i.append(u,p);else i.set(u,l)}let a=Buffer.concat(o),c=await r(new Request(`http://${e.headers.host??"127.0.0.1"}${e.url??"/"}`,{method:e.method??"GET",headers:i,...a.length===0?{}:{body:a}})),d=Buffer.from(await c.arrayBuffer());t.writeHead(c.status,Object.fromEntries(c.headers)),t.end(d)}catch(o){n.error(`hightea-mcp: a request could not be answered: ${o instanceof Error?o.name:typeof o}`),t.writeHead(500,{"content-type":"application/json"}),t.end(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32603,message:"the Hightea MCP server could not answer this request"}}))}}var Fw=(e)=>e.change.op==="delete"?{op:"delete",address:e.change.address,revision:`${e.position.epoch}#${e.position.ordinal}`}:{op:"upsert",address:e.change.row.address,revision:e.change.row.version,scope:e.change.row.scope,columns:e.change.row.columns,extra:e.change.row.extra},Y="hightea-pipe",vh=`plugin:${Y}`,Hw=ur.map((e)=>e.name);function Bw(e){let t=[];return e.onMessage((r)=>{for(let n of t)n(r)}),{request:(r,n,o)=>e.request(r,n,o),notify:(r,n)=>e.notify(r,n),onMessage:(r)=>void t.push(r),close:()=>e.close()}}function qw(e){let t=e instanceof Error?e.message:String(e);if(/wants to be signed in|set the authenticate option/u.test(t))return`AGENT_SIGN_IN_REQUIRED: sign in to ${/^([a-z][a-z0-9_-]{0,19}): /u.exec(t)?.[1]??"the agent backend"}`;if(e instanceof vt||/no matching configured ACP process authority/u.test(t))return"AGENT_START_REFUSED: the agent is not mapped on this host";if(/durable state|invalid durable|RECORD_READ_FAILED/u.test(t))return"HOST_STATE_UNREADABLE: the host's saved state could not be read";if(/answered protocol|initialize|local ahpd/u.test(t))return"AHPD_INIT_FAILED: the local daemon did not answer";return"AGENT_START_REFUSED: the agent could not start"}function Gw(e){let t=e.headers;if(typeof t!=="object"||t===null||Array.isArray(t))throw Error(`${Y}: the plugin entry names no headers (headers), so this host cannot say which Hightea host it is`);return t}function Kw(e,t,r){let n=t.houseId;if(typeof t.workspaceId!=="string"||t.workspaceId===""){if(typeof n!=="string"||n==="")throw Error("hightea-pipe: the plugin entry names no workspace (workspaceId)");t={...t,workspaceId:n}}let o=Gw(t),s=typeof t.pluginVersion==="string"&&t.pluginVersion!==""?{version:t.pluginVersion}:ah(),i="version"in s?s.version:void 0,a=(E)=>{if(e.configDir===void 0)return;try{uh(e.configDir,String(E),i)}catch(A){e.log.error(`${Y}: could not record the refused start in ${e.configDir}: ${String(A)}`)}};if(!("version"in s))e.log.error(`${Y}: hello will name no plugin version: ${s.error}`);let c=!1,d,u=!1,l,p,f=new Map,m,y=new Map,g,w=nh({sources:()=>[...f.values()].map((E)=>({source:E.sourceId,epoch:E.epoch})),log:e.log,assign:async(E,A)=>{if(g===void 0)throw Error("records:assign: no source is listening on this host yet");return g(E,A)}});w.bind(e.registerChannel(th,w.channel)),e.registerGrants(rh,{title:"Board records",description:"Each board source's records as a channel: reading them, and assigning one record's owner against the revision that was read.",operations:[Ie]});let b=async()=>{if(u=!0,l!==void 0)clearTimeout(l);l=void 0,p?.close(),await Promise.all([...y.values()].map((E)=>E.stop?.()))};e.registerClose(b),e.registerClose(()=>m?.stop());let v=e.configDir===void 0?Promise.resolve(void 0):Rf(e.configDir).catch((E)=>{let A=E instanceof Error?E:Error(String(E));return e.log.error(`${Y}: ${A.message}`),A}),x=new sr({configDir:e.configDir,workspaceId:t.workspaceId,ownAgents:new Set(t.agents.map(([E])=>E)),hostKey:v,readThread:async(E,A)=>{if(t.mcpUrl===void 0)throw new Z("ROOM_ASKS_UNTRUSTED","this host has no house MCP endpoint to read the ask from");return(await bn(t.mcpUrl,kt(E),"thread_read",A)).result?.structuredContent}}),I=r.askGate??x;if(e.registerSessionMeta===void 0)e.log.error(`${Y}: this ahpd cannot publish a session's member (registerSessionMeta is absent), so Hightea page rows for its sessions will name none`);else e.registerSessionMeta("hh/agentMemberId",(E)=>d?.agentMemberOf(E));e.on("listening",()=>{if(u||l!==void 0||p!==void 0)return;l=setTimeout(()=>{l=void 0,R().catch((E)=>{e.log.error(`${Y}: the host could not start its connections: ${String(E)}`),a(E)})},100)});async function R(){if(u)return;let E,A=o[mf]??o[gf]??"";f=new Map,y=new Map;for(let T of t.sources??[]){if(Xf(T)){y.set(T.sourceId,new ws({config:T,workspaceId:t.workspaceId,hostId:A,log:e.log,push:(N)=>Ne.sourcePush(N),...r.sourceChildren===void 0?{}:{run:r.sourceChildren.run}}));continue}if(T.kind!==void 0&&T.kind!=="km")throw Error(`${Y}: the plugin entry names a source kind it cannot construct (${JSON.stringify(T.kind)}) for ${T.sourceId}, so this start is refused rather than offering it as km`);let L=new gs({config:T,workspaceId:t.workspaceId,hostId:A,log:e.log,...r.sourceChildren,onRecords:(N)=>w.observe(T.sourceId,N.map(Fw)),serviceIdentityEnvironment:(N)=>{if(typeof e.serviceIdentityEnvironment!=="function")throw Error("SERVICE_IDENTITY_UNAVAILABLE: native host callback missing");return e.serviceIdentityEnvironment(N)},push:(N)=>Ne.sourcePush(N)});f.set(T.sourceId,L),y.set(T.sourceId,L)}g=async(T,L)=>{let N=[...f.values()].find((xh)=>T.address.startsWith(`issue:${xh.sourceId}/`));if(N===void 0)return{outcome:"refused",code:"INVALID_ADDRESS"};let Ct=L?.owner?.id??`client:${L?.client??"unknown"}`;return N.assign(T,{workspaceId:t.workspaceId,sourceId:N.sourceId,hostId:A},Ct)};let q=new Set(y.keys()),ke=eh({workspaceId:t.workspaceId,hostId:A,bindings:()=>q,log:e.log,handler:{handle:(T)=>{let L=y.get(T.sourceId);if(L===void 0)return e.log.error(`hightea-source: no handler for ${T.sourceId} although it is bound here`),Promise.resolve({workspaceId:T.workspaceId,sourceId:T.sourceId,hostId:T.hostId,op:T.op,outcome:"refused",code:"SOURCE_UNAVAILABLE"});return L.handle(T)}}}),re;if(t.hostToolsPort!==void 0&&t.mcpUrl!==void 0)try{let T=new xs({mcpUrl:t.mcpUrl,workspaceId:t.workspaceId,configDir:e.configDir,ownAgents:new Set(t.agents.map(([N])=>N)),hostKey:v,gate:I}),L=Sh(T,{port:t.hostToolsPort,resourceMetadataUrl:`http://127.0.0.1:${String(t.hostToolsPort)}/.well-known/oauth-protected-resource`,log:e.log,requiredScopes:fh});if(await L.ready,u){L.stop();return}m=L,re={resource:L.url,name:hh}}catch(T){e.log.error(`${Y}: the Hightea MCP server could not listen on 127.0.0.1:${String(t.hostToolsPort)} (another process may hold it), so no session is offered Hightea tools: ${String(T)}`)}let Ne=Df({dial:(T)=>{let L=new ki(t.cloudUrl,{headers:o,handshakeTimeout:15000,followRedirects:!1});return L.on("unexpected-response",(N,Ct)=>{T(Ct.statusCode??0),Ct.resume(),L.terminate()}),L},receive:(T,L)=>{let N=yh(T);if(N!==null){(e.log.info??e.log.error).call(e.log,_h(N));return}if(ke.receive(T,L))return;En.fromCloud(T)},log:e.log,opened:(T)=>{E??=En.start(Y);let L=()=>{if(u)return;if(e.configDir!==void 0)try{dh(e.configDir)}catch(N){e.log.error(`${Y}: could not clear the refused-start stamp in ${e.configDir}: ${String(N)}`)}if(c||i===void 0||e.configDir===void 0)return;c=!0;try{ch(e.configDir,i)}catch(N){e.log.error(`${Y}: could not stamp this bundle's first connection in ${e.configDir}: ${String(N)}`)}};E.then(L,(N)=>{if(u)return;if(N instanceof vt&&f.size>0){e.log.error(`${Y}: agent conversations unavailable; declared sources remain connected: ${String(N)}`),L();return}if(e.log.error(`${Y}: could not start on the local ahpd: ${String(N)}`),a(N),T.close===void 0)e.log.error(`${Y}: this connection cannot be closed by name`);else T.close(4001,qw(N));b()})}});p=Ne;for(let T of y.values())T.start?.();let dr=Bw(e.connect()),En=new ls(r.peer===void 0?dr:r.peer(dr),Ne,{workspaceId:t.workspaceId,agents:new Map(t.agents),owner:vh,tools:t.mcpUrl===void 0?[]:Hw,...re===void 0?{}:{hostTools:re},startSession:(T,L)=>e.startSession(T,L),log:e.log,store:Mf(e.records("hightea"),vh,(T)=>e.sessionOwner(T),e.log,e.records("hightea/chats")),admitTurn:(T)=>I.admit(T),handshake:{...i===void 0?{}:{plugin:{name:Y,version:i}},ahpd:t.ahpdVersion,capabilities:[nf,of,ln],sources:()=>[...y.keys()]}});d=En}}function _0(e,t){Kw(e,t,{})}export{ls as WakePipe,_0 as apply,Kw as applyWith,Y as name,lh as pageScreenshotArgs,Mf as recordsPipeStore,Bw as shareListener,qw as startFailureReason};
|