@agent-team-foundation/first-tree-hub 0.6.2 → 0.6.3

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.
@@ -260,7 +260,7 @@ Please change the parent <Route path="${R}"> to <Route path="${R==="/"?"*":`${R}
260
260
 
261
261
  `)}w.write("payload.value = newResult;"),w.write("return payload;");const Q=w.compile();return(B,F)=>Q(j,B,F)};let d;const h=Bi,m=!c0.jitless,p=m&&Q2.value,x=a.catchall;let b;t._zod.parse=(j,w)=>{b??(b=s.value);const C=j.value;return h(C)?m&&p&&(w==null?void 0:w.async)===!1&&w.jitless!==!0?(d||(d=o(a.shape)),j=d(j,w),x?C0([],C,j,w,b,t):j):l(j,w):(j.issues.push({expected:"object",code:"invalid_type",input:C,inst:t}),j)}});function Jy(t,a,l,s){for(const d of t)if(d.issues.length===0)return a.value=d.value,a;const o=t.filter(d=>!is(d));return o.length===1?(a.value=o[0].value,o[0]):(a.issues.push({code:"invalid_union",input:a.value,inst:l,errors:t.map(d=>d.issues.map(h=>Cr(h,s,Er())))}),a)}const A0=I("$ZodUnion",(t,a)=>{ft.init(t,a),Ye(t._zod,"optin",()=>a.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Ye(t._zod,"optout",()=>a.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Ye(t._zod,"values",()=>{if(a.options.every(o=>o._zod.values))return new Set(a.options.flatMap(o=>Array.from(o._zod.values)))}),Ye(t._zod,"pattern",()=>{if(a.options.every(o=>o._zod.pattern)){const o=a.options.map(d=>d._zod.pattern);return new RegExp(`^(${o.map(d=>Kh(d.source)).join("|")})$`)}});const l=a.options.length===1,s=a.options[0]._zod.run;t._zod.parse=(o,d)=>{if(l)return s(o,d);let h=!1;const m=[];for(const g of a.options){const p=g._zod.run({value:o.value,issues:[]},d);if(p instanceof Promise)m.push(p),h=!0;else{if(p.issues.length===0)return p;m.push(p)}}return h?Promise.all(m).then(g=>Jy(g,o,t,d)):Jy(m,o,t,d)}}),TA=I("$ZodDiscriminatedUnion",(t,a)=>{a.inclusive=!1,A0.init(t,a);const l=t._zod.parse;Ye(t._zod,"propValues",()=>{const o={};for(const d of a.options){const h=d._zod.propValues;if(!h||Object.keys(h).length===0)throw new Error(`Invalid discriminated union option at index "${a.options.indexOf(d)}"`);for(const[m,g]of Object.entries(h)){o[m]||(o[m]=new Set);for(const p of g)o[m].add(p)}}return o});const s=Wu(()=>{var h;const o=a.options,d=new Map;for(const m of o){const g=(h=m._zod.propValues)==null?void 0:h[a.discriminator];if(!g||g.size===0)throw new Error(`Invalid discriminated union option at index "${a.options.indexOf(m)}"`);for(const p of g){if(d.has(p))throw new Error(`Duplicate discriminator value "${String(p)}"`);d.set(p,m)}}return d});t._zod.parse=(o,d)=>{const h=o.value;if(!Bi(h))return o.issues.push({code:"invalid_type",expected:"object",input:h,inst:t}),o;const m=s.value.get(h==null?void 0:h[a.discriminator]);return m?m._zod.run(o,d):a.unionFallback?l(o,d):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:a.discriminator,input:h,path:[a.discriminator],inst:t}),o)}}),zA=I("$ZodIntersection",(t,a)=>{ft.init(t,a),t._zod.parse=(l,s)=>{const o=l.value,d=a.left._zod.run({value:o,issues:[]},s),h=a.right._zod.run({value:o,issues:[]},s);return d instanceof Promise||h instanceof Promise?Promise.all([d,h]).then(([g,p])=>Wy(l,g,p)):Wy(l,d,h)}});function xh(t,a){if(t===a)return{valid:!0,data:t};if(t instanceof Date&&a instanceof Date&&+t==+a)return{valid:!0,data:t};if(_s(t)&&_s(a)){const l=Object.keys(a),s=Object.keys(t).filter(d=>l.indexOf(d)!==-1),o={...t,...a};for(const d of s){const h=xh(t[d],a[d]);if(!h.valid)return{valid:!1,mergeErrorPath:[d,...h.mergeErrorPath]};o[d]=h.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(a)){if(t.length!==a.length)return{valid:!1,mergeErrorPath:[]};const l=[];for(let s=0;s<t.length;s++){const o=t[s],d=a[s],h=xh(o,d);if(!h.valid)return{valid:!1,mergeErrorPath:[s,...h.mergeErrorPath]};l.push(h.data)}return{valid:!0,data:l}}return{valid:!1,mergeErrorPath:[]}}function Wy(t,a,l){const s=new Map;let o;for(const m of a.issues)if(m.code==="unrecognized_keys"){o??(o=m);for(const g of m.keys)s.has(g)||s.set(g,{}),s.get(g).l=!0}else t.issues.push(m);for(const m of l.issues)if(m.code==="unrecognized_keys")for(const g of m.keys)s.has(g)||s.set(g,{}),s.get(g).r=!0;else t.issues.push(m);const d=[...s].filter(([,m])=>m.l&&m.r).map(([m])=>m);if(d.length&&o&&t.issues.push({...o,keys:d}),is(t))return t;const h=xh(a.value,l.value);if(!h.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(h.mergeErrorPath)}`);return t.value=h.data,t}const OA=I("$ZodRecord",(t,a)=>{ft.init(t,a),t._zod.parse=(l,s)=>{const o=l.value;if(!_s(o))return l.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),l;const d=[],h=a.keyType._zod.values;if(h){l.value={};const m=new Set;for(const p of h)if(typeof p=="string"||typeof p=="number"||typeof p=="symbol"){m.add(typeof p=="number"?p.toString():p);const x=a.valueType._zod.run({value:o[p],issues:[]},s);x instanceof Promise?d.push(x.then(b=>{b.issues.length&&l.issues.push(...os(p,b.issues)),l.value[p]=b.value})):(x.issues.length&&l.issues.push(...os(p,x.issues)),l.value[p]=x.value)}let g;for(const p in o)m.has(p)||(g=g??[],g.push(p));g&&g.length>0&&l.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:g})}else{l.value={};for(const m of Reflect.ownKeys(o)){if(m==="__proto__")continue;let g=a.keyType._zod.run({value:m,issues:[]},s);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof m=="string"&&x0.test(m)&&g.issues.length){const b=a.keyType._zod.run({value:Number(m),issues:[]},s);if(b instanceof Promise)throw new Error("Async schemas not supported in object keys currently");b.issues.length===0&&(g=b)}if(g.issues.length){a.mode==="loose"?l.value[m]=o[m]:l.issues.push({code:"invalid_key",origin:"record",issues:g.issues.map(b=>Cr(b,s,Er())),input:m,path:[m],inst:t});continue}const x=a.valueType._zod.run({value:o[m],issues:[]},s);x instanceof Promise?d.push(x.then(b=>{b.issues.length&&l.issues.push(...os(m,b.issues)),l.value[g.value]=b.value})):(x.issues.length&&l.issues.push(...os(m,x.issues)),l.value[g.value]=x.value)}}return d.length?Promise.all(d).then(()=>l):l}}),RA=I("$ZodEnum",(t,a)=>{ft.init(t,a);const l=d0(a.entries),s=new Set(l);t._zod.values=s,t._zod.pattern=new RegExp(`^(${l.filter(o=>G2.has(typeof o)).map(o=>typeof o=="string"?Es(o):o.toString()).join("|")})$`),t._zod.parse=(o,d)=>{const h=o.value;return s.has(h)||o.issues.push({code:"invalid_value",values:l,input:h,inst:t}),o}}),MA=I("$ZodLiteral",(t,a)=>{if(ft.init(t,a),a.values.length===0)throw new Error("Cannot create literal schema with no valid values");const l=new Set(a.values);t._zod.values=l,t._zod.pattern=new RegExp(`^(${a.values.map(s=>typeof s=="string"?Es(s):s?Es(s.toString()):String(s)).join("|")})$`),t._zod.parse=(s,o)=>{const d=s.value;return l.has(d)||s.issues.push({code:"invalid_value",values:a.values,input:d,inst:t}),s}}),kA=I("$ZodTransform",(t,a)=>{ft.init(t,a),t._zod.parse=(l,s)=>{if(s.direction==="backward")throw new u0(t.constructor.name);const o=a.transform(l.value,l);if(s.async)return(o instanceof Promise?o:Promise.resolve(o)).then(h=>(l.value=h,l));if(o instanceof Promise)throw new us;return l.value=o,l}});function eb(t,a){return t.issues.length&&a===void 0?{issues:[],value:void 0}:t}const T0=I("$ZodOptional",(t,a)=>{ft.init(t,a),t._zod.optin="optional",t._zod.optout="optional",Ye(t._zod,"values",()=>a.innerType._zod.values?new Set([...a.innerType._zod.values,void 0]):void 0),Ye(t._zod,"pattern",()=>{const l=a.innerType._zod.pattern;return l?new RegExp(`^(${Kh(l.source)})?$`):void 0}),t._zod.parse=(l,s)=>{if(a.innerType._zod.optin==="optional"){const o=a.innerType._zod.run(l,s);return o instanceof Promise?o.then(d=>eb(d,l.value)):eb(o,l.value)}return l.value===void 0?l:a.innerType._zod.run(l,s)}}),DA=I("$ZodExactOptional",(t,a)=>{T0.init(t,a),Ye(t._zod,"values",()=>a.innerType._zod.values),Ye(t._zod,"pattern",()=>a.innerType._zod.pattern),t._zod.parse=(l,s)=>a.innerType._zod.run(l,s)}),UA=I("$ZodNullable",(t,a)=>{ft.init(t,a),Ye(t._zod,"optin",()=>a.innerType._zod.optin),Ye(t._zod,"optout",()=>a.innerType._zod.optout),Ye(t._zod,"pattern",()=>{const l=a.innerType._zod.pattern;return l?new RegExp(`^(${Kh(l.source)}|null)$`):void 0}),Ye(t._zod,"values",()=>a.innerType._zod.values?new Set([...a.innerType._zod.values,null]):void 0),t._zod.parse=(l,s)=>l.value===null?l:a.innerType._zod.run(l,s)}),LA=I("$ZodDefault",(t,a)=>{ft.init(t,a),t._zod.optin="optional",Ye(t._zod,"values",()=>a.innerType._zod.values),t._zod.parse=(l,s)=>{if(s.direction==="backward")return a.innerType._zod.run(l,s);if(l.value===void 0)return l.value=a.defaultValue,l;const o=a.innerType._zod.run(l,s);return o instanceof Promise?o.then(d=>tb(d,a)):tb(o,a)}});function tb(t,a){return t.value===void 0&&(t.value=a.defaultValue),t}const ZA=I("$ZodPrefault",(t,a)=>{ft.init(t,a),t._zod.optin="optional",Ye(t._zod,"values",()=>a.innerType._zod.values),t._zod.parse=(l,s)=>(s.direction==="backward"||l.value===void 0&&(l.value=a.defaultValue),a.innerType._zod.run(l,s))}),qA=I("$ZodNonOptional",(t,a)=>{ft.init(t,a),Ye(t._zod,"values",()=>{const l=a.innerType._zod.values;return l?new Set([...l].filter(s=>s!==void 0)):void 0}),t._zod.parse=(l,s)=>{const o=a.innerType._zod.run(l,s);return o instanceof Promise?o.then(d=>nb(d,t)):nb(o,t)}});function nb(t,a){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:a}),t}const BA=I("$ZodCatch",(t,a)=>{ft.init(t,a),Ye(t._zod,"optin",()=>a.innerType._zod.optin),Ye(t._zod,"optout",()=>a.innerType._zod.optout),Ye(t._zod,"values",()=>a.innerType._zod.values),t._zod.parse=(l,s)=>{if(s.direction==="backward")return a.innerType._zod.run(l,s);const o=a.innerType._zod.run(l,s);return o instanceof Promise?o.then(d=>(l.value=d.value,d.issues.length&&(l.value=a.catchValue({...l,error:{issues:d.issues.map(h=>Cr(h,s,Er()))},input:l.value}),l.issues=[]),l)):(l.value=o.value,o.issues.length&&(l.value=a.catchValue({...l,error:{issues:o.issues.map(d=>Cr(d,s,Er()))},input:l.value}),l.issues=[]),l)}}),$A=I("$ZodPipe",(t,a)=>{ft.init(t,a),Ye(t._zod,"values",()=>a.in._zod.values),Ye(t._zod,"optin",()=>a.in._zod.optin),Ye(t._zod,"optout",()=>a.out._zod.optout),Ye(t._zod,"propValues",()=>a.in._zod.propValues),t._zod.parse=(l,s)=>{if(s.direction==="backward"){const d=a.out._zod.run(l,s);return d instanceof Promise?d.then(h=>Cu(h,a.in,s)):Cu(d,a.in,s)}const o=a.in._zod.run(l,s);return o instanceof Promise?o.then(d=>Cu(d,a.out,s)):Cu(o,a.out,s)}});function Cu(t,a,l){return t.issues.length?(t.aborted=!0,t):a._zod.run({value:t.value,issues:t.issues},l)}const HA=I("$ZodReadonly",(t,a)=>{ft.init(t,a),Ye(t._zod,"propValues",()=>a.innerType._zod.propValues),Ye(t._zod,"values",()=>a.innerType._zod.values),Ye(t._zod,"optin",()=>{var l,s;return(s=(l=a.innerType)==null?void 0:l._zod)==null?void 0:s.optin}),Ye(t._zod,"optout",()=>{var l,s;return(s=(l=a.innerType)==null?void 0:l._zod)==null?void 0:s.optout}),t._zod.parse=(l,s)=>{if(s.direction==="backward")return a.innerType._zod.run(l,s);const o=a.innerType._zod.run(l,s);return o instanceof Promise?o.then(ab):ab(o)}});function ab(t){return t.value=Object.freeze(t.value),t}const QA=I("$ZodCustom",(t,a)=>{cn.init(t,a),ft.init(t,a),t._zod.parse=(l,s)=>l,t._zod.check=l=>{const s=l.value,o=a.fn(s);if(o instanceof Promise)return o.then(d=>rb(d,l,s,t));rb(o,l,s,t)}});function rb(t,a,l,s){if(!t){const o={code:"custom",input:l,inst:s,path:[...s._zod.def.path??[]],continue:!s._zod.def.abort};s._zod.def.params&&(o.params=s._zod.def.params),a.issues.push($i(o))}}var lb;class GA{constructor(){this._map=new WeakMap,this._idmap=new Map}add(a,...l){const s=l[0];return this._map.set(a,s),s&&typeof s=="object"&&"id"in s&&this._idmap.set(s.id,a),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(a){const l=this._map.get(a);return l&&typeof l=="object"&&"id"in l&&this._idmap.delete(l.id),this._map.delete(a),this}get(a){const l=a._zod.parent;if(l){const s={...this.get(l)??{}};delete s.id;const o={...s,...this._map.get(a)};return Object.keys(o).length?o:void 0}return this._map.get(a)}has(a){return this._map.has(a)}}function IA(){return new GA}(lb=globalThis).__zod_globalRegistry??(lb.__zod_globalRegistry=IA());const ki=globalThis.__zod_globalRegistry;function VA(t,a){return new t({type:"string",...he(a)})}function YA(t,a){return new t({type:"string",format:"email",check:"string_format",abort:!1,...he(a)})}function sb(t,a){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...he(a)})}function KA(t,a){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...he(a)})}function PA(t,a){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...he(a)})}function FA(t,a){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...he(a)})}function XA(t,a){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...he(a)})}function JA(t,a){return new t({type:"string",format:"url",check:"string_format",abort:!1,...he(a)})}function WA(t,a){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...he(a)})}function eT(t,a){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...he(a)})}function tT(t,a){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...he(a)})}function nT(t,a){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...he(a)})}function aT(t,a){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...he(a)})}function rT(t,a){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...he(a)})}function lT(t,a){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...he(a)})}function sT(t,a){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...he(a)})}function iT(t,a){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...he(a)})}function oT(t,a){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...he(a)})}function uT(t,a){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...he(a)})}function cT(t,a){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...he(a)})}function dT(t,a){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...he(a)})}function fT(t,a){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...he(a)})}function hT(t,a){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...he(a)})}function mT(t,a){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...he(a)})}function pT(t,a){return new t({type:"string",format:"date",check:"string_format",...he(a)})}function gT(t,a){return new t({type:"string",format:"time",check:"string_format",precision:null,...he(a)})}function vT(t,a){return new t({type:"string",format:"duration",check:"string_format",...he(a)})}function yT(t,a){return new t({type:"number",checks:[],...he(a)})}function bT(t,a){return new t({type:"number",coerce:!0,checks:[],...he(a)})}function xT(t,a){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...he(a)})}function ST(t,a){return new t({type:"boolean",...he(a)})}function jT(t){return new t({type:"unknown"})}function NT(t,a){return new t({type:"never",...he(a)})}function ib(t,a){return new j0({check:"less_than",...he(a),value:t,inclusive:!1})}function Zf(t,a){return new j0({check:"less_than",...he(a),value:t,inclusive:!0})}function ob(t,a){return new N0({check:"greater_than",...he(a),value:t,inclusive:!1})}function qf(t,a){return new N0({check:"greater_than",...he(a),value:t,inclusive:!0})}function ub(t,a){return new LC({check:"multiple_of",...he(a),value:t})}function z0(t,a){return new qC({check:"max_length",...he(a),maximum:t})}function Iu(t,a){return new BC({check:"min_length",...he(a),minimum:t})}function O0(t,a){return new $C({check:"length_equals",...he(a),length:t})}function wT(t,a){return new HC({check:"string_format",format:"regex",...he(a),pattern:t})}function _T(t){return new QC({check:"string_format",format:"lowercase",...he(t)})}function ET(t){return new GC({check:"string_format",format:"uppercase",...he(t)})}function CT(t,a){return new IC({check:"string_format",format:"includes",...he(a),includes:t})}function AT(t,a){return new VC({check:"string_format",format:"starts_with",...he(a),prefix:t})}function TT(t,a){return new YC({check:"string_format",format:"ends_with",...he(a),suffix:t})}function Rs(t){return new KC({check:"overwrite",tx:t})}function zT(t){return Rs(a=>a.normalize(t))}function OT(){return Rs(t=>t.trim())}function RT(){return Rs(t=>t.toLowerCase())}function MT(){return Rs(t=>t.toUpperCase())}function kT(){return Rs(t=>H2(t))}function DT(t,a,l){return new t({type:"array",element:a,...he(l)})}function UT(t,a,l){return new t({type:"custom",check:"custom",fn:a,...he(l)})}function LT(t){const a=ZT(l=>(l.addIssue=s=>{if(typeof s=="string")l.issues.push($i(s,l.value,a._zod.def));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=l.value),o.inst??(o.inst=a),o.continue??(o.continue=!a._zod.def.abort),l.issues.push($i(o))}},t(l.value,l)));return a}function ZT(t,a){const l=new cn({check:"custom",...he(a)});return l._zod.check=t,l}function R0(t){let a=(t==null?void 0:t.target)??"draft-2020-12";return a==="draft-4"&&(a="draft-04"),a==="draft-7"&&(a="draft-07"),{processors:t.processors??{},metadataRegistry:(t==null?void 0:t.metadata)??ki,target:a,unrepresentable:(t==null?void 0:t.unrepresentable)??"throw",override:(t==null?void 0:t.override)??(()=>{}),io:(t==null?void 0:t.io)??"output",counter:0,seen:new Map,cycles:(t==null?void 0:t.cycles)??"ref",reused:(t==null?void 0:t.reused)??"inline",external:(t==null?void 0:t.external)??void 0}}function Ct(t,a,l={path:[],schemaPath:[]}){var x,b;var s;const o=t._zod.def,d=a.seen.get(t);if(d)return d.count++,l.schemaPath.includes(t)&&(d.cycle=l.path),d.schema;const h={schema:{},count:1,cycle:void 0,path:l.path};a.seen.set(t,h);const m=(b=(x=t._zod).toJSONSchema)==null?void 0:b.call(x);if(m)h.schema=m;else{const j={...l,schemaPath:[...l.schemaPath,t],path:l.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(a,h.schema,j);else{const C=h.schema,N=a.processors[o.type];if(!N)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);N(t,a,C,j)}const w=t._zod.parent;w&&(h.ref||(h.ref=w),Ct(w,a,j),a.seen.get(w).isParent=!0)}const g=a.metadataRegistry.get(t);return g&&Object.assign(h.schema,g),a.io==="input"&&Kt(t)&&(delete h.schema.examples,delete h.schema.default),a.io==="input"&&h.schema._prefault&&((s=h.schema).default??(s.default=h.schema._prefault)),delete h.schema._prefault,a.seen.get(t).schema}function M0(t,a){var h,m,g,p;const l=t.seen.get(a);if(!l)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=new Map;for(const x of t.seen.entries()){const b=(h=t.metadataRegistry.get(x[0]))==null?void 0:h.id;if(b){const j=s.get(b);if(j&&j!==x[0])throw new Error(`Duplicate schema id "${b}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);s.set(b,x[0])}}const o=x=>{var N;const b=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){const _=(N=t.external.registry.get(x[0]))==null?void 0:N.id,R=t.external.uri??(q=>q);if(_)return{ref:R(_)};const Q=x[1].defId??x[1].schema.id??`schema${t.counter++}`;return x[1].defId=Q,{defId:Q,ref:`${R("__shared")}#/${b}/${Q}`}}if(x[1]===l)return{ref:"#"};const w=`#/${b}/`,C=x[1].schema.id??`__schema${t.counter++}`;return{defId:C,ref:w+C}},d=x=>{if(x[1].schema.$ref)return;const b=x[1],{ref:j,defId:w}=o(x);b.def={...b.schema},w&&(b.defId=w);const C=b.schema;for(const N in C)delete C[N];C.$ref=j};if(t.cycles==="throw")for(const x of t.seen.entries()){const b=x[1];if(b.cycle)throw new Error(`Cycle detected: #/${(m=b.cycle)==null?void 0:m.join("/")}/<root>
262
262
 
263
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const x of t.seen.entries()){const b=x[1];if(a===x[0]){d(x);continue}if(t.external){const w=(g=t.external.registry.get(x[0]))==null?void 0:g.id;if(a!==x[0]&&w){d(x);continue}}if((p=t.metadataRegistry.get(x[0]))==null?void 0:p.id){d(x);continue}if(b.cycle){d(x);continue}if(b.count>1&&t.reused==="ref"){d(x);continue}}}function k0(t,a){var h,m,g;const l=t.seen.get(a);if(!l)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=p=>{const x=t.seen.get(p);if(x.ref===null)return;const b=x.def??x.schema,j={...b},w=x.ref;if(x.ref=null,w){s(w);const N=t.seen.get(w),_=N.schema;if(_.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(b.allOf=b.allOf??[],b.allOf.push(_)):Object.assign(b,_),Object.assign(b,j),p._zod.parent===w)for(const Q in b)Q==="$ref"||Q==="allOf"||Q in j||delete b[Q];if(_.$ref&&N.def)for(const Q in b)Q==="$ref"||Q==="allOf"||Q in N.def&&JSON.stringify(b[Q])===JSON.stringify(N.def[Q])&&delete b[Q]}const C=p._zod.parent;if(C&&C!==w){s(C);const N=t.seen.get(C);if(N!=null&&N.schema.$ref&&(b.$ref=N.schema.$ref,N.def))for(const _ in b)_==="$ref"||_==="allOf"||_ in N.def&&JSON.stringify(b[_])===JSON.stringify(N.def[_])&&delete b[_]}t.override({zodSchema:p,jsonSchema:b,path:x.path??[]})};for(const p of[...t.seen.entries()].reverse())s(p[0]);const o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,(h=t.external)!=null&&h.uri){const p=(m=t.external.registry.get(a))==null?void 0:m.id;if(!p)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(p)}Object.assign(o,l.def??l.schema);const d=((g=t.external)==null?void 0:g.defs)??{};for(const p of t.seen.entries()){const x=p[1];x.def&&x.defId&&(d[x.defId]=x.def)}t.external||Object.keys(d).length>0&&(t.target==="draft-2020-12"?o.$defs=d:o.definitions=d);try{const p=JSON.parse(JSON.stringify(o));return Object.defineProperty(p,"~standard",{value:{...a["~standard"],jsonSchema:{input:Vu(a,"input",t.processors),output:Vu(a,"output",t.processors)}},enumerable:!1,writable:!1}),p}catch{throw new Error("Error converting schema to JSON.")}}function Kt(t,a){const l=a??{seen:new Set};if(l.seen.has(t))return!1;l.seen.add(t);const s=t._zod.def;if(s.type==="transform")return!0;if(s.type==="array")return Kt(s.element,l);if(s.type==="set")return Kt(s.valueType,l);if(s.type==="lazy")return Kt(s.getter(),l);if(s.type==="promise"||s.type==="optional"||s.type==="nonoptional"||s.type==="nullable"||s.type==="readonly"||s.type==="default"||s.type==="prefault")return Kt(s.innerType,l);if(s.type==="intersection")return Kt(s.left,l)||Kt(s.right,l);if(s.type==="record"||s.type==="map")return Kt(s.keyType,l)||Kt(s.valueType,l);if(s.type==="pipe")return Kt(s.in,l)||Kt(s.out,l);if(s.type==="object"){for(const o in s.shape)if(Kt(s.shape[o],l))return!0;return!1}if(s.type==="union"){for(const o of s.options)if(Kt(o,l))return!0;return!1}if(s.type==="tuple"){for(const o of s.items)if(Kt(o,l))return!0;return!!(s.rest&&Kt(s.rest,l))}return!1}const qT=(t,a={})=>l=>{const s=R0({...l,processors:a});return Ct(t,s),M0(s,t),k0(s,t)},Vu=(t,a,l={})=>s=>{const{libraryOptions:o,target:d}=s??{},h=R0({...o??{},target:d,io:a,processors:l});return Ct(t,h),M0(h,t),k0(h,t)},BT={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},$T=(t,a,l,s)=>{const o=l;o.type="string";const{minimum:d,maximum:h,format:m,patterns:g,contentEncoding:p}=t._zod.bag;if(typeof d=="number"&&(o.minLength=d),typeof h=="number"&&(o.maxLength=h),m&&(o.format=BT[m]??m,o.format===""&&delete o.format,m==="time"&&delete o.format),p&&(o.contentEncoding=p),g&&g.size>0){const x=[...g];x.length===1?o.pattern=x[0].source:x.length>1&&(o.allOf=[...x.map(b=>({...a.target==="draft-07"||a.target==="draft-04"||a.target==="openapi-3.0"?{type:"string"}:{},pattern:b.source}))])}},HT=(t,a,l,s)=>{const o=l,{minimum:d,maximum:h,format:m,multipleOf:g,exclusiveMaximum:p,exclusiveMinimum:x}=t._zod.bag;typeof m=="string"&&m.includes("int")?o.type="integer":o.type="number",typeof x=="number"&&(a.target==="draft-04"||a.target==="openapi-3.0"?(o.minimum=x,o.exclusiveMinimum=!0):o.exclusiveMinimum=x),typeof d=="number"&&(o.minimum=d,typeof x=="number"&&a.target!=="draft-04"&&(x>=d?delete o.minimum:delete o.exclusiveMinimum)),typeof p=="number"&&(a.target==="draft-04"||a.target==="openapi-3.0"?(o.maximum=p,o.exclusiveMaximum=!0):o.exclusiveMaximum=p),typeof h=="number"&&(o.maximum=h,typeof p=="number"&&a.target!=="draft-04"&&(p<=h?delete o.maximum:delete o.exclusiveMaximum)),typeof g=="number"&&(o.multipleOf=g)},QT=(t,a,l,s)=>{l.type="boolean"},GT=(t,a,l,s)=>{l.not={}},IT=(t,a,l,s)=>{},VT=(t,a,l,s)=>{const o=t._zod.def,d=d0(o.entries);d.every(h=>typeof h=="number")&&(l.type="number"),d.every(h=>typeof h=="string")&&(l.type="string"),l.enum=d},YT=(t,a,l,s)=>{const o=t._zod.def,d=[];for(const h of o.values)if(h===void 0){if(a.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof h=="bigint"){if(a.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");d.push(Number(h))}else d.push(h);if(d.length!==0)if(d.length===1){const h=d[0];l.type=h===null?"null":typeof h,a.target==="draft-04"||a.target==="openapi-3.0"?l.enum=[h]:l.const=h}else d.every(h=>typeof h=="number")&&(l.type="number"),d.every(h=>typeof h=="string")&&(l.type="string"),d.every(h=>typeof h=="boolean")&&(l.type="boolean"),d.every(h=>h===null)&&(l.type="null"),l.enum=d},KT=(t,a,l,s)=>{if(a.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},PT=(t,a,l,s)=>{if(a.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},FT=(t,a,l,s)=>{const o=l,d=t._zod.def,{minimum:h,maximum:m}=t._zod.bag;typeof h=="number"&&(o.minItems=h),typeof m=="number"&&(o.maxItems=m),o.type="array",o.items=Ct(d.element,a,{...s,path:[...s.path,"items"]})},XT=(t,a,l,s)=>{var p;const o=l,d=t._zod.def;o.type="object",o.properties={};const h=d.shape;for(const x in h)o.properties[x]=Ct(h[x],a,{...s,path:[...s.path,"properties",x]});const m=new Set(Object.keys(h)),g=new Set([...m].filter(x=>{const b=d.shape[x]._zod;return a.io==="input"?b.optin===void 0:b.optout===void 0}));g.size>0&&(o.required=Array.from(g)),((p=d.catchall)==null?void 0:p._zod.def.type)==="never"?o.additionalProperties=!1:d.catchall?d.catchall&&(o.additionalProperties=Ct(d.catchall,a,{...s,path:[...s.path,"additionalProperties"]})):a.io==="output"&&(o.additionalProperties=!1)},JT=(t,a,l,s)=>{const o=t._zod.def,d=o.inclusive===!1,h=o.options.map((m,g)=>Ct(m,a,{...s,path:[...s.path,d?"oneOf":"anyOf",g]}));d?l.oneOf=h:l.anyOf=h},WT=(t,a,l,s)=>{const o=t._zod.def,d=Ct(o.left,a,{...s,path:[...s.path,"allOf",0]}),h=Ct(o.right,a,{...s,path:[...s.path,"allOf",1]}),m=p=>"allOf"in p&&Object.keys(p).length===1,g=[...m(d)?d.allOf:[d],...m(h)?h.allOf:[h]];l.allOf=g},ez=(t,a,l,s)=>{const o=l,d=t._zod.def;o.type="object";const h=d.keyType,m=h._zod.bag,g=m==null?void 0:m.patterns;if(d.mode==="loose"&&g&&g.size>0){const x=Ct(d.valueType,a,{...s,path:[...s.path,"patternProperties","*"]});o.patternProperties={};for(const b of g)o.patternProperties[b.source]=x}else(a.target==="draft-07"||a.target==="draft-2020-12")&&(o.propertyNames=Ct(d.keyType,a,{...s,path:[...s.path,"propertyNames"]})),o.additionalProperties=Ct(d.valueType,a,{...s,path:[...s.path,"additionalProperties"]});const p=h._zod.values;if(p){const x=[...p].filter(b=>typeof b=="string"||typeof b=="number");x.length>0&&(o.required=x)}},tz=(t,a,l,s)=>{const o=t._zod.def,d=Ct(o.innerType,a,s),h=a.seen.get(t);a.target==="openapi-3.0"?(h.ref=o.innerType,l.nullable=!0):l.anyOf=[d,{type:"null"}]},nz=(t,a,l,s)=>{const o=t._zod.def;Ct(o.innerType,a,s);const d=a.seen.get(t);d.ref=o.innerType},az=(t,a,l,s)=>{const o=t._zod.def;Ct(o.innerType,a,s);const d=a.seen.get(t);d.ref=o.innerType,l.default=JSON.parse(JSON.stringify(o.defaultValue))},rz=(t,a,l,s)=>{const o=t._zod.def;Ct(o.innerType,a,s);const d=a.seen.get(t);d.ref=o.innerType,a.io==="input"&&(l._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},lz=(t,a,l,s)=>{const o=t._zod.def;Ct(o.innerType,a,s);const d=a.seen.get(t);d.ref=o.innerType;let h;try{h=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}l.default=h},sz=(t,a,l,s)=>{const o=t._zod.def,d=a.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;Ct(d,a,s);const h=a.seen.get(t);h.ref=d},iz=(t,a,l,s)=>{const o=t._zod.def;Ct(o.innerType,a,s);const d=a.seen.get(t);d.ref=o.innerType,l.readOnly=!0},D0=(t,a,l,s)=>{const o=t._zod.def;Ct(o.innerType,a,s);const d=a.seen.get(t);d.ref=o.innerType},oz=I("ZodISODateTime",(t,a)=>{oA.init(t,a),mt.init(t,a)});function uz(t){return mT(oz,t)}const cz=I("ZodISODate",(t,a)=>{uA.init(t,a),mt.init(t,a)});function dz(t){return pT(cz,t)}const fz=I("ZodISOTime",(t,a)=>{cA.init(t,a),mt.init(t,a)});function hz(t){return gT(fz,t)}const mz=I("ZodISODuration",(t,a)=>{dA.init(t,a),mt.init(t,a)});function pz(t){return vT(mz,t)}const gz=(t,a)=>{p0.init(t,a),t.name="ZodError",Object.defineProperties(t,{format:{value:l=>tC(t,l)},flatten:{value:l=>eC(t,l)},addIssue:{value:l=>{t.issues.push(l),t.message=JSON.stringify(t.issues,bh,2)}},addIssues:{value:l=>{t.issues.push(...l),t.message=JSON.stringify(t.issues,bh,2)}},isEmpty:{get(){return t.issues.length===0}}})},Un=I("ZodError",gz,{Parent:Error}),vz=Fh(Un),yz=Xh(Un),bz=ec(Un),xz=tc(Un),Sz=rC(Un),jz=lC(Un),Nz=sC(Un),wz=iC(Un),_z=oC(Un),Ez=uC(Un),Cz=cC(Un),Az=dC(Un),ht=I("ZodType",(t,a)=>(ft.init(t,a),Object.assign(t["~standard"],{jsonSchema:{input:Vu(t,"input"),output:Vu(t,"output")}}),t.toJSONSchema=qT(t,{}),t.def=a,t.type=a.type,Object.defineProperty(t,"_def",{value:a}),t.check=(...l)=>t.clone(zr(a,{checks:[...a.checks??[],...l.map(s=>typeof s=="function"?{_zod:{check:s,def:{check:"custom"},onattach:[]}}:s)]}),{parent:!0}),t.with=t.check,t.clone=(l,s)=>Or(t,l,s),t.brand=()=>t,t.register=((l,s)=>(l.add(t,s),t)),t.parse=(l,s)=>vz(t,l,s,{callee:t.parse}),t.safeParse=(l,s)=>bz(t,l,s),t.parseAsync=async(l,s)=>yz(t,l,s,{callee:t.parseAsync}),t.safeParseAsync=async(l,s)=>xz(t,l,s),t.spa=t.safeParseAsync,t.encode=(l,s)=>Sz(t,l,s),t.decode=(l,s)=>jz(t,l,s),t.encodeAsync=async(l,s)=>Nz(t,l,s),t.decodeAsync=async(l,s)=>wz(t,l,s),t.safeEncode=(l,s)=>_z(t,l,s),t.safeDecode=(l,s)=>Ez(t,l,s),t.safeEncodeAsync=async(l,s)=>Cz(t,l,s),t.safeDecodeAsync=async(l,s)=>Az(t,l,s),t.refine=(l,s)=>t.check(NO(l,s)),t.superRefine=l=>t.check(wO(l)),t.overwrite=l=>t.check(Rs(l)),t.optional=()=>fb(t),t.exactOptional=()=>cO(t),t.nullable=()=>hb(t),t.nullish=()=>fb(hb(t)),t.nonoptional=l=>gO(t,l),t.array=()=>ea(t),t.or=l=>eO([t,l]),t.and=l=>rO(t,l),t.transform=l=>mb(t,oO(l)),t.default=l=>hO(t,l),t.prefault=l=>pO(t,l),t.catch=l=>yO(t,l),t.pipe=l=>mb(t,l),t.readonly=()=>SO(t),t.describe=l=>{const s=t.clone();return ki.add(s,{description:l}),s},Object.defineProperty(t,"description",{get(){var l;return(l=ki.get(t))==null?void 0:l.description},configurable:!0}),t.meta=(...l)=>{if(l.length===0)return ki.get(t);const s=t.clone();return ki.add(s,l[0]),s},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=l=>l(t),t)),U0=I("_ZodString",(t,a)=>{Jh.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(s,o,d)=>$T(t,s,o);const l=t._zod.bag;t.format=l.format??null,t.minLength=l.minimum??null,t.maxLength=l.maximum??null,t.regex=(...s)=>t.check(wT(...s)),t.includes=(...s)=>t.check(CT(...s)),t.startsWith=(...s)=>t.check(AT(...s)),t.endsWith=(...s)=>t.check(TT(...s)),t.min=(...s)=>t.check(Iu(...s)),t.max=(...s)=>t.check(z0(...s)),t.length=(...s)=>t.check(O0(...s)),t.nonempty=(...s)=>t.check(Iu(1,...s)),t.lowercase=s=>t.check(_T(s)),t.uppercase=s=>t.check(ET(s)),t.trim=()=>t.check(OT()),t.normalize=(...s)=>t.check(zT(...s)),t.toLowerCase=()=>t.check(RT()),t.toUpperCase=()=>t.check(MT()),t.slugify=()=>t.check(kT())}),Tz=I("ZodString",(t,a)=>{Jh.init(t,a),U0.init(t,a),t.email=l=>t.check(YA(zz,l)),t.url=l=>t.check(JA(Oz,l)),t.jwt=l=>t.check(hT(Vz,l)),t.emoji=l=>t.check(WA(Rz,l)),t.guid=l=>t.check(sb(cb,l)),t.uuid=l=>t.check(KA(Au,l)),t.uuidv4=l=>t.check(PA(Au,l)),t.uuidv6=l=>t.check(FA(Au,l)),t.uuidv7=l=>t.check(XA(Au,l)),t.nanoid=l=>t.check(eT(Mz,l)),t.guid=l=>t.check(sb(cb,l)),t.cuid=l=>t.check(tT(kz,l)),t.cuid2=l=>t.check(nT(Dz,l)),t.ulid=l=>t.check(aT(Uz,l)),t.base64=l=>t.check(cT(Qz,l)),t.base64url=l=>t.check(dT(Gz,l)),t.xid=l=>t.check(rT(Lz,l)),t.ksuid=l=>t.check(lT(Zz,l)),t.ipv4=l=>t.check(sT(qz,l)),t.ipv6=l=>t.check(iT(Bz,l)),t.cidrv4=l=>t.check(oT($z,l)),t.cidrv6=l=>t.check(uT(Hz,l)),t.e164=l=>t.check(fT(Iz,l)),t.datetime=l=>t.check(uz(l)),t.date=l=>t.check(dz(l)),t.time=l=>t.check(hz(l)),t.duration=l=>t.check(pz(l))});function E(t){return VA(Tz,t)}const mt=I("ZodStringFormat",(t,a)=>{dt.init(t,a),U0.init(t,a)}),zz=I("ZodEmail",(t,a)=>{WC.init(t,a),mt.init(t,a)}),cb=I("ZodGUID",(t,a)=>{XC.init(t,a),mt.init(t,a)}),Au=I("ZodUUID",(t,a)=>{JC.init(t,a),mt.init(t,a)}),Oz=I("ZodURL",(t,a)=>{eA.init(t,a),mt.init(t,a)}),Rz=I("ZodEmoji",(t,a)=>{tA.init(t,a),mt.init(t,a)}),Mz=I("ZodNanoID",(t,a)=>{nA.init(t,a),mt.init(t,a)}),kz=I("ZodCUID",(t,a)=>{aA.init(t,a),mt.init(t,a)}),Dz=I("ZodCUID2",(t,a)=>{rA.init(t,a),mt.init(t,a)}),Uz=I("ZodULID",(t,a)=>{lA.init(t,a),mt.init(t,a)}),Lz=I("ZodXID",(t,a)=>{sA.init(t,a),mt.init(t,a)}),Zz=I("ZodKSUID",(t,a)=>{iA.init(t,a),mt.init(t,a)}),qz=I("ZodIPv4",(t,a)=>{fA.init(t,a),mt.init(t,a)}),Bz=I("ZodIPv6",(t,a)=>{hA.init(t,a),mt.init(t,a)}),$z=I("ZodCIDRv4",(t,a)=>{mA.init(t,a),mt.init(t,a)}),Hz=I("ZodCIDRv6",(t,a)=>{pA.init(t,a),mt.init(t,a)}),Qz=I("ZodBase64",(t,a)=>{gA.init(t,a),mt.init(t,a)}),Gz=I("ZodBase64URL",(t,a)=>{yA.init(t,a),mt.init(t,a)}),Iz=I("ZodE164",(t,a)=>{bA.init(t,a),mt.init(t,a)}),Vz=I("ZodJWT",(t,a)=>{SA.init(t,a),mt.init(t,a)}),Wh=I("ZodNumber",(t,a)=>{_0.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(s,o,d)=>HT(t,s,o),t.gt=(s,o)=>t.check(ob(s,o)),t.gte=(s,o)=>t.check(qf(s,o)),t.min=(s,o)=>t.check(qf(s,o)),t.lt=(s,o)=>t.check(ib(s,o)),t.lte=(s,o)=>t.check(Zf(s,o)),t.max=(s,o)=>t.check(Zf(s,o)),t.int=s=>t.check(db(s)),t.safe=s=>t.check(db(s)),t.positive=s=>t.check(ob(0,s)),t.nonnegative=s=>t.check(qf(0,s)),t.negative=s=>t.check(ib(0,s)),t.nonpositive=s=>t.check(Zf(0,s)),t.multipleOf=(s,o)=>t.check(ub(s,o)),t.step=(s,o)=>t.check(ub(s,o)),t.finite=()=>t;const l=t._zod.bag;t.minValue=Math.max(l.minimum??Number.NEGATIVE_INFINITY,l.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(l.maximum??Number.POSITIVE_INFINITY,l.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(l.format??"").includes("int")||Number.isSafeInteger(l.multipleOf??.5),t.isFinite=!0,t.format=l.format??null});function Ve(t){return yT(Wh,t)}const Yz=I("ZodNumberFormat",(t,a)=>{jA.init(t,a),Wh.init(t,a)});function db(t){return xT(Yz,t)}const Kz=I("ZodBoolean",(t,a)=>{NA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>QT(t,l,s)});function ac(t){return ST(Kz,t)}const Pz=I("ZodUnknown",(t,a)=>{wA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>IT()});function it(){return jT(Pz)}const Fz=I("ZodNever",(t,a)=>{_A.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>GT(t,l,s)});function Xz(t){return NT(Fz,t)}const Jz=I("ZodArray",(t,a)=>{EA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>FT(t,l,s,o),t.element=a.element,t.min=(l,s)=>t.check(Iu(l,s)),t.nonempty=l=>t.check(Iu(1,l)),t.max=(l,s)=>t.check(z0(l,s)),t.length=(l,s)=>t.check(O0(l,s)),t.unwrap=()=>t.element});function ea(t,a){return DT(Jz,t,a)}const Wz=I("ZodObject",(t,a)=>{AA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>XT(t,l,s,o),Ye(t,"shape",()=>a.shape),t.keyof=()=>Xe(Object.keys(t._zod.def.shape)),t.catchall=l=>t.clone({...t._zod.def,catchall:l}),t.passthrough=()=>t.clone({...t._zod.def,catchall:it()}),t.loose=()=>t.clone({...t._zod.def,catchall:it()}),t.strict=()=>t.clone({...t._zod.def,catchall:Xz()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=l=>P2(t,l),t.safeExtend=l=>F2(t,l),t.merge=l=>X2(t,l),t.pick=l=>Y2(t,l),t.omit=l=>K2(t,l),t.partial=(...l)=>J2(Z0,t,l[0]),t.required=(...l)=>W2(q0,t,l[0])});function ne(t,a){const l={type:"object",shape:t??{},...he(a)};return new Wz(l)}const L0=I("ZodUnion",(t,a)=>{A0.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>JT(t,l,s,o),t.options=a.options});function eO(t,a){return new L0({type:"union",options:t,...he(a)})}const tO=I("ZodDiscriminatedUnion",(t,a)=>{L0.init(t,a),TA.init(t,a)});function nO(t,a,l){return new tO({type:"union",options:a,discriminator:t,...he(l)})}const aO=I("ZodIntersection",(t,a)=>{zA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>WT(t,l,s,o)});function rO(t,a){return new aO({type:"intersection",left:t,right:a})}const lO=I("ZodRecord",(t,a)=>{OA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>ez(t,l,s,o),t.keyType=a.keyType,t.valueType=a.valueType});function Ot(t,a,l){return new lO({type:"record",keyType:t,valueType:a,...he(l)})}const Sh=I("ZodEnum",(t,a)=>{RA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(s,o,d)=>VT(t,s,o),t.enum=a.entries,t.options=Object.values(a.entries);const l=new Set(Object.keys(a.entries));t.extract=(s,o)=>{const d={};for(const h of s)if(l.has(h))d[h]=a.entries[h];else throw new Error(`Key ${h} not found in enum`);return new Sh({...a,checks:[],...he(o),entries:d})},t.exclude=(s,o)=>{const d={...a.entries};for(const h of s)if(l.has(h))delete d[h];else throw new Error(`Key ${h} not found in enum`);return new Sh({...a,checks:[],...he(o),entries:d})}});function Xe(t,a){const l=Array.isArray(t)?Object.fromEntries(t.map(s=>[s,s])):t;return new Sh({type:"enum",entries:l,...he(a)})}const sO=I("ZodLiteral",(t,a)=>{MA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>YT(t,l,s),t.values=new Set(a.values),Object.defineProperty(t,"value",{get(){if(a.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return a.values[0]}})});function rc(t,a){return new sO({type:"literal",values:Array.isArray(t)?t:[t],...he(a)})}const iO=I("ZodTransform",(t,a)=>{kA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>PT(t,l),t._zod.parse=(l,s)=>{if(s.direction==="backward")throw new u0(t.constructor.name);l.addIssue=d=>{if(typeof d=="string")l.issues.push($i(d,l.value,a));else{const h=d;h.fatal&&(h.continue=!1),h.code??(h.code="custom"),h.input??(h.input=l.value),h.inst??(h.inst=t),l.issues.push($i(h))}};const o=a.transform(l.value,l);return o instanceof Promise?o.then(d=>(l.value=d,l)):(l.value=o,l)}});function oO(t){return new iO({type:"transform",transform:t})}const Z0=I("ZodOptional",(t,a)=>{T0.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>D0(t,l,s,o),t.unwrap=()=>t._zod.def.innerType});function fb(t){return new Z0({type:"optional",innerType:t})}const uO=I("ZodExactOptional",(t,a)=>{DA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>D0(t,l,s,o),t.unwrap=()=>t._zod.def.innerType});function cO(t){return new uO({type:"optional",innerType:t})}const dO=I("ZodNullable",(t,a)=>{UA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>tz(t,l,s,o),t.unwrap=()=>t._zod.def.innerType});function hb(t){return new dO({type:"nullable",innerType:t})}const fO=I("ZodDefault",(t,a)=>{LA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>az(t,l,s,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function hO(t,a){return new fO({type:"default",innerType:t,get defaultValue(){return typeof a=="function"?a():h0(a)}})}const mO=I("ZodPrefault",(t,a)=>{ZA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>rz(t,l,s,o),t.unwrap=()=>t._zod.def.innerType});function pO(t,a){return new mO({type:"prefault",innerType:t,get defaultValue(){return typeof a=="function"?a():h0(a)}})}const q0=I("ZodNonOptional",(t,a)=>{qA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>nz(t,l,s,o),t.unwrap=()=>t._zod.def.innerType});function gO(t,a){return new q0({type:"nonoptional",innerType:t,...he(a)})}const vO=I("ZodCatch",(t,a)=>{BA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>lz(t,l,s,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function yO(t,a){return new vO({type:"catch",innerType:t,catchValue:typeof a=="function"?a:()=>a})}const bO=I("ZodPipe",(t,a)=>{$A.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>sz(t,l,s,o),t.in=a.in,t.out=a.out});function mb(t,a){return new bO({type:"pipe",in:t,out:a})}const xO=I("ZodReadonly",(t,a)=>{HA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>iz(t,l,s,o),t.unwrap=()=>t._zod.def.innerType});function SO(t){return new xO({type:"readonly",innerType:t})}const jO=I("ZodCustom",(t,a)=>{QA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>KT(t,l)});function NO(t,a={}){return UT(jO,t,a)}function wO(t){return LT(t)}const Bf={custom:"custom"};function lc(t){return bT(Wh,t)}const _O={FEISHU:"feishu",SLACK:"slack",KAEL:"kael"},B0=Xe(["feishu","slack","kael"]),$0=Xe(["active","inactive"]);ne({platform:B0,agentId:E().min(1),credentials:Ot(E(),it()),status:$0.default("active")});ne({agentId:E().min(1).optional(),credentials:Ot(E(),it()).optional(),status:$0.optional()});ne({id:Ve(),platform:E(),agentId:E(),hasCredentials:ac(),status:E(),createdAt:E(),updatedAt:E()});const EO=Xe(["code","reverse_token","oauth","manual"]);ne({appId:E().min(1),appSecret:E().min(1)});ne({platform:B0,externalUserId:E().min(1),agentId:E().min(1),boundVia:EO.default("manual"),displayName:E().max(200).optional()});ne({id:Ve(),platform:E(),externalUserId:E(),agentId:E(),boundVia:E().nullable(),displayName:E().nullable(),createdAt:E()});ne({feishuUserId:E().min(1),displayName:E().max(200).optional()});ne({configId:Ve(),platform:E(),agentId:E(),appId:E(),connected:ac(),lastActiveAt:E().nullable()});const H0=Xe(["online","offline"]),Q0=Xe(["idle","working","blocked","error"]),CO=Xe(["active","suspended","evicted"]);ne({chatId:E().min(1),state:CO});ne({runtimeState:Q0});ne({agentId:E().min(1),runtimeType:E().max(50),runtimeVersion:E().max(50).optional()});Xe(["wrong_client","not_owned","agent_suspended","wrong_org","unknown_agent"]);ne({agentId:E(),status:H0,connectedAt:E().nullable(),lastSeenAt:E(),clientId:E().nullable().optional(),runtimeType:E().nullable().optional(),runtimeVersion:E().nullable().optional(),runtimeState:Q0.nullable().optional(),activeSessions:Ve().int().nullable().optional(),totalSessions:Ve().int().nullable().optional(),runtimeUpdatedAt:E().nullable().optional()});ne({total:Ve().int(),running:Ve().int(),byState:ne({idle:Ve().int(),working:Ve().int(),blocked:Ve().int(),error:Ve().int()}),clients:Ve().int()});const G0={HUMAN:"human",PERSONAL_ASSISTANT:"personal_assistant",AUTONOMOUS_AGENT:"autonomous_agent"},em=Xe(["human","personal_assistant","autonomous_agent"]),tm=Xe(["private","organization"]),AO=Xe(["admin-api","portal"]);Xe(["active","suspended"]);ne({name:E().min(1).max(100).regex(/^[a-z0-9_-]+$/,"Only lowercase alphanumeric, hyphens, and underscores").optional(),type:em,displayName:E().max(200).optional(),delegateMention:E().max(100).optional(),organizationId:E().max(100).optional(),source:AO.optional(),visibility:tm.optional(),metadata:Ot(E(),it()).optional(),managerId:E().optional(),clientId:E().min(1).max(100).optional()});ne({type:em.optional(),displayName:E().max(200).nullable().optional(),delegateMention:E().max(100).nullable().optional(),visibility:tm.optional(),metadata:Ot(E(),it()).optional(),managerId:E().nullable().optional(),clientId:E().optional()});ne({uuid:E(),name:E().nullable(),organizationId:E(),type:em,displayName:E().nullable(),delegateMention:E().nullable(),inboxId:E(),status:E(),source:E().nullable().optional(),cloudUserId:E().nullable().optional(),visibility:tm,metadata:Ot(E(),it()),managerId:E().nullable(),clientId:E().nullable(),presenceStatus:H0.optional(),createdAt:E(),updatedAt:E()});ne({repo:E().nullable(),branch:E().nullable()});const TO=32e3,nm=/^[a-z0-9][a-z0-9_-]{0,63}$/i,zO=/^[A-Z][A-Z0-9_]*$/,OO=ne({append:E().max(TO).default("")}),RO=ne({name:E().regex(nm,"MCP name must match /^[a-z0-9][a-z0-9_-]{0,63}$/i"),transport:rc("stdio"),command:E().min(1),args:ea(E()).optional()}),MO=ne({name:E().regex(nm,"MCP name must match /^[a-z0-9][a-z0-9_-]{0,63}$/i"),transport:rc("http"),url:E().url(),headers:Ot(E(),E()).optional()}),kO=ne({name:E().regex(nm,"MCP name must match /^[a-z0-9][a-z0-9_-]{0,63}$/i"),transport:rc("sse"),url:E().url(),headers:Ot(E(),E()).optional()}),DO=nO("transport",[RO,MO,kO]),UO=ne({key:E().regex(zO,"Env key must match /^[A-Z][A-Z0-9_]*$/"),value:E(),sensitive:ac().default(!1)}),LO=ne({url:E().min(1),ref:E().min(1).optional(),localPath:E().min(1).optional()}),am=ne({prompt:OO.default({append:""}),model:E().default(""),mcpServers:ea(DO).default([]),env:ea(UO).default([]),gitRepos:ea(LO).default([])}),ZO=(t,a)=>{const l=new Set;t.mcpServers.forEach((d,h)=>{const m=d.name.toLowerCase();l.has(m)&&a.addIssue({code:Bf.custom,path:["mcpServers",h,"name"],message:`Duplicate MCP server name "${d.name}"`}),l.add(m)});const s=new Set;t.env.forEach((d,h)=>{s.has(d.key)&&a.addIssue({code:Bf.custom,path:["env",h,"key"],message:`Duplicate env key "${d.key}"`}),s.add(d.key)});const o=new Set;t.gitRepos.forEach((d,h)=>{const m=d.localPath??Yu(d.url);m&&(o.has(m)&&a.addIssue({code:Bf.custom,path:["gitRepos",h,"localPath"],message:`Duplicate git repo local path "${m}"`}),o.add(m))})},I0=am.superRefine(ZO),qO=ne({agentId:E(),version:Ve().int().positive(),payload:I0,updatedAt:E(),updatedBy:E()});ne({expectedVersion:Ve().int().positive(),payload:am.partial()});ne({payload:am.partial()});ne({current:qO,next:I0,diff:ea(ne({path:E(),op:Xe(["add","remove","replace"]),before:it().optional(),after:it().optional()}))});const jh="***";function Yu(t){const a=t.trim();return a?((a.split(/[?#]/)[0]??"").split(/[/:]/).filter(Boolean).pop()??"").replace(/\.git$/i,""):""}ne({username:E().min(1),password:E().min(1)});ne({accessToken:E(),refreshToken:E()});ne({refreshToken:E().min(1)});ne({token:E().min(1)});ne({token:E(),expiresIn:Ve(),command:E()});const BO=Xe(["direct","group","thread"]);ne({type:BO,topic:E().max(500).optional(),participantIds:ea(E()).min(1),metadata:Ot(E(),it()).optional()});const $O=ne({agentId:E(),role:E(),mode:E(),joinedAt:E()}),HO=ne({id:E(),organizationId:E(),type:E(),topic:E().nullable(),lifecyclePolicy:E().nullable().optional(),metadata:Ot(E(),it()),createdAt:E(),updatedAt:E()});HO.extend({participants:ea($O)});ne({agentId:E().min(1),mode:Xe(["full","mention_only"]).default("full")});ne({agentId:E().min(1)});const QO=Xe(["connected","disconnected"]);ne({id:E(),userId:E().nullable(),status:QO,sdkVersion:E().max(50).nullable(),hostname:E().max(100).nullable(),os:E().max(50).nullable(),agentCount:Ve().int().min(0),connectedAt:E().nullable(),lastSeenAt:E(),metadata:Ot(E(),it()).nullable()});ne({clientId:E().min(1).max(100),hostname:E().max(100).optional(),os:E().max(50).optional(),sdkVersion:E().max(50).optional()});ne({limit:lc().int().min(1).max(100).default(20),cursor:E().optional()});const rm=Xe(["hub_ui","cli","feishu","github","api"]),V0=Xe(["text","markdown","card","reference","file","task"]);ne({format:V0.default("text"),content:it(),metadata:Ot(E(),it()).optional(),inReplyTo:E().optional(),replyToInbox:E().optional(),replyToChat:E().optional(),source:rm.optional()});ne({format:V0.default("text"),content:it(),metadata:Ot(E(),it()).optional(),replyToInbox:E().optional(),replyToChat:E().optional(),source:rm.optional()});const GO=ne({id:E(),chatId:E(),senderId:E(),format:E(),content:it(),metadata:Ot(E(),it()),replyToInbox:E().nullable(),replyToChat:E().nullable(),inReplyTo:E().nullable(),source:rm.nullable(),createdAt:E()}),IO=GO.extend({configVersion:Ve().int().positive()});Xe(["pending","delivered","acked","failed"]);const VO=ne({id:Ve(),inboxId:E(),messageId:E(),chatId:E().nullable(),status:E(),retryCount:Ve(),createdAt:E(),deliveredAt:E().nullable(),ackedAt:E().nullable()});VO.extend({message:IO});ne({limit:lc().int().min(1).max(50).default(10)});const YO={ADMIN:"admin",MEMBER:"member"},lm=Xe(["admin","member"]),KO=ne({id:E(),userId:E(),organizationId:E(),agentId:E(),role:lm,createdAt:E()});ne({username:E().min(1).max(100),displayName:E().min(1).max(200),role:lm.default("member")});ne({role:lm.optional()});KO.extend({username:E(),displayName:E(),password:E()});const PO=Xe(["agent_error","session_error","agent_needs_decision","agent_blocked","agent_stale","agent_disconnected","agent_connected","session_completed"]),Y0=Xe(["high","medium","low"]);ne({id:E(),organizationId:E(),type:PO,severity:Y0,agentId:E().nullable(),chatId:E().nullable(),message:E(),read:ac(),createdAt:E()});ne({limit:lc().int().min(1).max(100).default(20),cursor:E().optional(),severity:Y0.optional(),read:Xe(["true","false"]).transform(t=>t==="true").optional(),agentId:E().optional()});const K0=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;ne({name:E().min(2).max(50).regex(/^[a-z0-9][a-z0-9-]*$/,"Must start with a letter or digit and contain only lowercase alphanumeric and hyphens").refine(t=>!K0.test(t),"Name must not be a UUID format"),displayName:E().min(1).max(200),maxAgents:Ve().int().min(0).default(0),maxMessagesPerMinute:Ve().int().min(0).default(0),features:Ot(E(),it()).default({})});ne({name:E().min(2).max(50).regex(/^[a-z0-9][a-z0-9-]*$/,"Must start with a letter or digit and contain only lowercase alphanumeric and hyphens").refine(t=>!K0.test(t),"Name must not be a UUID format").optional(),displayName:E().min(1).max(200).optional(),maxAgents:Ve().int().min(0).optional(),maxMessagesPerMinute:Ve().int().min(0).optional(),features:Ot(E(),it()).optional()});ne({id:E(),name:E(),displayName:E(),maxAgents:Ve(),maxMessagesPerMinute:Ve(),features:Ot(E(),it()),createdAt:E(),updatedAt:E()});ne({id:E(),agentId:E(),chatId:E(),content:E(),updatedAt:E()});ne({agentId:E(),chatId:E(),content:E().max(5e4)});const FO=ne({organizationId:E(),agentCount:Ve(),chatCount:Ve(),messageCount:Ve()});ne({totalAgents:Ve(),totalChats:Ve(),totalMessages:Ve(),byOrganization:ea(FO)});ne({key:E(),value:it(),updatedAt:E()});Ot(E(),it());const Aa={INBOX_TIMEOUT_SECONDS:"inbox_timeout_seconds",MAX_RETRY_COUNT:"max_retry_count",POLLING_INTERVAL_SECONDS:"polling_interval_seconds",PRESENCE_CLEANUP_SECONDS:"presence_cleanup_seconds"},$f={[Aa.INBOX_TIMEOUT_SECONDS]:300,[Aa.MAX_RETRY_COUNT]:3,[Aa.POLLING_INTERVAL_SECONDS]:5,[Aa.PRESENCE_CLEANUP_SECONDS]:60},Hi=Xe(["pending","assigned","working","completed","failed","cancelled"]),pb=Xe(["agent","admin"]),XO=Xe(["assigned","status_changed","cancelled"]);ne({taskId:E(),event:XO,title:E(),body:E().default(""),status:Hi,fromStatus:Hi.optional(),originRef:E().nullable().optional()});const JO=ne({title:E().min(1).max(500),body:E().optional(),assigneeAgentId:E().optional(),originRef:E().max(500).optional(),metadata:Ot(E(),it()).optional()});JO.extend({organizationId:E().optional()});ne({status:Xe(["working","completed","failed"]),result:E().optional()});ne({assigneeAgentId:E().nullable().optional(),status:Hi.optional(),result:E().optional()});ne({chatId:E().min(1)});const WO=ne({id:E(),organizationId:E(),title:E(),body:E(),status:Hi,assigneeAgentId:E().nullable(),createdByType:pb,createdById:E(),originRef:E().nullable(),result:E().nullable(),metadata:Ot(E(),it()),createdAt:E(),updatedAt:E(),cancelledAt:E().nullable(),cancelledByType:pb.nullable(),cancelledById:E().nullable()}),eR=ne({taskId:E(),chatId:E(),linkedByAgentId:E().nullable(),linkedAt:E()});WO.extend({chats:ea(eR)});ne({status:Hi.optional(),assigneeAgentId:E().optional(),originRef:E().optional(),limit:lc().int().min(1).max(100).default(20),cursor:E().optional()});const tR=Xe(["normal","idle_island","awaiting_reply","no_chat","not_applicable"]);ne({taskId:E(),signal:tR,reason:E()});const nR=Xe(["active","suspended"]);ne({id:E(),username:E(),displayName:E(),avatarUrl:E().nullable(),status:nR,createdAt:E(),updatedAt:E()});ne({username:E().min(1).max(100),displayName:E().min(1).max(200),password:E().min(8).max(200)});ne({displayName:E().min(1).max(200).optional(),password:E().min(8).max(200).optional()});ne({type:rc("auth"),token:E().min(1)});function sm(){return we.get("/members")}function aR(t){return we.post("/members",t)}function rR(t){return we.delete(`/members/${encodeURIComponent(t)}`)}function _r(t,a,{checkForDefaultPrevented:l=!0}={}){return function(o){if(t==null||t(o),l===!1||!o.defaultPrevented)return a==null?void 0:a(o)}}function lR(t,a){const l=y.createContext(a),s=d=>{const{children:h,...m}=d,g=y.useMemo(()=>m,Object.values(m));return u.jsx(l.Provider,{value:g,children:h})};s.displayName=t+"Provider";function o(d){const h=y.useContext(l);if(h)return h;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${t}\``)}return[s,o]}function sR(t,a=[]){let l=[];function s(d,h){const m=y.createContext(h),g=l.length;l=[...l,h];const p=b=>{var R;const{scope:j,children:w,...C}=b,N=((R=j==null?void 0:j[t])==null?void 0:R[g])||m,_=y.useMemo(()=>C,Object.values(C));return u.jsx(N.Provider,{value:_,children:w})};p.displayName=d+"Provider";function x(b,j){var N;const w=((N=j==null?void 0:j[t])==null?void 0:N[g])||m,C=y.useContext(w);if(C)return C;if(h!==void 0)return h;throw new Error(`\`${b}\` must be used within \`${d}\``)}return[p,x]}const o=()=>{const d=l.map(h=>y.createContext(h));return function(m){const g=(m==null?void 0:m[t])||d;return y.useMemo(()=>({[`__scope${t}`]:{...m,[t]:g}}),[m,g])}};return o.scopeName=t,[s,iR(o,...a)]}function iR(...t){const a=t[0];if(t.length===1)return a;const l=()=>{const s=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(d){const h=s.reduce((m,{useScope:g,scopeName:p})=>{const b=g(d)[`__scope${p}`];return{...m,...b}},{});return y.useMemo(()=>({[`__scope${a.scopeName}`]:h}),[h])}};return l.scopeName=a.scopeName,l}var Qi=globalThis!=null&&globalThis.document?y.useLayoutEffect:()=>{},oR=Ch[" useId ".trim().toString()]||(()=>{}),uR=0;function Hf(t){const[a,l]=y.useState(oR());return Qi(()=>{l(s=>s??String(uR++))},[t]),t||(a?`radix-${a}`:"")}var cR=Ch[" useInsertionEffect ".trim().toString()]||Qi;function dR({prop:t,defaultProp:a,onChange:l=()=>{},caller:s}){const[o,d,h]=fR({defaultProp:a,onChange:l}),m=t!==void 0,g=m?t:o;{const x=y.useRef(t!==void 0);y.useEffect(()=>{const b=x.current;b!==m&&console.warn(`${s} is changing from ${b?"controlled":"uncontrolled"} to ${m?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),x.current=m},[m,s])}const p=y.useCallback(x=>{var b;if(m){const j=hR(x)?x(t):x;j!==t&&((b=h.current)==null||b.call(h,j))}else d(x)},[m,t,d,h]);return[g,p]}function fR({defaultProp:t,onChange:a}){const[l,s]=y.useState(t),o=y.useRef(l),d=y.useRef(a);return cR(()=>{d.current=a},[a]),y.useEffect(()=>{var h;o.current!==l&&((h=d.current)==null||h.call(d,l),o.current=l)},[l,o]),[l,s,d]}function hR(t){return typeof t=="function"}var P0=Yb();const mR=Vb(P0);function F0(t){const a=pR(t),l=y.forwardRef((s,o)=>{const{children:d,...h}=s,m=y.Children.toArray(d),g=m.find(vR);if(g){const p=g.props.children,x=m.map(b=>b===g?y.Children.count(p)>1?y.Children.only(null):y.isValidElement(p)?p.props.children:null:b);return u.jsx(a,{...h,ref:o,children:y.isValidElement(p)?y.cloneElement(p,void 0,x):null})}return u.jsx(a,{...h,ref:o,children:d})});return l.displayName=`${t}.Slot`,l}function pR(t){const a=y.forwardRef((l,s)=>{const{children:o,...d}=l;if(y.isValidElement(o)){const h=bR(o),m=yR(d,o.props);return o.type!==y.Fragment&&(m.ref=s?Vh(s,h):h),y.cloneElement(o,m)}return y.Children.count(o)>1?y.Children.only(null):null});return a.displayName=`${t}.SlotClone`,a}var gR=Symbol("radix.slottable");function vR(t){return y.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===gR}function yR(t,a){const l={...a};for(const s in a){const o=t[s],d=a[s];/^on[A-Z]/.test(s)?o&&d?l[s]=(...m)=>{const g=d(...m);return o(...m),g}:o&&(l[s]=o):s==="style"?l[s]={...o,...d}:s==="className"&&(l[s]=[o,d].filter(Boolean).join(" "))}return{...t,...l}}function bR(t){var s,o;let a=(s=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:s.get,l=a&&"isReactWarning"in a&&a.isReactWarning;return l?t.ref:(a=(o=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:o.get,l=a&&"isReactWarning"in a&&a.isReactWarning,l?t.props.ref:t.props.ref||t.ref)}var xR=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ka=xR.reduce((t,a)=>{const l=F0(`Primitive.${a}`),s=y.forwardRef((o,d)=>{const{asChild:h,...m}=o,g=h?l:a;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(g,{...m,ref:d})});return s.displayName=`Primitive.${a}`,{...t,[a]:s}},{});function SR(t,a){t&&P0.flushSync(()=>t.dispatchEvent(a))}function Gi(t){const a=y.useRef(t);return y.useEffect(()=>{a.current=t}),y.useMemo(()=>(...l)=>{var s;return(s=a.current)==null?void 0:s.call(a,...l)},[])}function jR(t,a=globalThis==null?void 0:globalThis.document){const l=Gi(t);y.useEffect(()=>{const s=o=>{o.key==="Escape"&&l(o)};return a.addEventListener("keydown",s,{capture:!0}),()=>a.removeEventListener("keydown",s,{capture:!0})},[l,a])}var NR="DismissableLayer",Nh="dismissableLayer.update",wR="dismissableLayer.pointerDownOutside",_R="dismissableLayer.focusOutside",gb,X0=y.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),J0=y.forwardRef((t,a)=>{const{disableOutsidePointerEvents:l=!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:d,onInteractOutside:h,onDismiss:m,...g}=t,p=y.useContext(X0),[x,b]=y.useState(null),j=(x==null?void 0:x.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,w]=y.useState({}),C=pl(a,K=>b(K)),N=Array.from(p.layers),[_]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),R=N.indexOf(_),Q=x?N.indexOf(x):-1,q=p.layersWithOutsidePointerEventsDisabled.size>0,B=Q>=R,F=AR(K=>{const k=K.target,ee=[...p.branches].some(be=>be.contains(k));!B||ee||(o==null||o(K),h==null||h(K),K.defaultPrevented||m==null||m())},j),J=TR(K=>{const k=K.target;[...p.branches].some(be=>be.contains(k))||(d==null||d(K),h==null||h(K),K.defaultPrevented||m==null||m())},j);return jR(K=>{Q===p.layers.size-1&&(s==null||s(K),!K.defaultPrevented&&m&&(K.preventDefault(),m()))},j),y.useEffect(()=>{if(x)return l&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(gb=j.body.style.pointerEvents,j.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(x)),p.layers.add(x),vb(),()=>{l&&p.layersWithOutsidePointerEventsDisabled.size===1&&(j.body.style.pointerEvents=gb)}},[x,j,l,p]),y.useEffect(()=>()=>{x&&(p.layers.delete(x),p.layersWithOutsidePointerEventsDisabled.delete(x),vb())},[x,p]),y.useEffect(()=>{const K=()=>w({});return document.addEventListener(Nh,K),()=>document.removeEventListener(Nh,K)},[]),u.jsx(ka.div,{...g,ref:C,style:{pointerEvents:q?B?"auto":"none":void 0,...t.style},onFocusCapture:_r(t.onFocusCapture,J.onFocusCapture),onBlurCapture:_r(t.onBlurCapture,J.onBlurCapture),onPointerDownCapture:_r(t.onPointerDownCapture,F.onPointerDownCapture)})});J0.displayName=NR;var ER="DismissableLayerBranch",CR=y.forwardRef((t,a)=>{const l=y.useContext(X0),s=y.useRef(null),o=pl(a,s);return y.useEffect(()=>{const d=s.current;if(d)return l.branches.add(d),()=>{l.branches.delete(d)}},[l.branches]),u.jsx(ka.div,{...t,ref:o})});CR.displayName=ER;function AR(t,a=globalThis==null?void 0:globalThis.document){const l=Gi(t),s=y.useRef(!1),o=y.useRef(()=>{});return y.useEffect(()=>{const d=m=>{if(m.target&&!s.current){let g=function(){W0(wR,l,p,{discrete:!0})};const p={originalEvent:m};m.pointerType==="touch"?(a.removeEventListener("click",o.current),o.current=g,a.addEventListener("click",o.current,{once:!0})):g()}else a.removeEventListener("click",o.current);s.current=!1},h=window.setTimeout(()=>{a.addEventListener("pointerdown",d)},0);return()=>{window.clearTimeout(h),a.removeEventListener("pointerdown",d),a.removeEventListener("click",o.current)}},[a,l]),{onPointerDownCapture:()=>s.current=!0}}function TR(t,a=globalThis==null?void 0:globalThis.document){const l=Gi(t),s=y.useRef(!1);return y.useEffect(()=>{const o=d=>{d.target&&!s.current&&W0(_R,l,{originalEvent:d},{discrete:!1})};return a.addEventListener("focusin",o),()=>a.removeEventListener("focusin",o)},[a,l]),{onFocusCapture:()=>s.current=!0,onBlurCapture:()=>s.current=!1}}function vb(){const t=new CustomEvent(Nh);document.dispatchEvent(t)}function W0(t,a,l,{discrete:s}){const o=l.originalEvent.target,d=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:l});a&&o.addEventListener(t,a,{once:!0}),s?SR(o,d):o.dispatchEvent(d)}var Qf="focusScope.autoFocusOnMount",Gf="focusScope.autoFocusOnUnmount",yb={bubbles:!1,cancelable:!0},zR="FocusScope",eS=y.forwardRef((t,a)=>{const{loop:l=!1,trapped:s=!1,onMountAutoFocus:o,onUnmountAutoFocus:d,...h}=t,[m,g]=y.useState(null),p=Gi(o),x=Gi(d),b=y.useRef(null),j=pl(a,N=>g(N)),w=y.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;y.useEffect(()=>{if(s){let N=function(q){if(w.paused||!m)return;const B=q.target;m.contains(B)?b.current=B:mr(b.current,{select:!0})},_=function(q){if(w.paused||!m)return;const B=q.relatedTarget;B!==null&&(m.contains(B)||mr(b.current,{select:!0}))},R=function(q){if(document.activeElement===document.body)for(const F of q)F.removedNodes.length>0&&mr(m)};document.addEventListener("focusin",N),document.addEventListener("focusout",_);const Q=new MutationObserver(R);return m&&Q.observe(m,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",N),document.removeEventListener("focusout",_),Q.disconnect()}}},[s,m,w.paused]),y.useEffect(()=>{if(m){xb.add(w);const N=document.activeElement;if(!m.contains(N)){const R=new CustomEvent(Qf,yb);m.addEventListener(Qf,p),m.dispatchEvent(R),R.defaultPrevented||(OR(UR(tS(m)),{select:!0}),document.activeElement===N&&mr(m))}return()=>{m.removeEventListener(Qf,p),setTimeout(()=>{const R=new CustomEvent(Gf,yb);m.addEventListener(Gf,x),m.dispatchEvent(R),R.defaultPrevented||mr(N??document.body,{select:!0}),m.removeEventListener(Gf,x),xb.remove(w)},0)}}},[m,p,x,w]);const C=y.useCallback(N=>{if(!l&&!s||w.paused)return;const _=N.key==="Tab"&&!N.altKey&&!N.ctrlKey&&!N.metaKey,R=document.activeElement;if(_&&R){const Q=N.currentTarget,[q,B]=RR(Q);q&&B?!N.shiftKey&&R===B?(N.preventDefault(),l&&mr(q,{select:!0})):N.shiftKey&&R===q&&(N.preventDefault(),l&&mr(B,{select:!0})):R===Q&&N.preventDefault()}},[l,s,w.paused]);return u.jsx(ka.div,{tabIndex:-1,...h,ref:j,onKeyDown:C})});eS.displayName=zR;function OR(t,{select:a=!1}={}){const l=document.activeElement;for(const s of t)if(mr(s,{select:a}),document.activeElement!==l)return}function RR(t){const a=tS(t),l=bb(a,t),s=bb(a.reverse(),t);return[l,s]}function tS(t){const a=[],l=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:s=>{const o=s.tagName==="INPUT"&&s.type==="hidden";return s.disabled||s.hidden||o?NodeFilter.FILTER_SKIP:s.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;l.nextNode();)a.push(l.currentNode);return a}function bb(t,a){for(const l of t)if(!MR(l,{upTo:a}))return l}function MR(t,{upTo:a}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(a!==void 0&&t===a)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function kR(t){return t instanceof HTMLInputElement&&"select"in t}function mr(t,{select:a=!1}={}){if(t&&t.focus){const l=document.activeElement;t.focus({preventScroll:!0}),t!==l&&kR(t)&&a&&t.select()}}var xb=DR();function DR(){let t=[];return{add(a){const l=t[0];a!==l&&(l==null||l.pause()),t=Sb(t,a),t.unshift(a)},remove(a){var l;t=Sb(t,a),(l=t[0])==null||l.resume()}}}function Sb(t,a){const l=[...t],s=l.indexOf(a);return s!==-1&&l.splice(s,1),l}function UR(t){return t.filter(a=>a.tagName!=="A")}var LR="Portal",nS=y.forwardRef((t,a)=>{var m;const{container:l,...s}=t,[o,d]=y.useState(!1);Qi(()=>d(!0),[]);const h=l||o&&((m=globalThis==null?void 0:globalThis.document)==null?void 0:m.body);return h?mR.createPortal(u.jsx(ka.div,{...s,ref:a}),h):null});nS.displayName=LR;function ZR(t,a){return y.useReducer((l,s)=>a[l][s]??l,t)}var sc=t=>{const{present:a,children:l}=t,s=qR(a),o=typeof l=="function"?l({present:s.isPresent}):y.Children.only(l),d=pl(s.ref,BR(o));return typeof l=="function"||s.isPresent?y.cloneElement(o,{ref:d}):null};sc.displayName="Presence";function qR(t){const[a,l]=y.useState(),s=y.useRef(null),o=y.useRef(t),d=y.useRef("none"),h=t?"mounted":"unmounted",[m,g]=ZR(h,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return y.useEffect(()=>{const p=Tu(s.current);d.current=m==="mounted"?p:"none"},[m]),Qi(()=>{const p=s.current,x=o.current;if(x!==t){const j=d.current,w=Tu(p);t?g("MOUNT"):w==="none"||(p==null?void 0:p.display)==="none"?g("UNMOUNT"):g(x&&j!==w?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,g]),Qi(()=>{if(a){let p;const x=a.ownerDocument.defaultView??window,b=w=>{const N=Tu(s.current).includes(CSS.escape(w.animationName));if(w.target===a&&N&&(g("ANIMATION_END"),!o.current)){const _=a.style.animationFillMode;a.style.animationFillMode="forwards",p=x.setTimeout(()=>{a.style.animationFillMode==="forwards"&&(a.style.animationFillMode=_)})}},j=w=>{w.target===a&&(d.current=Tu(s.current))};return a.addEventListener("animationstart",j),a.addEventListener("animationcancel",b),a.addEventListener("animationend",b),()=>{x.clearTimeout(p),a.removeEventListener("animationstart",j),a.removeEventListener("animationcancel",b),a.removeEventListener("animationend",b)}}else g("ANIMATION_END")},[a,g]),{isPresent:["mounted","unmountSuspended"].includes(m),ref:y.useCallback(p=>{s.current=p?getComputedStyle(p):null,l(p)},[])}}function Tu(t){return(t==null?void 0:t.animationName)||"none"}function BR(t){var s,o;let a=(s=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:s.get,l=a&&"isReactWarning"in a&&a.isReactWarning;return l?t.ref:(a=(o=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:o.get,l=a&&"isReactWarning"in a&&a.isReactWarning,l?t.props.ref:t.props.ref||t.ref)}var If=0;function $R(){y.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??jb()),document.body.insertAdjacentElement("beforeend",t[1]??jb()),If++,()=>{If===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(a=>a.remove()),If--}},[])}function jb(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var Jn=function(){return Jn=Object.assign||function(a){for(var l,s=1,o=arguments.length;s<o;s++){l=arguments[s];for(var d in l)Object.prototype.hasOwnProperty.call(l,d)&&(a[d]=l[d])}return a},Jn.apply(this,arguments)};function aS(t,a){var l={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&a.indexOf(s)<0&&(l[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,s=Object.getOwnPropertySymbols(t);o<s.length;o++)a.indexOf(s[o])<0&&Object.prototype.propertyIsEnumerable.call(t,s[o])&&(l[s[o]]=t[s[o]]);return l}function HR(t,a,l){if(l||arguments.length===2)for(var s=0,o=a.length,d;s<o;s++)(d||!(s in a))&&(d||(d=Array.prototype.slice.call(a,0,s)),d[s]=a[s]);return t.concat(d||Array.prototype.slice.call(a))}var Lu="right-scroll-bar-position",Zu="width-before-scroll-bar",QR="with-scroll-bars-hidden",GR="--removed-body-scroll-bar-size";function Vf(t,a){return typeof t=="function"?t(a):t&&(t.current=a),t}function IR(t,a){var l=y.useState(function(){return{value:t,callback:a,facade:{get current(){return l.value},set current(s){var o=l.value;o!==s&&(l.value=s,l.callback(s,o))}}}})[0];return l.callback=a,l.facade}var VR=typeof window<"u"?y.useLayoutEffect:y.useEffect,Nb=new WeakMap;function YR(t,a){var l=IR(null,function(s){return t.forEach(function(o){return Vf(o,s)})});return VR(function(){var s=Nb.get(l);if(s){var o=new Set(s),d=new Set(t),h=l.current;o.forEach(function(m){d.has(m)||Vf(m,null)}),d.forEach(function(m){o.has(m)||Vf(m,h)})}Nb.set(l,t)},[t]),l}function KR(t){return t}function PR(t,a){a===void 0&&(a=KR);var l=[],s=!1,o={read:function(){if(s)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return l.length?l[l.length-1]:t},useMedium:function(d){var h=a(d,s);return l.push(h),function(){l=l.filter(function(m){return m!==h})}},assignSyncMedium:function(d){for(s=!0;l.length;){var h=l;l=[],h.forEach(d)}l={push:function(m){return d(m)},filter:function(){return l}}},assignMedium:function(d){s=!0;var h=[];if(l.length){var m=l;l=[],m.forEach(d),h=l}var g=function(){var x=h;h=[],x.forEach(d)},p=function(){return Promise.resolve().then(g)};p(),l={push:function(x){h.push(x),p()},filter:function(x){return h=h.filter(x),l}}}};return o}function FR(t){t===void 0&&(t={});var a=PR(null);return a.options=Jn({async:!0,ssr:!1},t),a}var rS=function(t){var a=t.sideCar,l=aS(t,["sideCar"]);if(!a)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var s=a.read();if(!s)throw new Error("Sidecar medium not found");return y.createElement(s,Jn({},l))};rS.isSideCarExport=!0;function XR(t,a){return t.useMedium(a),rS}var lS=FR(),Yf=function(){},ic=y.forwardRef(function(t,a){var l=y.useRef(null),s=y.useState({onScrollCapture:Yf,onWheelCapture:Yf,onTouchMoveCapture:Yf}),o=s[0],d=s[1],h=t.forwardProps,m=t.children,g=t.className,p=t.removeScrollBar,x=t.enabled,b=t.shards,j=t.sideCar,w=t.noRelative,C=t.noIsolation,N=t.inert,_=t.allowPinchZoom,R=t.as,Q=R===void 0?"div":R,q=t.gapMode,B=aS(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),F=j,J=YR([l,a]),K=Jn(Jn({},B),o);return y.createElement(y.Fragment,null,x&&y.createElement(F,{sideCar:lS,removeScrollBar:p,shards:b,noRelative:w,noIsolation:C,inert:N,setCallbacks:d,allowPinchZoom:!!_,lockRef:l,gapMode:q}),h?y.cloneElement(y.Children.only(m),Jn(Jn({},K),{ref:J})):y.createElement(Q,Jn({},K,{className:g,ref:J}),m))});ic.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};ic.classNames={fullWidth:Zu,zeroRight:Lu};var JR=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function WR(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var a=JR();return a&&t.setAttribute("nonce",a),t}function eM(t,a){t.styleSheet?t.styleSheet.cssText=a:t.appendChild(document.createTextNode(a))}function tM(t){var a=document.head||document.getElementsByTagName("head")[0];a.appendChild(t)}var nM=function(){var t=0,a=null;return{add:function(l){t==0&&(a=WR())&&(eM(a,l),tM(a)),t++},remove:function(){t--,!t&&a&&(a.parentNode&&a.parentNode.removeChild(a),a=null)}}},aM=function(){var t=nM();return function(a,l){y.useEffect(function(){return t.add(a),function(){t.remove()}},[a&&l])}},sS=function(){var t=aM(),a=function(l){var s=l.styles,o=l.dynamic;return t(s,o),null};return a},rM={left:0,top:0,right:0,gap:0},Kf=function(t){return parseInt(t||"",10)||0},lM=function(t){var a=window.getComputedStyle(document.body),l=a[t==="padding"?"paddingLeft":"marginLeft"],s=a[t==="padding"?"paddingTop":"marginTop"],o=a[t==="padding"?"paddingRight":"marginRight"];return[Kf(l),Kf(s),Kf(o)]},sM=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return rM;var a=lM(t),l=document.documentElement.clientWidth,s=window.innerWidth;return{left:a[0],top:a[1],right:a[2],gap:Math.max(0,s-l+a[2]-a[0])}},iM=sS(),cs="data-scroll-locked",oM=function(t,a,l,s){var o=t.left,d=t.top,h=t.right,m=t.gap;return l===void 0&&(l="margin"),`
263
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const x of t.seen.entries()){const b=x[1];if(a===x[0]){d(x);continue}if(t.external){const w=(g=t.external.registry.get(x[0]))==null?void 0:g.id;if(a!==x[0]&&w){d(x);continue}}if((p=t.metadataRegistry.get(x[0]))==null?void 0:p.id){d(x);continue}if(b.cycle){d(x);continue}if(b.count>1&&t.reused==="ref"){d(x);continue}}}function k0(t,a){var h,m,g;const l=t.seen.get(a);if(!l)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=p=>{const x=t.seen.get(p);if(x.ref===null)return;const b=x.def??x.schema,j={...b},w=x.ref;if(x.ref=null,w){s(w);const N=t.seen.get(w),_=N.schema;if(_.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(b.allOf=b.allOf??[],b.allOf.push(_)):Object.assign(b,_),Object.assign(b,j),p._zod.parent===w)for(const Q in b)Q==="$ref"||Q==="allOf"||Q in j||delete b[Q];if(_.$ref&&N.def)for(const Q in b)Q==="$ref"||Q==="allOf"||Q in N.def&&JSON.stringify(b[Q])===JSON.stringify(N.def[Q])&&delete b[Q]}const C=p._zod.parent;if(C&&C!==w){s(C);const N=t.seen.get(C);if(N!=null&&N.schema.$ref&&(b.$ref=N.schema.$ref,N.def))for(const _ in b)_==="$ref"||_==="allOf"||_ in N.def&&JSON.stringify(b[_])===JSON.stringify(N.def[_])&&delete b[_]}t.override({zodSchema:p,jsonSchema:b,path:x.path??[]})};for(const p of[...t.seen.entries()].reverse())s(p[0]);const o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,(h=t.external)!=null&&h.uri){const p=(m=t.external.registry.get(a))==null?void 0:m.id;if(!p)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(p)}Object.assign(o,l.def??l.schema);const d=((g=t.external)==null?void 0:g.defs)??{};for(const p of t.seen.entries()){const x=p[1];x.def&&x.defId&&(d[x.defId]=x.def)}t.external||Object.keys(d).length>0&&(t.target==="draft-2020-12"?o.$defs=d:o.definitions=d);try{const p=JSON.parse(JSON.stringify(o));return Object.defineProperty(p,"~standard",{value:{...a["~standard"],jsonSchema:{input:Vu(a,"input",t.processors),output:Vu(a,"output",t.processors)}},enumerable:!1,writable:!1}),p}catch{throw new Error("Error converting schema to JSON.")}}function Kt(t,a){const l=a??{seen:new Set};if(l.seen.has(t))return!1;l.seen.add(t);const s=t._zod.def;if(s.type==="transform")return!0;if(s.type==="array")return Kt(s.element,l);if(s.type==="set")return Kt(s.valueType,l);if(s.type==="lazy")return Kt(s.getter(),l);if(s.type==="promise"||s.type==="optional"||s.type==="nonoptional"||s.type==="nullable"||s.type==="readonly"||s.type==="default"||s.type==="prefault")return Kt(s.innerType,l);if(s.type==="intersection")return Kt(s.left,l)||Kt(s.right,l);if(s.type==="record"||s.type==="map")return Kt(s.keyType,l)||Kt(s.valueType,l);if(s.type==="pipe")return Kt(s.in,l)||Kt(s.out,l);if(s.type==="object"){for(const o in s.shape)if(Kt(s.shape[o],l))return!0;return!1}if(s.type==="union"){for(const o of s.options)if(Kt(o,l))return!0;return!1}if(s.type==="tuple"){for(const o of s.items)if(Kt(o,l))return!0;return!!(s.rest&&Kt(s.rest,l))}return!1}const qT=(t,a={})=>l=>{const s=R0({...l,processors:a});return Ct(t,s),M0(s,t),k0(s,t)},Vu=(t,a,l={})=>s=>{const{libraryOptions:o,target:d}=s??{},h=R0({...o??{},target:d,io:a,processors:l});return Ct(t,h),M0(h,t),k0(h,t)},BT={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},$T=(t,a,l,s)=>{const o=l;o.type="string";const{minimum:d,maximum:h,format:m,patterns:g,contentEncoding:p}=t._zod.bag;if(typeof d=="number"&&(o.minLength=d),typeof h=="number"&&(o.maxLength=h),m&&(o.format=BT[m]??m,o.format===""&&delete o.format,m==="time"&&delete o.format),p&&(o.contentEncoding=p),g&&g.size>0){const x=[...g];x.length===1?o.pattern=x[0].source:x.length>1&&(o.allOf=[...x.map(b=>({...a.target==="draft-07"||a.target==="draft-04"||a.target==="openapi-3.0"?{type:"string"}:{},pattern:b.source}))])}},HT=(t,a,l,s)=>{const o=l,{minimum:d,maximum:h,format:m,multipleOf:g,exclusiveMaximum:p,exclusiveMinimum:x}=t._zod.bag;typeof m=="string"&&m.includes("int")?o.type="integer":o.type="number",typeof x=="number"&&(a.target==="draft-04"||a.target==="openapi-3.0"?(o.minimum=x,o.exclusiveMinimum=!0):o.exclusiveMinimum=x),typeof d=="number"&&(o.minimum=d,typeof x=="number"&&a.target!=="draft-04"&&(x>=d?delete o.minimum:delete o.exclusiveMinimum)),typeof p=="number"&&(a.target==="draft-04"||a.target==="openapi-3.0"?(o.maximum=p,o.exclusiveMaximum=!0):o.exclusiveMaximum=p),typeof h=="number"&&(o.maximum=h,typeof p=="number"&&a.target!=="draft-04"&&(p<=h?delete o.maximum:delete o.exclusiveMaximum)),typeof g=="number"&&(o.multipleOf=g)},QT=(t,a,l,s)=>{l.type="boolean"},GT=(t,a,l,s)=>{l.not={}},IT=(t,a,l,s)=>{},VT=(t,a,l,s)=>{const o=t._zod.def,d=d0(o.entries);d.every(h=>typeof h=="number")&&(l.type="number"),d.every(h=>typeof h=="string")&&(l.type="string"),l.enum=d},YT=(t,a,l,s)=>{const o=t._zod.def,d=[];for(const h of o.values)if(h===void 0){if(a.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof h=="bigint"){if(a.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");d.push(Number(h))}else d.push(h);if(d.length!==0)if(d.length===1){const h=d[0];l.type=h===null?"null":typeof h,a.target==="draft-04"||a.target==="openapi-3.0"?l.enum=[h]:l.const=h}else d.every(h=>typeof h=="number")&&(l.type="number"),d.every(h=>typeof h=="string")&&(l.type="string"),d.every(h=>typeof h=="boolean")&&(l.type="boolean"),d.every(h=>h===null)&&(l.type="null"),l.enum=d},KT=(t,a,l,s)=>{if(a.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},PT=(t,a,l,s)=>{if(a.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},FT=(t,a,l,s)=>{const o=l,d=t._zod.def,{minimum:h,maximum:m}=t._zod.bag;typeof h=="number"&&(o.minItems=h),typeof m=="number"&&(o.maxItems=m),o.type="array",o.items=Ct(d.element,a,{...s,path:[...s.path,"items"]})},XT=(t,a,l,s)=>{var p;const o=l,d=t._zod.def;o.type="object",o.properties={};const h=d.shape;for(const x in h)o.properties[x]=Ct(h[x],a,{...s,path:[...s.path,"properties",x]});const m=new Set(Object.keys(h)),g=new Set([...m].filter(x=>{const b=d.shape[x]._zod;return a.io==="input"?b.optin===void 0:b.optout===void 0}));g.size>0&&(o.required=Array.from(g)),((p=d.catchall)==null?void 0:p._zod.def.type)==="never"?o.additionalProperties=!1:d.catchall?d.catchall&&(o.additionalProperties=Ct(d.catchall,a,{...s,path:[...s.path,"additionalProperties"]})):a.io==="output"&&(o.additionalProperties=!1)},JT=(t,a,l,s)=>{const o=t._zod.def,d=o.inclusive===!1,h=o.options.map((m,g)=>Ct(m,a,{...s,path:[...s.path,d?"oneOf":"anyOf",g]}));d?l.oneOf=h:l.anyOf=h},WT=(t,a,l,s)=>{const o=t._zod.def,d=Ct(o.left,a,{...s,path:[...s.path,"allOf",0]}),h=Ct(o.right,a,{...s,path:[...s.path,"allOf",1]}),m=p=>"allOf"in p&&Object.keys(p).length===1,g=[...m(d)?d.allOf:[d],...m(h)?h.allOf:[h]];l.allOf=g},ez=(t,a,l,s)=>{const o=l,d=t._zod.def;o.type="object";const h=d.keyType,m=h._zod.bag,g=m==null?void 0:m.patterns;if(d.mode==="loose"&&g&&g.size>0){const x=Ct(d.valueType,a,{...s,path:[...s.path,"patternProperties","*"]});o.patternProperties={};for(const b of g)o.patternProperties[b.source]=x}else(a.target==="draft-07"||a.target==="draft-2020-12")&&(o.propertyNames=Ct(d.keyType,a,{...s,path:[...s.path,"propertyNames"]})),o.additionalProperties=Ct(d.valueType,a,{...s,path:[...s.path,"additionalProperties"]});const p=h._zod.values;if(p){const x=[...p].filter(b=>typeof b=="string"||typeof b=="number");x.length>0&&(o.required=x)}},tz=(t,a,l,s)=>{const o=t._zod.def,d=Ct(o.innerType,a,s),h=a.seen.get(t);a.target==="openapi-3.0"?(h.ref=o.innerType,l.nullable=!0):l.anyOf=[d,{type:"null"}]},nz=(t,a,l,s)=>{const o=t._zod.def;Ct(o.innerType,a,s);const d=a.seen.get(t);d.ref=o.innerType},az=(t,a,l,s)=>{const o=t._zod.def;Ct(o.innerType,a,s);const d=a.seen.get(t);d.ref=o.innerType,l.default=JSON.parse(JSON.stringify(o.defaultValue))},rz=(t,a,l,s)=>{const o=t._zod.def;Ct(o.innerType,a,s);const d=a.seen.get(t);d.ref=o.innerType,a.io==="input"&&(l._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},lz=(t,a,l,s)=>{const o=t._zod.def;Ct(o.innerType,a,s);const d=a.seen.get(t);d.ref=o.innerType;let h;try{h=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}l.default=h},sz=(t,a,l,s)=>{const o=t._zod.def,d=a.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;Ct(d,a,s);const h=a.seen.get(t);h.ref=d},iz=(t,a,l,s)=>{const o=t._zod.def;Ct(o.innerType,a,s);const d=a.seen.get(t);d.ref=o.innerType,l.readOnly=!0},D0=(t,a,l,s)=>{const o=t._zod.def;Ct(o.innerType,a,s);const d=a.seen.get(t);d.ref=o.innerType},oz=I("ZodISODateTime",(t,a)=>{oA.init(t,a),mt.init(t,a)});function uz(t){return mT(oz,t)}const cz=I("ZodISODate",(t,a)=>{uA.init(t,a),mt.init(t,a)});function dz(t){return pT(cz,t)}const fz=I("ZodISOTime",(t,a)=>{cA.init(t,a),mt.init(t,a)});function hz(t){return gT(fz,t)}const mz=I("ZodISODuration",(t,a)=>{dA.init(t,a),mt.init(t,a)});function pz(t){return vT(mz,t)}const gz=(t,a)=>{p0.init(t,a),t.name="ZodError",Object.defineProperties(t,{format:{value:l=>tC(t,l)},flatten:{value:l=>eC(t,l)},addIssue:{value:l=>{t.issues.push(l),t.message=JSON.stringify(t.issues,bh,2)}},addIssues:{value:l=>{t.issues.push(...l),t.message=JSON.stringify(t.issues,bh,2)}},isEmpty:{get(){return t.issues.length===0}}})},Un=I("ZodError",gz,{Parent:Error}),vz=Fh(Un),yz=Xh(Un),bz=ec(Un),xz=tc(Un),Sz=rC(Un),jz=lC(Un),Nz=sC(Un),wz=iC(Un),_z=oC(Un),Ez=uC(Un),Cz=cC(Un),Az=dC(Un),ht=I("ZodType",(t,a)=>(ft.init(t,a),Object.assign(t["~standard"],{jsonSchema:{input:Vu(t,"input"),output:Vu(t,"output")}}),t.toJSONSchema=qT(t,{}),t.def=a,t.type=a.type,Object.defineProperty(t,"_def",{value:a}),t.check=(...l)=>t.clone(zr(a,{checks:[...a.checks??[],...l.map(s=>typeof s=="function"?{_zod:{check:s,def:{check:"custom"},onattach:[]}}:s)]}),{parent:!0}),t.with=t.check,t.clone=(l,s)=>Or(t,l,s),t.brand=()=>t,t.register=((l,s)=>(l.add(t,s),t)),t.parse=(l,s)=>vz(t,l,s,{callee:t.parse}),t.safeParse=(l,s)=>bz(t,l,s),t.parseAsync=async(l,s)=>yz(t,l,s,{callee:t.parseAsync}),t.safeParseAsync=async(l,s)=>xz(t,l,s),t.spa=t.safeParseAsync,t.encode=(l,s)=>Sz(t,l,s),t.decode=(l,s)=>jz(t,l,s),t.encodeAsync=async(l,s)=>Nz(t,l,s),t.decodeAsync=async(l,s)=>wz(t,l,s),t.safeEncode=(l,s)=>_z(t,l,s),t.safeDecode=(l,s)=>Ez(t,l,s),t.safeEncodeAsync=async(l,s)=>Cz(t,l,s),t.safeDecodeAsync=async(l,s)=>Az(t,l,s),t.refine=(l,s)=>t.check(NO(l,s)),t.superRefine=l=>t.check(wO(l)),t.overwrite=l=>t.check(Rs(l)),t.optional=()=>fb(t),t.exactOptional=()=>cO(t),t.nullable=()=>hb(t),t.nullish=()=>fb(hb(t)),t.nonoptional=l=>gO(t,l),t.array=()=>ea(t),t.or=l=>eO([t,l]),t.and=l=>rO(t,l),t.transform=l=>mb(t,oO(l)),t.default=l=>hO(t,l),t.prefault=l=>pO(t,l),t.catch=l=>yO(t,l),t.pipe=l=>mb(t,l),t.readonly=()=>SO(t),t.describe=l=>{const s=t.clone();return ki.add(s,{description:l}),s},Object.defineProperty(t,"description",{get(){var l;return(l=ki.get(t))==null?void 0:l.description},configurable:!0}),t.meta=(...l)=>{if(l.length===0)return ki.get(t);const s=t.clone();return ki.add(s,l[0]),s},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=l=>l(t),t)),U0=I("_ZodString",(t,a)=>{Jh.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(s,o,d)=>$T(t,s,o);const l=t._zod.bag;t.format=l.format??null,t.minLength=l.minimum??null,t.maxLength=l.maximum??null,t.regex=(...s)=>t.check(wT(...s)),t.includes=(...s)=>t.check(CT(...s)),t.startsWith=(...s)=>t.check(AT(...s)),t.endsWith=(...s)=>t.check(TT(...s)),t.min=(...s)=>t.check(Iu(...s)),t.max=(...s)=>t.check(z0(...s)),t.length=(...s)=>t.check(O0(...s)),t.nonempty=(...s)=>t.check(Iu(1,...s)),t.lowercase=s=>t.check(_T(s)),t.uppercase=s=>t.check(ET(s)),t.trim=()=>t.check(OT()),t.normalize=(...s)=>t.check(zT(...s)),t.toLowerCase=()=>t.check(RT()),t.toUpperCase=()=>t.check(MT()),t.slugify=()=>t.check(kT())}),Tz=I("ZodString",(t,a)=>{Jh.init(t,a),U0.init(t,a),t.email=l=>t.check(YA(zz,l)),t.url=l=>t.check(JA(Oz,l)),t.jwt=l=>t.check(hT(Vz,l)),t.emoji=l=>t.check(WA(Rz,l)),t.guid=l=>t.check(sb(cb,l)),t.uuid=l=>t.check(KA(Au,l)),t.uuidv4=l=>t.check(PA(Au,l)),t.uuidv6=l=>t.check(FA(Au,l)),t.uuidv7=l=>t.check(XA(Au,l)),t.nanoid=l=>t.check(eT(Mz,l)),t.guid=l=>t.check(sb(cb,l)),t.cuid=l=>t.check(tT(kz,l)),t.cuid2=l=>t.check(nT(Dz,l)),t.ulid=l=>t.check(aT(Uz,l)),t.base64=l=>t.check(cT(Qz,l)),t.base64url=l=>t.check(dT(Gz,l)),t.xid=l=>t.check(rT(Lz,l)),t.ksuid=l=>t.check(lT(Zz,l)),t.ipv4=l=>t.check(sT(qz,l)),t.ipv6=l=>t.check(iT(Bz,l)),t.cidrv4=l=>t.check(oT($z,l)),t.cidrv6=l=>t.check(uT(Hz,l)),t.e164=l=>t.check(fT(Iz,l)),t.datetime=l=>t.check(uz(l)),t.date=l=>t.check(dz(l)),t.time=l=>t.check(hz(l)),t.duration=l=>t.check(pz(l))});function E(t){return VA(Tz,t)}const mt=I("ZodStringFormat",(t,a)=>{dt.init(t,a),U0.init(t,a)}),zz=I("ZodEmail",(t,a)=>{WC.init(t,a),mt.init(t,a)}),cb=I("ZodGUID",(t,a)=>{XC.init(t,a),mt.init(t,a)}),Au=I("ZodUUID",(t,a)=>{JC.init(t,a),mt.init(t,a)}),Oz=I("ZodURL",(t,a)=>{eA.init(t,a),mt.init(t,a)}),Rz=I("ZodEmoji",(t,a)=>{tA.init(t,a),mt.init(t,a)}),Mz=I("ZodNanoID",(t,a)=>{nA.init(t,a),mt.init(t,a)}),kz=I("ZodCUID",(t,a)=>{aA.init(t,a),mt.init(t,a)}),Dz=I("ZodCUID2",(t,a)=>{rA.init(t,a),mt.init(t,a)}),Uz=I("ZodULID",(t,a)=>{lA.init(t,a),mt.init(t,a)}),Lz=I("ZodXID",(t,a)=>{sA.init(t,a),mt.init(t,a)}),Zz=I("ZodKSUID",(t,a)=>{iA.init(t,a),mt.init(t,a)}),qz=I("ZodIPv4",(t,a)=>{fA.init(t,a),mt.init(t,a)}),Bz=I("ZodIPv6",(t,a)=>{hA.init(t,a),mt.init(t,a)}),$z=I("ZodCIDRv4",(t,a)=>{mA.init(t,a),mt.init(t,a)}),Hz=I("ZodCIDRv6",(t,a)=>{pA.init(t,a),mt.init(t,a)}),Qz=I("ZodBase64",(t,a)=>{gA.init(t,a),mt.init(t,a)}),Gz=I("ZodBase64URL",(t,a)=>{yA.init(t,a),mt.init(t,a)}),Iz=I("ZodE164",(t,a)=>{bA.init(t,a),mt.init(t,a)}),Vz=I("ZodJWT",(t,a)=>{SA.init(t,a),mt.init(t,a)}),Wh=I("ZodNumber",(t,a)=>{_0.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(s,o,d)=>HT(t,s,o),t.gt=(s,o)=>t.check(ob(s,o)),t.gte=(s,o)=>t.check(qf(s,o)),t.min=(s,o)=>t.check(qf(s,o)),t.lt=(s,o)=>t.check(ib(s,o)),t.lte=(s,o)=>t.check(Zf(s,o)),t.max=(s,o)=>t.check(Zf(s,o)),t.int=s=>t.check(db(s)),t.safe=s=>t.check(db(s)),t.positive=s=>t.check(ob(0,s)),t.nonnegative=s=>t.check(qf(0,s)),t.negative=s=>t.check(ib(0,s)),t.nonpositive=s=>t.check(Zf(0,s)),t.multipleOf=(s,o)=>t.check(ub(s,o)),t.step=(s,o)=>t.check(ub(s,o)),t.finite=()=>t;const l=t._zod.bag;t.minValue=Math.max(l.minimum??Number.NEGATIVE_INFINITY,l.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(l.maximum??Number.POSITIVE_INFINITY,l.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(l.format??"").includes("int")||Number.isSafeInteger(l.multipleOf??.5),t.isFinite=!0,t.format=l.format??null});function Ve(t){return yT(Wh,t)}const Yz=I("ZodNumberFormat",(t,a)=>{jA.init(t,a),Wh.init(t,a)});function db(t){return xT(Yz,t)}const Kz=I("ZodBoolean",(t,a)=>{NA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>QT(t,l,s)});function ac(t){return ST(Kz,t)}const Pz=I("ZodUnknown",(t,a)=>{wA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>IT()});function it(){return jT(Pz)}const Fz=I("ZodNever",(t,a)=>{_A.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>GT(t,l,s)});function Xz(t){return NT(Fz,t)}const Jz=I("ZodArray",(t,a)=>{EA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>FT(t,l,s,o),t.element=a.element,t.min=(l,s)=>t.check(Iu(l,s)),t.nonempty=l=>t.check(Iu(1,l)),t.max=(l,s)=>t.check(z0(l,s)),t.length=(l,s)=>t.check(O0(l,s)),t.unwrap=()=>t.element});function ea(t,a){return DT(Jz,t,a)}const Wz=I("ZodObject",(t,a)=>{AA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>XT(t,l,s,o),Ye(t,"shape",()=>a.shape),t.keyof=()=>Xe(Object.keys(t._zod.def.shape)),t.catchall=l=>t.clone({...t._zod.def,catchall:l}),t.passthrough=()=>t.clone({...t._zod.def,catchall:it()}),t.loose=()=>t.clone({...t._zod.def,catchall:it()}),t.strict=()=>t.clone({...t._zod.def,catchall:Xz()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=l=>P2(t,l),t.safeExtend=l=>F2(t,l),t.merge=l=>X2(t,l),t.pick=l=>Y2(t,l),t.omit=l=>K2(t,l),t.partial=(...l)=>J2(Z0,t,l[0]),t.required=(...l)=>W2(q0,t,l[0])});function ne(t,a){const l={type:"object",shape:t??{},...he(a)};return new Wz(l)}const L0=I("ZodUnion",(t,a)=>{A0.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>JT(t,l,s,o),t.options=a.options});function eO(t,a){return new L0({type:"union",options:t,...he(a)})}const tO=I("ZodDiscriminatedUnion",(t,a)=>{L0.init(t,a),TA.init(t,a)});function nO(t,a,l){return new tO({type:"union",options:a,discriminator:t,...he(l)})}const aO=I("ZodIntersection",(t,a)=>{zA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>WT(t,l,s,o)});function rO(t,a){return new aO({type:"intersection",left:t,right:a})}const lO=I("ZodRecord",(t,a)=>{OA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>ez(t,l,s,o),t.keyType=a.keyType,t.valueType=a.valueType});function Ot(t,a,l){return new lO({type:"record",keyType:t,valueType:a,...he(l)})}const Sh=I("ZodEnum",(t,a)=>{RA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(s,o,d)=>VT(t,s,o),t.enum=a.entries,t.options=Object.values(a.entries);const l=new Set(Object.keys(a.entries));t.extract=(s,o)=>{const d={};for(const h of s)if(l.has(h))d[h]=a.entries[h];else throw new Error(`Key ${h} not found in enum`);return new Sh({...a,checks:[],...he(o),entries:d})},t.exclude=(s,o)=>{const d={...a.entries};for(const h of s)if(l.has(h))delete d[h];else throw new Error(`Key ${h} not found in enum`);return new Sh({...a,checks:[],...he(o),entries:d})}});function Xe(t,a){const l=Array.isArray(t)?Object.fromEntries(t.map(s=>[s,s])):t;return new Sh({type:"enum",entries:l,...he(a)})}const sO=I("ZodLiteral",(t,a)=>{MA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>YT(t,l,s),t.values=new Set(a.values),Object.defineProperty(t,"value",{get(){if(a.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return a.values[0]}})});function rc(t,a){return new sO({type:"literal",values:Array.isArray(t)?t:[t],...he(a)})}const iO=I("ZodTransform",(t,a)=>{kA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>PT(t,l),t._zod.parse=(l,s)=>{if(s.direction==="backward")throw new u0(t.constructor.name);l.addIssue=d=>{if(typeof d=="string")l.issues.push($i(d,l.value,a));else{const h=d;h.fatal&&(h.continue=!1),h.code??(h.code="custom"),h.input??(h.input=l.value),h.inst??(h.inst=t),l.issues.push($i(h))}};const o=a.transform(l.value,l);return o instanceof Promise?o.then(d=>(l.value=d,l)):(l.value=o,l)}});function oO(t){return new iO({type:"transform",transform:t})}const Z0=I("ZodOptional",(t,a)=>{T0.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>D0(t,l,s,o),t.unwrap=()=>t._zod.def.innerType});function fb(t){return new Z0({type:"optional",innerType:t})}const uO=I("ZodExactOptional",(t,a)=>{DA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>D0(t,l,s,o),t.unwrap=()=>t._zod.def.innerType});function cO(t){return new uO({type:"optional",innerType:t})}const dO=I("ZodNullable",(t,a)=>{UA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>tz(t,l,s,o),t.unwrap=()=>t._zod.def.innerType});function hb(t){return new dO({type:"nullable",innerType:t})}const fO=I("ZodDefault",(t,a)=>{LA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>az(t,l,s,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function hO(t,a){return new fO({type:"default",innerType:t,get defaultValue(){return typeof a=="function"?a():h0(a)}})}const mO=I("ZodPrefault",(t,a)=>{ZA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>rz(t,l,s,o),t.unwrap=()=>t._zod.def.innerType});function pO(t,a){return new mO({type:"prefault",innerType:t,get defaultValue(){return typeof a=="function"?a():h0(a)}})}const q0=I("ZodNonOptional",(t,a)=>{qA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>nz(t,l,s,o),t.unwrap=()=>t._zod.def.innerType});function gO(t,a){return new q0({type:"nonoptional",innerType:t,...he(a)})}const vO=I("ZodCatch",(t,a)=>{BA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>lz(t,l,s,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function yO(t,a){return new vO({type:"catch",innerType:t,catchValue:typeof a=="function"?a:()=>a})}const bO=I("ZodPipe",(t,a)=>{$A.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>sz(t,l,s,o),t.in=a.in,t.out=a.out});function mb(t,a){return new bO({type:"pipe",in:t,out:a})}const xO=I("ZodReadonly",(t,a)=>{HA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>iz(t,l,s,o),t.unwrap=()=>t._zod.def.innerType});function SO(t){return new xO({type:"readonly",innerType:t})}const jO=I("ZodCustom",(t,a)=>{QA.init(t,a),ht.init(t,a),t._zod.processJSONSchema=(l,s,o)=>KT(t,l)});function NO(t,a={}){return UT(jO,t,a)}function wO(t){return LT(t)}const Bf={custom:"custom"};function lc(t){return bT(Wh,t)}const _O={FEISHU:"feishu",SLACK:"slack",KAEL:"kael"},B0=Xe(["feishu","slack","kael"]),$0=Xe(["active","inactive"]);ne({platform:B0,agentId:E().min(1),credentials:Ot(E(),it()),status:$0.default("active")});ne({agentId:E().min(1).optional(),credentials:Ot(E(),it()).optional(),status:$0.optional()});ne({id:Ve(),platform:E(),agentId:E(),hasCredentials:ac(),status:E(),createdAt:E(),updatedAt:E()});const EO=Xe(["code","reverse_token","oauth","manual"]);ne({appId:E().min(1),appSecret:E().min(1)});ne({platform:B0,externalUserId:E().min(1),agentId:E().min(1),boundVia:EO.default("manual"),displayName:E().max(200).optional()});ne({id:Ve(),platform:E(),externalUserId:E(),agentId:E(),boundVia:E().nullable(),displayName:E().nullable(),createdAt:E()});ne({feishuUserId:E().min(1),displayName:E().max(200).optional()});ne({configId:Ve(),platform:E(),agentId:E(),appId:E(),connected:ac(),lastActiveAt:E().nullable()});const H0=Xe(["online","offline"]),Q0=Xe(["idle","working","blocked","error"]),CO=Xe(["active","suspended","evicted"]);ne({chatId:E().min(1),state:CO});ne({runtimeState:Q0});ne({agentId:E().min(1),runtimeType:E().max(50),runtimeVersion:E().max(50).optional()});Xe(["wrong_client","not_owned","agent_suspended","wrong_org","unknown_agent"]);ne({agentId:E(),status:H0,connectedAt:E().nullable(),lastSeenAt:E(),clientId:E().nullable().optional(),runtimeType:E().nullable().optional(),runtimeVersion:E().nullable().optional(),runtimeState:Q0.nullable().optional(),activeSessions:Ve().int().nullable().optional(),totalSessions:Ve().int().nullable().optional(),runtimeUpdatedAt:E().nullable().optional()});ne({total:Ve().int(),running:Ve().int(),byState:ne({idle:Ve().int(),working:Ve().int(),blocked:Ve().int(),error:Ve().int()}),clients:Ve().int()});const G0={HUMAN:"human",PERSONAL_ASSISTANT:"personal_assistant",AUTONOMOUS_AGENT:"autonomous_agent"},em=Xe(["human","personal_assistant","autonomous_agent"]),tm=Xe(["private","organization"]),AO=Xe(["admin-api","portal"]);Xe(["active","suspended"]);ne({name:E().min(1).max(100).regex(/^[a-z0-9_-]+$/,"Only lowercase alphanumeric, hyphens, and underscores").optional(),type:em,displayName:E().max(200).optional(),delegateMention:E().max(100).optional(),organizationId:E().max(100).optional(),source:AO.optional(),visibility:tm.optional(),metadata:Ot(E(),it()).optional(),managerId:E().optional(),clientId:E().min(1).max(100).optional()});ne({type:em.optional(),displayName:E().max(200).nullable().optional(),delegateMention:E().max(100).nullable().optional(),visibility:tm.optional(),metadata:Ot(E(),it()).optional(),managerId:E().nullable().optional(),clientId:E().min(1).max(100).nullable().optional()});ne({uuid:E(),name:E().nullable(),organizationId:E(),type:em,displayName:E().nullable(),delegateMention:E().nullable(),inboxId:E(),status:E(),source:E().nullable().optional(),cloudUserId:E().nullable().optional(),visibility:tm,metadata:Ot(E(),it()),managerId:E().nullable(),clientId:E().nullable(),presenceStatus:H0.optional(),createdAt:E(),updatedAt:E()});ne({repo:E().nullable(),branch:E().nullable()});const TO=32e3,nm=/^[a-z0-9][a-z0-9_-]{0,63}$/i,zO=/^[A-Z][A-Z0-9_]*$/,OO=ne({append:E().max(TO).default("")}),RO=ne({name:E().regex(nm,"MCP name must match /^[a-z0-9][a-z0-9_-]{0,63}$/i"),transport:rc("stdio"),command:E().min(1),args:ea(E()).optional()}),MO=ne({name:E().regex(nm,"MCP name must match /^[a-z0-9][a-z0-9_-]{0,63}$/i"),transport:rc("http"),url:E().url(),headers:Ot(E(),E()).optional()}),kO=ne({name:E().regex(nm,"MCP name must match /^[a-z0-9][a-z0-9_-]{0,63}$/i"),transport:rc("sse"),url:E().url(),headers:Ot(E(),E()).optional()}),DO=nO("transport",[RO,MO,kO]),UO=ne({key:E().regex(zO,"Env key must match /^[A-Z][A-Z0-9_]*$/"),value:E(),sensitive:ac().default(!1)}),LO=ne({url:E().min(1),ref:E().min(1).optional(),localPath:E().min(1).optional()}),am=ne({prompt:OO.default({append:""}),model:E().default(""),mcpServers:ea(DO).default([]),env:ea(UO).default([]),gitRepos:ea(LO).default([])}),ZO=(t,a)=>{const l=new Set;t.mcpServers.forEach((d,h)=>{const m=d.name.toLowerCase();l.has(m)&&a.addIssue({code:Bf.custom,path:["mcpServers",h,"name"],message:`Duplicate MCP server name "${d.name}"`}),l.add(m)});const s=new Set;t.env.forEach((d,h)=>{s.has(d.key)&&a.addIssue({code:Bf.custom,path:["env",h,"key"],message:`Duplicate env key "${d.key}"`}),s.add(d.key)});const o=new Set;t.gitRepos.forEach((d,h)=>{const m=d.localPath??Yu(d.url);m&&(o.has(m)&&a.addIssue({code:Bf.custom,path:["gitRepos",h,"localPath"],message:`Duplicate git repo local path "${m}"`}),o.add(m))})},I0=am.superRefine(ZO),qO=ne({agentId:E(),version:Ve().int().positive(),payload:I0,updatedAt:E(),updatedBy:E()});ne({expectedVersion:Ve().int().positive(),payload:am.partial()});ne({payload:am.partial()});ne({current:qO,next:I0,diff:ea(ne({path:E(),op:Xe(["add","remove","replace"]),before:it().optional(),after:it().optional()}))});const jh="***";function Yu(t){const a=t.trim();return a?((a.split(/[?#]/)[0]??"").split(/[/:]/).filter(Boolean).pop()??"").replace(/\.git$/i,""):""}ne({username:E().min(1),password:E().min(1)});ne({accessToken:E(),refreshToken:E()});ne({refreshToken:E().min(1)});ne({token:E().min(1)});ne({token:E(),expiresIn:Ve(),command:E()});const BO=Xe(["direct","group","thread"]);ne({type:BO,topic:E().max(500).optional(),participantIds:ea(E()).min(1),metadata:Ot(E(),it()).optional()});const $O=ne({agentId:E(),role:E(),mode:E(),joinedAt:E()}),HO=ne({id:E(),organizationId:E(),type:E(),topic:E().nullable(),lifecyclePolicy:E().nullable().optional(),metadata:Ot(E(),it()),createdAt:E(),updatedAt:E()});HO.extend({participants:ea($O)});ne({agentId:E().min(1),mode:Xe(["full","mention_only"]).default("full")});ne({agentId:E().min(1)});const QO=Xe(["connected","disconnected"]);ne({id:E(),userId:E().nullable(),status:QO,sdkVersion:E().max(50).nullable(),hostname:E().max(100).nullable(),os:E().max(50).nullable(),agentCount:Ve().int().min(0),connectedAt:E().nullable(),lastSeenAt:E(),metadata:Ot(E(),it()).nullable()});ne({clientId:E().min(1).max(100),hostname:E().max(100).optional(),os:E().max(50).optional(),sdkVersion:E().max(50).optional()});ne({limit:lc().int().min(1).max(100).default(20),cursor:E().optional()});const rm=Xe(["hub_ui","cli","feishu","github","api"]),V0=Xe(["text","markdown","card","reference","file","task"]);ne({format:V0.default("text"),content:it(),metadata:Ot(E(),it()).optional(),inReplyTo:E().optional(),replyToInbox:E().optional(),replyToChat:E().optional(),source:rm.optional()});ne({format:V0.default("text"),content:it(),metadata:Ot(E(),it()).optional(),replyToInbox:E().optional(),replyToChat:E().optional(),source:rm.optional()});const GO=ne({id:E(),chatId:E(),senderId:E(),format:E(),content:it(),metadata:Ot(E(),it()),replyToInbox:E().nullable(),replyToChat:E().nullable(),inReplyTo:E().nullable(),source:rm.nullable(),createdAt:E()}),IO=GO.extend({configVersion:Ve().int().positive()});Xe(["pending","delivered","acked","failed"]);const VO=ne({id:Ve(),inboxId:E(),messageId:E(),chatId:E().nullable(),status:E(),retryCount:Ve(),createdAt:E(),deliveredAt:E().nullable(),ackedAt:E().nullable()});VO.extend({message:IO});ne({limit:lc().int().min(1).max(50).default(10)});const YO={ADMIN:"admin",MEMBER:"member"},lm=Xe(["admin","member"]),KO=ne({id:E(),userId:E(),organizationId:E(),agentId:E(),role:lm,createdAt:E()});ne({username:E().min(1).max(100),displayName:E().min(1).max(200),role:lm.default("member")});ne({role:lm.optional()});KO.extend({username:E(),displayName:E(),password:E()});const PO=Xe(["agent_error","session_error","agent_needs_decision","agent_blocked","agent_stale","agent_disconnected","agent_connected","session_completed"]),Y0=Xe(["high","medium","low"]);ne({id:E(),organizationId:E(),type:PO,severity:Y0,agentId:E().nullable(),chatId:E().nullable(),message:E(),read:ac(),createdAt:E()});ne({limit:lc().int().min(1).max(100).default(20),cursor:E().optional(),severity:Y0.optional(),read:Xe(["true","false"]).transform(t=>t==="true").optional(),agentId:E().optional()});const K0=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;ne({name:E().min(2).max(50).regex(/^[a-z0-9][a-z0-9-]*$/,"Must start with a letter or digit and contain only lowercase alphanumeric and hyphens").refine(t=>!K0.test(t),"Name must not be a UUID format"),displayName:E().min(1).max(200),maxAgents:Ve().int().min(0).default(0),maxMessagesPerMinute:Ve().int().min(0).default(0),features:Ot(E(),it()).default({})});ne({name:E().min(2).max(50).regex(/^[a-z0-9][a-z0-9-]*$/,"Must start with a letter or digit and contain only lowercase alphanumeric and hyphens").refine(t=>!K0.test(t),"Name must not be a UUID format").optional(),displayName:E().min(1).max(200).optional(),maxAgents:Ve().int().min(0).optional(),maxMessagesPerMinute:Ve().int().min(0).optional(),features:Ot(E(),it()).optional()});ne({id:E(),name:E(),displayName:E(),maxAgents:Ve(),maxMessagesPerMinute:Ve(),features:Ot(E(),it()),createdAt:E(),updatedAt:E()});ne({id:E(),agentId:E(),chatId:E(),content:E(),updatedAt:E()});ne({agentId:E(),chatId:E(),content:E().max(5e4)});const FO=ne({organizationId:E(),agentCount:Ve(),chatCount:Ve(),messageCount:Ve()});ne({totalAgents:Ve(),totalChats:Ve(),totalMessages:Ve(),byOrganization:ea(FO)});ne({key:E(),value:it(),updatedAt:E()});Ot(E(),it());const Aa={INBOX_TIMEOUT_SECONDS:"inbox_timeout_seconds",MAX_RETRY_COUNT:"max_retry_count",POLLING_INTERVAL_SECONDS:"polling_interval_seconds",PRESENCE_CLEANUP_SECONDS:"presence_cleanup_seconds"},$f={[Aa.INBOX_TIMEOUT_SECONDS]:300,[Aa.MAX_RETRY_COUNT]:3,[Aa.POLLING_INTERVAL_SECONDS]:5,[Aa.PRESENCE_CLEANUP_SECONDS]:60},Hi=Xe(["pending","assigned","working","completed","failed","cancelled"]),pb=Xe(["agent","admin"]),XO=Xe(["assigned","status_changed","cancelled"]);ne({taskId:E(),event:XO,title:E(),body:E().default(""),status:Hi,fromStatus:Hi.optional(),originRef:E().nullable().optional()});const JO=ne({title:E().min(1).max(500),body:E().optional(),assigneeAgentId:E().optional(),originRef:E().max(500).optional(),metadata:Ot(E(),it()).optional()});JO.extend({organizationId:E().optional()});ne({status:Xe(["working","completed","failed"]),result:E().optional()});ne({assigneeAgentId:E().nullable().optional(),status:Hi.optional(),result:E().optional()});ne({chatId:E().min(1)});const WO=ne({id:E(),organizationId:E(),title:E(),body:E(),status:Hi,assigneeAgentId:E().nullable(),createdByType:pb,createdById:E(),originRef:E().nullable(),result:E().nullable(),metadata:Ot(E(),it()),createdAt:E(),updatedAt:E(),cancelledAt:E().nullable(),cancelledByType:pb.nullable(),cancelledById:E().nullable()}),eR=ne({taskId:E(),chatId:E(),linkedByAgentId:E().nullable(),linkedAt:E()});WO.extend({chats:ea(eR)});ne({status:Hi.optional(),assigneeAgentId:E().optional(),originRef:E().optional(),limit:lc().int().min(1).max(100).default(20),cursor:E().optional()});const tR=Xe(["normal","idle_island","awaiting_reply","no_chat","not_applicable"]);ne({taskId:E(),signal:tR,reason:E()});const nR=Xe(["active","suspended"]);ne({id:E(),username:E(),displayName:E(),avatarUrl:E().nullable(),status:nR,createdAt:E(),updatedAt:E()});ne({username:E().min(1).max(100),displayName:E().min(1).max(200),password:E().min(8).max(200)});ne({displayName:E().min(1).max(200).optional(),password:E().min(8).max(200).optional()});ne({type:rc("auth"),token:E().min(1)});function sm(){return we.get("/members")}function aR(t){return we.post("/members",t)}function rR(t){return we.delete(`/members/${encodeURIComponent(t)}`)}function _r(t,a,{checkForDefaultPrevented:l=!0}={}){return function(o){if(t==null||t(o),l===!1||!o.defaultPrevented)return a==null?void 0:a(o)}}function lR(t,a){const l=y.createContext(a),s=d=>{const{children:h,...m}=d,g=y.useMemo(()=>m,Object.values(m));return u.jsx(l.Provider,{value:g,children:h})};s.displayName=t+"Provider";function o(d){const h=y.useContext(l);if(h)return h;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${t}\``)}return[s,o]}function sR(t,a=[]){let l=[];function s(d,h){const m=y.createContext(h),g=l.length;l=[...l,h];const p=b=>{var R;const{scope:j,children:w,...C}=b,N=((R=j==null?void 0:j[t])==null?void 0:R[g])||m,_=y.useMemo(()=>C,Object.values(C));return u.jsx(N.Provider,{value:_,children:w})};p.displayName=d+"Provider";function x(b,j){var N;const w=((N=j==null?void 0:j[t])==null?void 0:N[g])||m,C=y.useContext(w);if(C)return C;if(h!==void 0)return h;throw new Error(`\`${b}\` must be used within \`${d}\``)}return[p,x]}const o=()=>{const d=l.map(h=>y.createContext(h));return function(m){const g=(m==null?void 0:m[t])||d;return y.useMemo(()=>({[`__scope${t}`]:{...m,[t]:g}}),[m,g])}};return o.scopeName=t,[s,iR(o,...a)]}function iR(...t){const a=t[0];if(t.length===1)return a;const l=()=>{const s=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(d){const h=s.reduce((m,{useScope:g,scopeName:p})=>{const b=g(d)[`__scope${p}`];return{...m,...b}},{});return y.useMemo(()=>({[`__scope${a.scopeName}`]:h}),[h])}};return l.scopeName=a.scopeName,l}var Qi=globalThis!=null&&globalThis.document?y.useLayoutEffect:()=>{},oR=Ch[" useId ".trim().toString()]||(()=>{}),uR=0;function Hf(t){const[a,l]=y.useState(oR());return Qi(()=>{l(s=>s??String(uR++))},[t]),t||(a?`radix-${a}`:"")}var cR=Ch[" useInsertionEffect ".trim().toString()]||Qi;function dR({prop:t,defaultProp:a,onChange:l=()=>{},caller:s}){const[o,d,h]=fR({defaultProp:a,onChange:l}),m=t!==void 0,g=m?t:o;{const x=y.useRef(t!==void 0);y.useEffect(()=>{const b=x.current;b!==m&&console.warn(`${s} is changing from ${b?"controlled":"uncontrolled"} to ${m?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),x.current=m},[m,s])}const p=y.useCallback(x=>{var b;if(m){const j=hR(x)?x(t):x;j!==t&&((b=h.current)==null||b.call(h,j))}else d(x)},[m,t,d,h]);return[g,p]}function fR({defaultProp:t,onChange:a}){const[l,s]=y.useState(t),o=y.useRef(l),d=y.useRef(a);return cR(()=>{d.current=a},[a]),y.useEffect(()=>{var h;o.current!==l&&((h=d.current)==null||h.call(d,l),o.current=l)},[l,o]),[l,s,d]}function hR(t){return typeof t=="function"}var P0=Yb();const mR=Vb(P0);function F0(t){const a=pR(t),l=y.forwardRef((s,o)=>{const{children:d,...h}=s,m=y.Children.toArray(d),g=m.find(vR);if(g){const p=g.props.children,x=m.map(b=>b===g?y.Children.count(p)>1?y.Children.only(null):y.isValidElement(p)?p.props.children:null:b);return u.jsx(a,{...h,ref:o,children:y.isValidElement(p)?y.cloneElement(p,void 0,x):null})}return u.jsx(a,{...h,ref:o,children:d})});return l.displayName=`${t}.Slot`,l}function pR(t){const a=y.forwardRef((l,s)=>{const{children:o,...d}=l;if(y.isValidElement(o)){const h=bR(o),m=yR(d,o.props);return o.type!==y.Fragment&&(m.ref=s?Vh(s,h):h),y.cloneElement(o,m)}return y.Children.count(o)>1?y.Children.only(null):null});return a.displayName=`${t}.SlotClone`,a}var gR=Symbol("radix.slottable");function vR(t){return y.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===gR}function yR(t,a){const l={...a};for(const s in a){const o=t[s],d=a[s];/^on[A-Z]/.test(s)?o&&d?l[s]=(...m)=>{const g=d(...m);return o(...m),g}:o&&(l[s]=o):s==="style"?l[s]={...o,...d}:s==="className"&&(l[s]=[o,d].filter(Boolean).join(" "))}return{...t,...l}}function bR(t){var s,o;let a=(s=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:s.get,l=a&&"isReactWarning"in a&&a.isReactWarning;return l?t.ref:(a=(o=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:o.get,l=a&&"isReactWarning"in a&&a.isReactWarning,l?t.props.ref:t.props.ref||t.ref)}var xR=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ka=xR.reduce((t,a)=>{const l=F0(`Primitive.${a}`),s=y.forwardRef((o,d)=>{const{asChild:h,...m}=o,g=h?l:a;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(g,{...m,ref:d})});return s.displayName=`Primitive.${a}`,{...t,[a]:s}},{});function SR(t,a){t&&P0.flushSync(()=>t.dispatchEvent(a))}function Gi(t){const a=y.useRef(t);return y.useEffect(()=>{a.current=t}),y.useMemo(()=>(...l)=>{var s;return(s=a.current)==null?void 0:s.call(a,...l)},[])}function jR(t,a=globalThis==null?void 0:globalThis.document){const l=Gi(t);y.useEffect(()=>{const s=o=>{o.key==="Escape"&&l(o)};return a.addEventListener("keydown",s,{capture:!0}),()=>a.removeEventListener("keydown",s,{capture:!0})},[l,a])}var NR="DismissableLayer",Nh="dismissableLayer.update",wR="dismissableLayer.pointerDownOutside",_R="dismissableLayer.focusOutside",gb,X0=y.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),J0=y.forwardRef((t,a)=>{const{disableOutsidePointerEvents:l=!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:d,onInteractOutside:h,onDismiss:m,...g}=t,p=y.useContext(X0),[x,b]=y.useState(null),j=(x==null?void 0:x.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,w]=y.useState({}),C=pl(a,K=>b(K)),N=Array.from(p.layers),[_]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),R=N.indexOf(_),Q=x?N.indexOf(x):-1,q=p.layersWithOutsidePointerEventsDisabled.size>0,B=Q>=R,F=AR(K=>{const k=K.target,ee=[...p.branches].some(be=>be.contains(k));!B||ee||(o==null||o(K),h==null||h(K),K.defaultPrevented||m==null||m())},j),J=TR(K=>{const k=K.target;[...p.branches].some(be=>be.contains(k))||(d==null||d(K),h==null||h(K),K.defaultPrevented||m==null||m())},j);return jR(K=>{Q===p.layers.size-1&&(s==null||s(K),!K.defaultPrevented&&m&&(K.preventDefault(),m()))},j),y.useEffect(()=>{if(x)return l&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(gb=j.body.style.pointerEvents,j.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(x)),p.layers.add(x),vb(),()=>{l&&p.layersWithOutsidePointerEventsDisabled.size===1&&(j.body.style.pointerEvents=gb)}},[x,j,l,p]),y.useEffect(()=>()=>{x&&(p.layers.delete(x),p.layersWithOutsidePointerEventsDisabled.delete(x),vb())},[x,p]),y.useEffect(()=>{const K=()=>w({});return document.addEventListener(Nh,K),()=>document.removeEventListener(Nh,K)},[]),u.jsx(ka.div,{...g,ref:C,style:{pointerEvents:q?B?"auto":"none":void 0,...t.style},onFocusCapture:_r(t.onFocusCapture,J.onFocusCapture),onBlurCapture:_r(t.onBlurCapture,J.onBlurCapture),onPointerDownCapture:_r(t.onPointerDownCapture,F.onPointerDownCapture)})});J0.displayName=NR;var ER="DismissableLayerBranch",CR=y.forwardRef((t,a)=>{const l=y.useContext(X0),s=y.useRef(null),o=pl(a,s);return y.useEffect(()=>{const d=s.current;if(d)return l.branches.add(d),()=>{l.branches.delete(d)}},[l.branches]),u.jsx(ka.div,{...t,ref:o})});CR.displayName=ER;function AR(t,a=globalThis==null?void 0:globalThis.document){const l=Gi(t),s=y.useRef(!1),o=y.useRef(()=>{});return y.useEffect(()=>{const d=m=>{if(m.target&&!s.current){let g=function(){W0(wR,l,p,{discrete:!0})};const p={originalEvent:m};m.pointerType==="touch"?(a.removeEventListener("click",o.current),o.current=g,a.addEventListener("click",o.current,{once:!0})):g()}else a.removeEventListener("click",o.current);s.current=!1},h=window.setTimeout(()=>{a.addEventListener("pointerdown",d)},0);return()=>{window.clearTimeout(h),a.removeEventListener("pointerdown",d),a.removeEventListener("click",o.current)}},[a,l]),{onPointerDownCapture:()=>s.current=!0}}function TR(t,a=globalThis==null?void 0:globalThis.document){const l=Gi(t),s=y.useRef(!1);return y.useEffect(()=>{const o=d=>{d.target&&!s.current&&W0(_R,l,{originalEvent:d},{discrete:!1})};return a.addEventListener("focusin",o),()=>a.removeEventListener("focusin",o)},[a,l]),{onFocusCapture:()=>s.current=!0,onBlurCapture:()=>s.current=!1}}function vb(){const t=new CustomEvent(Nh);document.dispatchEvent(t)}function W0(t,a,l,{discrete:s}){const o=l.originalEvent.target,d=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:l});a&&o.addEventListener(t,a,{once:!0}),s?SR(o,d):o.dispatchEvent(d)}var Qf="focusScope.autoFocusOnMount",Gf="focusScope.autoFocusOnUnmount",yb={bubbles:!1,cancelable:!0},zR="FocusScope",eS=y.forwardRef((t,a)=>{const{loop:l=!1,trapped:s=!1,onMountAutoFocus:o,onUnmountAutoFocus:d,...h}=t,[m,g]=y.useState(null),p=Gi(o),x=Gi(d),b=y.useRef(null),j=pl(a,N=>g(N)),w=y.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;y.useEffect(()=>{if(s){let N=function(q){if(w.paused||!m)return;const B=q.target;m.contains(B)?b.current=B:mr(b.current,{select:!0})},_=function(q){if(w.paused||!m)return;const B=q.relatedTarget;B!==null&&(m.contains(B)||mr(b.current,{select:!0}))},R=function(q){if(document.activeElement===document.body)for(const F of q)F.removedNodes.length>0&&mr(m)};document.addEventListener("focusin",N),document.addEventListener("focusout",_);const Q=new MutationObserver(R);return m&&Q.observe(m,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",N),document.removeEventListener("focusout",_),Q.disconnect()}}},[s,m,w.paused]),y.useEffect(()=>{if(m){xb.add(w);const N=document.activeElement;if(!m.contains(N)){const R=new CustomEvent(Qf,yb);m.addEventListener(Qf,p),m.dispatchEvent(R),R.defaultPrevented||(OR(UR(tS(m)),{select:!0}),document.activeElement===N&&mr(m))}return()=>{m.removeEventListener(Qf,p),setTimeout(()=>{const R=new CustomEvent(Gf,yb);m.addEventListener(Gf,x),m.dispatchEvent(R),R.defaultPrevented||mr(N??document.body,{select:!0}),m.removeEventListener(Gf,x),xb.remove(w)},0)}}},[m,p,x,w]);const C=y.useCallback(N=>{if(!l&&!s||w.paused)return;const _=N.key==="Tab"&&!N.altKey&&!N.ctrlKey&&!N.metaKey,R=document.activeElement;if(_&&R){const Q=N.currentTarget,[q,B]=RR(Q);q&&B?!N.shiftKey&&R===B?(N.preventDefault(),l&&mr(q,{select:!0})):N.shiftKey&&R===q&&(N.preventDefault(),l&&mr(B,{select:!0})):R===Q&&N.preventDefault()}},[l,s,w.paused]);return u.jsx(ka.div,{tabIndex:-1,...h,ref:j,onKeyDown:C})});eS.displayName=zR;function OR(t,{select:a=!1}={}){const l=document.activeElement;for(const s of t)if(mr(s,{select:a}),document.activeElement!==l)return}function RR(t){const a=tS(t),l=bb(a,t),s=bb(a.reverse(),t);return[l,s]}function tS(t){const a=[],l=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:s=>{const o=s.tagName==="INPUT"&&s.type==="hidden";return s.disabled||s.hidden||o?NodeFilter.FILTER_SKIP:s.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;l.nextNode();)a.push(l.currentNode);return a}function bb(t,a){for(const l of t)if(!MR(l,{upTo:a}))return l}function MR(t,{upTo:a}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(a!==void 0&&t===a)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function kR(t){return t instanceof HTMLInputElement&&"select"in t}function mr(t,{select:a=!1}={}){if(t&&t.focus){const l=document.activeElement;t.focus({preventScroll:!0}),t!==l&&kR(t)&&a&&t.select()}}var xb=DR();function DR(){let t=[];return{add(a){const l=t[0];a!==l&&(l==null||l.pause()),t=Sb(t,a),t.unshift(a)},remove(a){var l;t=Sb(t,a),(l=t[0])==null||l.resume()}}}function Sb(t,a){const l=[...t],s=l.indexOf(a);return s!==-1&&l.splice(s,1),l}function UR(t){return t.filter(a=>a.tagName!=="A")}var LR="Portal",nS=y.forwardRef((t,a)=>{var m;const{container:l,...s}=t,[o,d]=y.useState(!1);Qi(()=>d(!0),[]);const h=l||o&&((m=globalThis==null?void 0:globalThis.document)==null?void 0:m.body);return h?mR.createPortal(u.jsx(ka.div,{...s,ref:a}),h):null});nS.displayName=LR;function ZR(t,a){return y.useReducer((l,s)=>a[l][s]??l,t)}var sc=t=>{const{present:a,children:l}=t,s=qR(a),o=typeof l=="function"?l({present:s.isPresent}):y.Children.only(l),d=pl(s.ref,BR(o));return typeof l=="function"||s.isPresent?y.cloneElement(o,{ref:d}):null};sc.displayName="Presence";function qR(t){const[a,l]=y.useState(),s=y.useRef(null),o=y.useRef(t),d=y.useRef("none"),h=t?"mounted":"unmounted",[m,g]=ZR(h,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return y.useEffect(()=>{const p=Tu(s.current);d.current=m==="mounted"?p:"none"},[m]),Qi(()=>{const p=s.current,x=o.current;if(x!==t){const j=d.current,w=Tu(p);t?g("MOUNT"):w==="none"||(p==null?void 0:p.display)==="none"?g("UNMOUNT"):g(x&&j!==w?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,g]),Qi(()=>{if(a){let p;const x=a.ownerDocument.defaultView??window,b=w=>{const N=Tu(s.current).includes(CSS.escape(w.animationName));if(w.target===a&&N&&(g("ANIMATION_END"),!o.current)){const _=a.style.animationFillMode;a.style.animationFillMode="forwards",p=x.setTimeout(()=>{a.style.animationFillMode==="forwards"&&(a.style.animationFillMode=_)})}},j=w=>{w.target===a&&(d.current=Tu(s.current))};return a.addEventListener("animationstart",j),a.addEventListener("animationcancel",b),a.addEventListener("animationend",b),()=>{x.clearTimeout(p),a.removeEventListener("animationstart",j),a.removeEventListener("animationcancel",b),a.removeEventListener("animationend",b)}}else g("ANIMATION_END")},[a,g]),{isPresent:["mounted","unmountSuspended"].includes(m),ref:y.useCallback(p=>{s.current=p?getComputedStyle(p):null,l(p)},[])}}function Tu(t){return(t==null?void 0:t.animationName)||"none"}function BR(t){var s,o;let a=(s=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:s.get,l=a&&"isReactWarning"in a&&a.isReactWarning;return l?t.ref:(a=(o=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:o.get,l=a&&"isReactWarning"in a&&a.isReactWarning,l?t.props.ref:t.props.ref||t.ref)}var If=0;function $R(){y.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??jb()),document.body.insertAdjacentElement("beforeend",t[1]??jb()),If++,()=>{If===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(a=>a.remove()),If--}},[])}function jb(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var Jn=function(){return Jn=Object.assign||function(a){for(var l,s=1,o=arguments.length;s<o;s++){l=arguments[s];for(var d in l)Object.prototype.hasOwnProperty.call(l,d)&&(a[d]=l[d])}return a},Jn.apply(this,arguments)};function aS(t,a){var l={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&a.indexOf(s)<0&&(l[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,s=Object.getOwnPropertySymbols(t);o<s.length;o++)a.indexOf(s[o])<0&&Object.prototype.propertyIsEnumerable.call(t,s[o])&&(l[s[o]]=t[s[o]]);return l}function HR(t,a,l){if(l||arguments.length===2)for(var s=0,o=a.length,d;s<o;s++)(d||!(s in a))&&(d||(d=Array.prototype.slice.call(a,0,s)),d[s]=a[s]);return t.concat(d||Array.prototype.slice.call(a))}var Lu="right-scroll-bar-position",Zu="width-before-scroll-bar",QR="with-scroll-bars-hidden",GR="--removed-body-scroll-bar-size";function Vf(t,a){return typeof t=="function"?t(a):t&&(t.current=a),t}function IR(t,a){var l=y.useState(function(){return{value:t,callback:a,facade:{get current(){return l.value},set current(s){var o=l.value;o!==s&&(l.value=s,l.callback(s,o))}}}})[0];return l.callback=a,l.facade}var VR=typeof window<"u"?y.useLayoutEffect:y.useEffect,Nb=new WeakMap;function YR(t,a){var l=IR(null,function(s){return t.forEach(function(o){return Vf(o,s)})});return VR(function(){var s=Nb.get(l);if(s){var o=new Set(s),d=new Set(t),h=l.current;o.forEach(function(m){d.has(m)||Vf(m,null)}),d.forEach(function(m){o.has(m)||Vf(m,h)})}Nb.set(l,t)},[t]),l}function KR(t){return t}function PR(t,a){a===void 0&&(a=KR);var l=[],s=!1,o={read:function(){if(s)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return l.length?l[l.length-1]:t},useMedium:function(d){var h=a(d,s);return l.push(h),function(){l=l.filter(function(m){return m!==h})}},assignSyncMedium:function(d){for(s=!0;l.length;){var h=l;l=[],h.forEach(d)}l={push:function(m){return d(m)},filter:function(){return l}}},assignMedium:function(d){s=!0;var h=[];if(l.length){var m=l;l=[],m.forEach(d),h=l}var g=function(){var x=h;h=[],x.forEach(d)},p=function(){return Promise.resolve().then(g)};p(),l={push:function(x){h.push(x),p()},filter:function(x){return h=h.filter(x),l}}}};return o}function FR(t){t===void 0&&(t={});var a=PR(null);return a.options=Jn({async:!0,ssr:!1},t),a}var rS=function(t){var a=t.sideCar,l=aS(t,["sideCar"]);if(!a)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var s=a.read();if(!s)throw new Error("Sidecar medium not found");return y.createElement(s,Jn({},l))};rS.isSideCarExport=!0;function XR(t,a){return t.useMedium(a),rS}var lS=FR(),Yf=function(){},ic=y.forwardRef(function(t,a){var l=y.useRef(null),s=y.useState({onScrollCapture:Yf,onWheelCapture:Yf,onTouchMoveCapture:Yf}),o=s[0],d=s[1],h=t.forwardProps,m=t.children,g=t.className,p=t.removeScrollBar,x=t.enabled,b=t.shards,j=t.sideCar,w=t.noRelative,C=t.noIsolation,N=t.inert,_=t.allowPinchZoom,R=t.as,Q=R===void 0?"div":R,q=t.gapMode,B=aS(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),F=j,J=YR([l,a]),K=Jn(Jn({},B),o);return y.createElement(y.Fragment,null,x&&y.createElement(F,{sideCar:lS,removeScrollBar:p,shards:b,noRelative:w,noIsolation:C,inert:N,setCallbacks:d,allowPinchZoom:!!_,lockRef:l,gapMode:q}),h?y.cloneElement(y.Children.only(m),Jn(Jn({},K),{ref:J})):y.createElement(Q,Jn({},K,{className:g,ref:J}),m))});ic.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};ic.classNames={fullWidth:Zu,zeroRight:Lu};var JR=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function WR(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var a=JR();return a&&t.setAttribute("nonce",a),t}function eM(t,a){t.styleSheet?t.styleSheet.cssText=a:t.appendChild(document.createTextNode(a))}function tM(t){var a=document.head||document.getElementsByTagName("head")[0];a.appendChild(t)}var nM=function(){var t=0,a=null;return{add:function(l){t==0&&(a=WR())&&(eM(a,l),tM(a)),t++},remove:function(){t--,!t&&a&&(a.parentNode&&a.parentNode.removeChild(a),a=null)}}},aM=function(){var t=nM();return function(a,l){y.useEffect(function(){return t.add(a),function(){t.remove()}},[a&&l])}},sS=function(){var t=aM(),a=function(l){var s=l.styles,o=l.dynamic;return t(s,o),null};return a},rM={left:0,top:0,right:0,gap:0},Kf=function(t){return parseInt(t||"",10)||0},lM=function(t){var a=window.getComputedStyle(document.body),l=a[t==="padding"?"paddingLeft":"marginLeft"],s=a[t==="padding"?"paddingTop":"marginTop"],o=a[t==="padding"?"paddingRight":"marginRight"];return[Kf(l),Kf(s),Kf(o)]},sM=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return rM;var a=lM(t),l=document.documentElement.clientWidth,s=window.innerWidth;return{left:a[0],top:a[1],right:a[2],gap:Math.max(0,s-l+a[2]-a[0])}},iM=sS(),cs="data-scroll-locked",oM=function(t,a,l,s){var o=t.left,d=t.top,h=t.right,m=t.gap;return l===void 0&&(l="margin"),`
264
264
  .`.concat(QR,` {
265
265
  overflow: hidden `).concat(s,`;
266
266
  padding-right: `).concat(m,"px ").concat(s,`;
@@ -305,4 +305,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
305
305
  If you want to hide the \`${a.titleName}\`, you can wrap it with our VisuallyHidden component.
306
306
 
307
307
  For more information, see https://radix-ui.com/primitives/docs/components/${a.docsSlug}`;return y.useEffect(()=>{t&&(document.getElementById(t)||console.error(l))},[l,t]),null},DM="DialogDescriptionWarning",UM=({contentRef:t,descriptionId:a})=>{const s=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${CS(DM).contentName}}.`;return y.useEffect(()=>{var d;const o=(d=t.current)==null?void 0:d.getAttribute("aria-describedby");a&&o&&(document.getElementById(a)||console.warn(s))},[s,t,a]),null},LM=hS,ZM=pS,qM=vS,BM=yS,$M=bS,HM=SS,QM=NS,GM=_S;const Da=LM,IM=ZM,VM=qM,AS=y.forwardRef(({className:t,...a},l)=>u.jsx(BM,{ref:l,className:je("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...a}));AS.displayName="DialogOverlay";const na=y.forwardRef(({className:t,children:a,...l},s)=>u.jsxs(VM,{children:[u.jsx(AS,{}),u.jsxs($M,{ref:s,className:je("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] rounded-lg",t),...l,children:[a,u.jsxs(GM,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[u.jsx(pE,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));na.displayName="DialogContent";function Ua({className:t,...a}){return u.jsx("div",{className:je("flex flex-col space-y-1.5 text-center sm:text-left",t),...a})}function ta({className:t,...a}){return u.jsx("div",{className:je("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...a})}const aa=y.forwardRef(({className:t,...a},l)=>u.jsx(HM,{ref:l,className:je("text-lg font-semibold leading-none tracking-tight",t),...a}));aa.displayName="DialogTitle";const YM=y.forwardRef(({className:t,...a},l)=>u.jsx(QM,{ref:l,className:je("text-sm text-muted-foreground",t),...a}));YM.displayName="DialogDescription";const tt=y.forwardRef(({className:t,type:a,...l},s)=>u.jsx("input",{type:a,className:je("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",t),ref:s,...l}));tt.displayName="Input";var KM=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],PM=KM.reduce((t,a)=>{const l=i0(`Primitive.${a}`),s=y.forwardRef((o,d)=>{const{asChild:h,...m}=o,g=h?l:a;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(g,{...m,ref:d})});return s.displayName=`Primitive.${a}`,{...t,[a]:s}},{}),FM="Label",TS=y.forwardRef((t,a)=>u.jsx(PM.label,{...t,ref:a,onMouseDown:l=>{var o;l.target.closest("button, input, select, textarea")||((o=t.onMouseDown)==null||o.call(t,l),!l.defaultPrevented&&l.detail>1&&l.preventDefault())}}));TS.displayName=FM;var XM=TS;const $e=y.forwardRef(({className:t,...a},l)=>u.jsx(XM,{ref:l,className:je("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",t),...a}));$e.displayName="Label";const JM=Object.values(YO);function WM(){const t=Mn(),[a,l]=y.useState(!1),[s,o]=y.useState({username:"",displayName:"",role:"member"}),[d,h]=y.useState(null),{data:m,isLoading:g,error:p}=De({queryKey:["members"],queryFn:sm}),x=st({mutationFn:()=>aR({username:s.username,displayName:s.displayName,role:s.role}),onSuccess:N=>{t.invalidateQueries({queryKey:["members"]}),h(N.password)}}),b=st({mutationFn:rR,onSuccess:()=>t.invalidateQueries({queryKey:["members"]})});function j(){l(!1),o({username:"",displayName:"",role:"member"}),h(null)}function w(N){N.preventDefault(),x.mutate()}function C(N){window.confirm("Delete this member? Their human agent will also be deactivated.")&&b.mutate(N)}return u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between mb-6",children:[u.jsx("h1",{className:"text-2xl font-semibold",children:"Members"}),u.jsxs(Da,{open:a,onOpenChange:N=>N?l(!0):j(),children:[u.jsx(IM,{asChild:!0,children:u.jsxs(de,{children:[u.jsx(hl,{className:"h-4 w-4 mr-2"}),"Add Member"]})}),u.jsxs(na,{children:[u.jsx(Ua,{children:u.jsx(aa,{children:d?"Member Created":"Create Member"})}),d?u.jsxs("div",{className:"space-y-4",children:[u.jsx("p",{className:"text-sm text-muted-foreground",children:"Member created. Share the password below — it will only be shown once."}),u.jsxs("div",{className:"flex items-center gap-2 rounded-md border p-3 bg-muted",children:[u.jsx("code",{className:"flex-1 text-sm font-mono",children:d}),u.jsx(de,{variant:"ghost",size:"icon",onClick:()=>navigator.clipboard.writeText(d),title:"Copy password",children:u.jsx(Hh,{className:"h-4 w-4"})})]}),u.jsx(ta,{children:u.jsx(de,{onClick:j,children:"Done"})})]}):u.jsxs("form",{onSubmit:w,className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"member-username",children:"Username"}),u.jsx(tt,{id:"member-username",type:"text",value:s.username,onChange:N=>o({...s,username:N.target.value}),required:!0})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"member-name",children:"Display Name"}),u.jsx(tt,{id:"member-name",value:s.displayName,onChange:N=>o({...s,displayName:N.target.value}),required:!0})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"member-role",children:"Role"}),u.jsx("select",{id:"member-role",value:s.role,onChange:N=>o({...s,role:N.target.value}),className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:JM.map(N=>u.jsx("option",{value:N,children:N},N))})]}),x.error instanceof Error&&u.jsx("div",{className:"text-sm text-destructive",children:x.error.message}),u.jsx(ta,{children:u.jsx(de,{type:"submit",disabled:x.isPending,children:x.isPending?"Creating...":"Create"})})]})]})]})]}),u.jsx("div",{className:"border rounded-lg",children:u.jsxs(Oa,{children:[u.jsx(Ra,{children:u.jsxs(at,{children:[u.jsx(ye,{children:"Username"}),u.jsx(ye,{children:"Name"}),u.jsx(ye,{children:"Role"}),u.jsx(ye,{children:"Created"}),u.jsx(ye,{className:"w-16"})]})}),u.jsx(Ma,{children:g?u.jsx(at,{children:u.jsx(ve,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):p?u.jsx(at,{children:u.jsxs(ve,{colSpan:5,className:"text-center py-8 text-destructive",children:["Failed to load members: ",p instanceof Error?p.message:"Unknown error"]})}):(m==null?void 0:m.length)===0?u.jsx(at,{children:u.jsx(ve,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No members"})}):m==null?void 0:m.map(N=>u.jsxs(at,{children:[u.jsx(ve,{className:"font-medium",children:N.username}),u.jsx(ve,{children:N.displayName}),u.jsx(ve,{children:u.jsx($t,{variant:N.role==="admin"?"default":"secondary",children:N.role})}),u.jsx(ve,{className:"text-muted-foreground",children:un(N.createdAt)}),u.jsx(ve,{children:u.jsx(de,{variant:"ghost",size:"icon",onClick:()=>C(N.id),disabled:b.isPending,title:"Delete",children:u.jsx(Zi,{className:"h-4 w-4"})})})]},N.id))})]})})]})}function ek(){return we.get("/admin/system/config")}function tk(t){return we.patch("/admin/system/config",t)}const nk={[Aa.INBOX_TIMEOUT_SECONDS]:"Inbox Timeout (seconds)",[Aa.MAX_RETRY_COUNT]:"Max Retry Count",[Aa.POLLING_INTERVAL_SECONDS]:"Polling Interval (seconds)",[Aa.PRESENCE_CLEANUP_SECONDS]:"Presence Cleanup (seconds)"},Ab=Object.values(Aa);function ak(){const t=Mn(),{data:a,isLoading:l}=De({queryKey:["system-config"],queryFn:ek}),[s,o]=y.useState({}),[d,h]=y.useState(!1);y.useEffect(()=>{if(!a)return;const p={};for(const x of Ab){const b=a[x]??$f[x]??"";p[x]=String(b)}o(p)},[a]);const m=st({mutationFn:()=>{const p={};for(const[x,b]of Object.entries(s)){const j=b.trim();if(j==="")p[x]=$f[x]??0;else{const w=Number(j);p[x]=Number.isNaN(w)?j:w}}return tk(p)},onSuccess:()=>{t.invalidateQueries({queryKey:["system-config"]}),h(!0),setTimeout(()=>h(!1),2e3)}}),g=p=>{p.preventDefault(),m.mutate()};return l?u.jsx("div",{className:"text-muted-foreground",children:"Loading..."}):u.jsxs("div",{children:[u.jsx("h1",{className:"text-2xl font-semibold mb-6",children:"Settings"}),u.jsxs(cl,{children:[u.jsx(Ns,{children:u.jsx(ws,{children:"System Configuration"})}),u.jsx(dl,{children:u.jsxs("form",{onSubmit:g,className:"space-y-4",children:[Ab.map(p=>u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:p,children:nk[p]??p}),u.jsx(tt,{id:p,value:s[p]??"",onChange:x=>o({...s,[p]:x.target.value})}),u.jsxs("p",{className:"text-xs text-muted-foreground",children:["Default: ",String($f[p]??"—")]})]},p)),m.error instanceof Error&&u.jsx("div",{className:"text-sm text-destructive",children:m.error.message}),u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx(de,{type:"submit",disabled:m.isPending,children:m.isPending?"Saving...":"Save Changes"}),d&&u.jsx("span",{className:"text-sm text-green-600",children:"Saved!"})]})]})})]})]})}const Tb=[{key:"members",label:"Members"},{key:"clients",label:"Clients"},{key:"settings",label:"Settings"},{key:"bindings",label:"Bindings"}];function rk(){const t=Dn(),a=Ar(),l=t.hash.replace("#",""),s=Tb.some(d=>d.key===l)?l:"members",o=d=>{a({hash:d},{replace:!0})};return u.jsxs("div",{children:[u.jsx("h1",{className:"text-2xl font-semibold mb-4",children:"Admin"}),u.jsx("div",{className:"flex gap-1 border-b border-border mb-6",children:Tb.map(d=>u.jsx("button",{type:"button",onClick:()=>o(d.key),className:je("px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors",s===d.key?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:d.label},d.key))}),s==="members"&&u.jsx(WM,{}),s==="clients"&&u.jsx(q2,{}),s==="settings"&&u.jsx(ak,{}),s==="bindings"&&u.jsx(_2,{})]})}function lk(t){return we.get(`/admin/agents/${t}/config`)}function sk(t,a){return we.patch(`/admin/agents/${t}/config`,a)}function ik(t,a){return we.post(`/admin/agents/${t}/config/dry-run`,{payload:a})}function ok(t){return we.get(`/admin/agents/${t}/client-status`)}function uc(t,a){const l=new URLSearchParams;a!=null&&a.state&&l.set("state",a.state),a!=null&&a.runtimeState&&l.set("runtimeState",a.runtimeState);const s=l.toString();return we.get(`/admin/sessions/agents/${t}${s?`?${s}`:""}`)}function uk(t,a){return we.post(`/admin/sessions/agents/${t}/${a}/suspend`)}function ck(t,a){return we.post(`/admin/sessions/agents/${t}/${a}/resume`)}function dk(t,a){return we.post(`/admin/sessions/agents/${t}/${a}/terminate`)}function fk(t){const{agent:a}=t,[l,s]=y.useState(!1),o=a.displayName||a.name||a.uuid;return u.jsxs("section",{className:"rounded-md border border-red-200 bg-red-50/40",children:[u.jsxs("header",{className:"flex items-center gap-2 border-b border-red-200 px-4 py-2",children:[u.jsx(Lx,{className:"h-4 w-4 text-red-700"}),u.jsx("h3",{className:"text-sm font-medium text-red-800",children:"Danger Zone"})]}),u.jsxs("div",{className:"divide-y divide-red-200",children:[a.status==="active"?u.jsx(Ff,{title:"Suspend agent",body:"Pause all active sessions. You can reactivate later; tokens stay revoked until then.",action:u.jsx(de,{variant:"outline",size:"sm",onClick:t.onSuspend,disabled:t.suspendPending,children:t.suspendPending?"Suspending…":"Suspend"})}):u.jsx(Ff,{title:"Reactivate agent",body:"Resume sessions. Tokens must be recreated — they are not restored.",action:u.jsx(de,{variant:"outline",size:"sm",onClick:t.onReactivate,disabled:t.reactivatePending,children:t.reactivatePending?"Reactivating…":"Reactivate"})}),u.jsx(Ff,{title:"Delete agent",body:"Permanent. Configuration, bindings, tokens, and session history are all dropped.",action:u.jsxs(de,{variant:"destructive",size:"sm",onClick:()=>s(!0),disabled:t.deletePending,children:[u.jsx(Zi,{className:"h-3.5 w-3.5 mr-1.5"}),"Delete"]})})]}),u.jsx(hk,{open:l,onOpenChange:s,expected:o,onDelete:()=>{s(!1),t.onDelete()},deleting:t.deletePending})]})}function Ff(t){return u.jsxs("div",{className:"flex items-start justify-between gap-4 px-4 py-3 text-sm",children:[u.jsxs("div",{children:[u.jsx("p",{className:"font-medium text-red-900",children:t.title}),u.jsx("p",{className:"text-xs text-red-800/80",children:t.body})]}),u.jsx("div",{children:t.action})]})}function hk({open:t,onOpenChange:a,expected:l,onDelete:s,deleting:o}){const[d,h]=y.useState("");function m(g){g.preventDefault(),d===l&&s()}return u.jsx(Da,{open:t,onOpenChange:g=>{a(g),g||h("")},children:u.jsxs(na,{children:[u.jsx(Ua,{children:u.jsxs(aa,{children:['Delete "',l,'"?']})}),u.jsxs("form",{onSubmit:m,className:"space-y-4",children:[u.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action cannot be undone. Type ",u.jsx("span",{className:"font-mono font-medium text-gray-900",children:l})," ","to confirm."]}),u.jsx(tt,{value:d,onChange:g=>h(g.target.value),autoFocus:!0,placeholder:l,className:"font-mono"}),u.jsxs(ta,{children:[u.jsx(de,{type:"button",variant:"ghost",onClick:()=>a(!1),disabled:o,children:"Cancel"}),u.jsx(de,{type:"submit",variant:"destructive",disabled:d!==l||o,children:o?"Deleting…":"Delete"})]})]})]})})}const mk={unchanged:{label:"",tone:""},added:{label:"new",tone:"bg-green-100 text-green-900"},modified:{label:"changed",tone:"bg-amber-100 text-amber-900"},deleted:{label:"will be removed on save",tone:"bg-red-100 text-red-900"}};function cm({status:t,onEdit:a,onDelete:l,onUndo:s,children:o,disabled:d}){const h=mk[t],m=t==="deleted";return u.jsxs("div",{className:je("flex items-center gap-2 rounded border px-3 py-2 text-sm",m?"bg-red-50 border-red-200 text-red-900 line-through decoration-red-300":"bg-white"),children:[u.jsx("div",{className:"flex-1 min-w-0 flex items-center gap-2",children:o}),h.label&&u.jsx("span",{className:je("text-xs rounded px-1.5 py-0.5 whitespace-nowrap",h.tone),children:h.label}),!d&&(m?u.jsxs(de,{size:"sm",variant:"ghost",onClick:s,children:[u.jsx(dE,{className:"h-3.5 w-3.5 mr-1"}),"Undo"]}):u.jsx(pk,{onEdit:a,onDelete:l}))]})}function pk({onEdit:t,onDelete:a}){return u.jsxs("div",{className:"flex gap-1",children:[u.jsx(de,{size:"sm",variant:"ghost",onClick:t,title:"Edit",children:"Edit"}),u.jsxs(de,{size:"sm",variant:"ghost",onClick:a,title:"Delete",children:[u.jsx(Dx,{className:"sr-only h-3.5 w-3.5","aria-hidden":!0}),"Delete"]})]})}function gk(t){const[a,l]=y.useState(null),s=t.items.filter(o=>o.status!=="deleted").length;return u.jsxs("section",{className:"rounded-md border bg-white",children:[u.jsxs("header",{className:"flex items-center justify-between border-b px-4 py-2",children:[u.jsxs("h3",{className:"text-sm font-medium",children:["Environment Variables (",s,")"]}),!t.disabled&&u.jsxs(de,{size:"sm",variant:"outline",onClick:()=>l({mode:"add"}),children:[u.jsx(hl,{className:"h-3.5 w-3.5 mr-1.5"})," Add"]})]}),u.jsx("div",{className:"px-4 py-3 space-y-2",children:t.items.length===0?u.jsx("p",{className:"text-sm text-muted-foreground",children:"No environment variables."}):t.items.map(o=>u.jsxs(cm,{status:o.status,onEdit:()=>l({mode:"edit",key:o.key,initial:o.value}),onDelete:()=>t.onDelete(o.key),onUndo:()=>t.onUndoDelete(o.key),disabled:t.disabled,children:[u.jsx("span",{className:"font-mono font-medium",children:o.value.key}),u.jsx("span",{className:"font-mono text-xs text-muted-foreground truncate max-w-xs",children:o.value.sensitive?"••••••":o.value.value||u.jsx("em",{children:"(empty)"})}),o.value.sensitive&&u.jsx(V_,{className:"h-3 w-3 text-muted-foreground"})]},o.key))}),a&&u.jsx(vk,{open:!!a,onOpenChange:o=>!o&&l(null),initial:a.mode==="edit"?a.initial:null,forbiddenKeys:t.otherKeys(a.mode==="edit"?a.key:null),onSubmit:o=>{a.mode==="edit"?t.onUpdate(a.key,o):t.onAdd(o),l(null)}})]})}function vk({open:t,onOpenChange:a,initial:l,forbiddenKeys:s,onSubmit:o}){const[d,h]=y.useState((l==null?void 0:l.key)??""),[m,g]=y.useState(l!=null&&l.sensitive?"":(l==null?void 0:l.value)??""),[p,x]=y.useState((l==null?void 0:l.sensitive)??!1),[b,j]=y.useState(null);y.useEffect(()=>{t&&(h((l==null?void 0:l.key)??""),g(l!=null&&l.sensitive?"":(l==null?void 0:l.value)??""),x((l==null?void 0:l.sensitive)??!1),j(null))},[t,l]);function w(C){if(C.preventDefault(),!d.match(/^[A-Z][A-Z0-9_]*$/)){j("Key must match /^[A-Z][A-Z0-9_]*$/.");return}if(s.has(d)){j(`Another entry already uses key "${d}".`);return}let N=m;if(p&&(l!=null&&l.sensitive)&&!m&&(N=jh),!p&&!l&&!m){j("Value is required for non-sensitive entries.");return}o({key:d,value:N,sensitive:p})}return u.jsx(Da,{open:t,onOpenChange:a,children:u.jsxs(na,{children:[u.jsx(Ua,{children:u.jsx(aa,{children:l?"Edit environment variable":"Add environment variable"})}),u.jsxs("form",{onSubmit:w,className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"env-key",children:"Key"}),u.jsx(tt,{id:"env-key",value:d,onChange:C=>h(C.target.value.toUpperCase()),placeholder:"OPENAI_API_KEY",className:"font-mono",disabled:!!l}),l&&u.jsx("p",{className:"text-xs text-muted-foreground",children:"Key can't be renamed — delete and re-add."})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"env-value",children:"Value"}),u.jsx(tt,{id:"env-value",type:p?"password":"text",autoComplete:"new-password",value:m,onChange:C=>g(C.target.value),placeholder:l!=null&&l.sensitive?"Leave empty to keep existing value":p?"new secret":"value",className:"font-mono"})]}),u.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[u.jsx("input",{type:"checkbox",checked:p,onChange:C=>x(C.target.checked),className:"h-4 w-4",disabled:!!l&&l.sensitive}),"Mark as sensitive (encrypted at rest, never displayed again)"]}),u.jsx("p",{className:"text-xs text-muted-foreground",children:"Sensitive values cannot be viewed after saving. If you need to verify, save a new value."}),b&&u.jsx("p",{className:"text-sm text-destructive",children:b}),u.jsxs(ta,{children:[u.jsx(de,{type:"button",variant:"ghost",onClick:()=>a(!1),children:"Cancel"}),u.jsx(de,{type:"submit",children:l?"Done":"Add"})]})]})]})})}function yk(t){const[a,l]=y.useState(null),s=t.items.filter(o=>o.status!=="deleted").length;return u.jsxs("section",{className:"rounded-md border bg-white",children:[u.jsxs("header",{className:"flex items-center justify-between border-b px-4 py-2",children:[u.jsxs("h3",{className:"text-sm font-medium",children:["Git Repositories (",s,")"]}),!t.disabled&&u.jsxs(de,{size:"sm",variant:"outline",onClick:()=>l({mode:"add"}),children:[u.jsx(hl,{className:"h-3.5 w-3.5 mr-1.5"})," Add"]})]}),u.jsx("div",{className:"px-4 py-3 space-y-2",children:t.items.length===0?u.jsx("p",{className:"text-sm text-muted-foreground",children:"No Git repositories."}):t.items.map(o=>{const d=o.value.localPath??Yu(o.value.url);return u.jsxs(cm,{status:o.status,onEdit:()=>l({mode:"edit",key:o.key,initial:o.value}),onDelete:()=>t.onDelete(o.key),onUndo:()=>t.onUndoDelete(o.key),disabled:t.disabled,children:[u.jsx("span",{className:"font-mono text-xs",children:o.value.url}),o.value.ref&&u.jsxs("span",{className:"text-xs text-muted-foreground",children:["@ ",o.value.ref]}),u.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",d||"./"]})]},o.key)})}),a&&u.jsx(bk,{open:!!a,onOpenChange:o=>!o&&l(null),initial:a.mode==="edit"?a.initial:null,forbiddenPaths:t.otherPaths(a.mode==="edit"?a.key:null),onSubmit:o=>{a.mode==="edit"?t.onUpdate(a.key,o):t.onAdd(o),l(null)}})]})}function bk({open:t,onOpenChange:a,initial:l,forbiddenPaths:s,onSubmit:o}){const[d,h]=y.useState((l==null?void 0:l.url)??""),[m,g]=y.useState((l==null?void 0:l.ref)??""),[p,x]=y.useState((l==null?void 0:l.localPath)??""),[b,j]=y.useState(null);y.useEffect(()=>{t&&(h((l==null?void 0:l.url)??""),g((l==null?void 0:l.ref)??""),x((l==null?void 0:l.localPath)??""),j(null))},[t,l]);function w(C){C.preventDefault();const N=d.trim();if(!N){j("URL is required.");return}const _=p.trim()||Yu(N);if(_&&s.has(_)){j(`Another repo already occupies local path "${_}".`);return}const R={url:N,...m.trim()?{ref:m.trim()}:{},...p.trim()?{localPath:p.trim()}:{}};o(R)}return u.jsx(Da,{open:t,onOpenChange:a,children:u.jsxs(na,{children:[u.jsx(Ua,{children:u.jsx(aa,{children:l?"Edit Git repository":"Add Git repository"})}),u.jsxs("form",{onSubmit:w,className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"git-url",children:"URL"}),u.jsx(tt,{id:"git-url",value:d,onChange:C=>h(C.target.value),placeholder:"git@github.com:org/repo.git",className:"font-mono"})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"git-ref",children:"Ref (branch / tag / sha, optional)"}),u.jsx(tt,{id:"git-ref",value:m,onChange:C=>g(C.target.value),placeholder:"main",className:"font-mono"})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"git-path",children:"Local path (optional)"}),u.jsx(tt,{id:"git-path",value:p,onChange:C=>x(C.target.value),placeholder:Yu(d)||"repo-name",className:"font-mono"}),u.jsx("p",{className:"text-xs text-muted-foreground",children:"Relative to the session working directory. Leave empty to derive from the URL."})]}),b&&u.jsx("p",{className:"text-sm text-destructive",children:b}),u.jsxs(ta,{children:[u.jsx(de,{type:"button",variant:"ghost",onClick:()=>a(!1),children:"Cancel"}),u.jsx(de,{type:"submit",children:l?"Done":"Add"})]})]})]})})}function zS(){const{data:t}=De({queryKey:["members","name-map"],queryFn:sm,staleTime:3e4});return y.useMemo(()=>{const a=new Map;if(t)for(const l of t)a.set(l.id,l.displayName||l.username);return l=>l?a.get(l)??l:"—"},[t])}function xk({agent:t,onSave:a}){const[l,s]=y.useState(!1),o=Qn(),d=zS(),h=t.metadata,m=h==null?void 0:h.tree,g=typeof(m==null?void 0:m.role)=="string"?m.role:null,p=Array.isArray(m==null?void 0:m.domains)?(m==null?void 0:m.domains).filter(j=>typeof j=="string"):[],x=t.managerId?d(t.managerId):null,b=t.delegateMention?o(t.delegateMention):null;return u.jsxs("section",{className:"rounded-md border bg-white",children:[u.jsxs("header",{className:"flex items-center justify-between border-b px-4 py-2",children:[u.jsx("h2",{className:"text-sm font-medium",children:"Identity"}),t.status==="active"&&u.jsxs(de,{size:"sm",variant:"outline",onClick:()=>s(!0),children:[u.jsx(Ux,{className:"h-3.5 w-3.5 mr-1.5"})," Edit"]})]}),u.jsxs("div",{className:"px-4 py-3 text-sm space-y-1",children:[u.jsxs("div",{children:[u.jsx("span",{className:"font-mono",children:t.name??t.uuid}),u.jsx("span",{className:"mx-2 text-muted-foreground",children:"·"}),u.jsx("span",{children:t.displayName??u.jsx("span",{className:"text-muted-foreground italic",children:"no display name"})}),b&&u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"mx-2 text-muted-foreground",children:"·"}),u.jsxs("span",{className:"text-muted-foreground",children:["delegate ",u.jsx("span",{className:"font-mono",children:b})]})]})]}),u.jsxs("div",{className:"text-xs text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1",children:[u.jsxs("span",{children:["owner ",u.jsx("span",{className:"text-gray-900",children:x??"—"})]}),g&&u.jsxs("span",{children:["role ",u.jsx("span",{className:"text-gray-900",children:g})]}),u.jsxs("span",{children:["type ",u.jsx($t,{variant:"secondary",children:t.type})]}),p.length>0&&u.jsxs("span",{children:["domains"," ",u.jsx("span",{className:"inline-flex flex-wrap gap-1 align-middle",children:p.map(j=>u.jsx($t,{variant:"outline",children:j},j))})]})]})]}),u.jsx(Sk,{agent:t,open:l,onOpenChange:s,onSave:a})]})}function Sk({agent:t,open:a,onOpenChange:l,onSave:s}){var N;const[o,d]=y.useState(t.displayName??""),[h,m]=y.useState(t.delegateMention??""),[g,p]=y.useState(!1),[x,b]=y.useState(null);y.useEffect(()=>{a&&(d(t.displayName??""),m(t.delegateMention??""),b(null))},[a,t]);const j=t.type==="human",w=De({queryKey:["agents-for-delegate"],queryFn:async()=>(await Ju({limit:100})).items.filter(R=>R.type==="personal_assistant"&&R.status==="active"),enabled:a&&j});async function C(_){_.preventDefault(),b(null),p(!0);try{await s({displayName:o||null,delegateMention:h||null}),l(!1)}catch(R){b(R instanceof Error?R.message:String(R))}finally{p(!1)}}return u.jsx(Da,{open:a,onOpenChange:l,children:u.jsxs(na,{children:[u.jsx(Ua,{children:u.jsx(aa,{children:"Edit Identity"})}),u.jsxs("form",{onSubmit:C,className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{children:"Name (mention)"}),u.jsx(tt,{value:t.name??"",disabled:!0,className:"font-mono"}),u.jsx("p",{className:"text-xs text-muted-foreground",children:"Name is permanent after creation."})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"id-display",children:"Display Name"}),u.jsx(tt,{id:"id-display",value:o,onChange:_=>d(_.target.value),placeholder:"How teammates see this agent",maxLength:200})]}),j&&u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"id-delegate",children:"Delegate Mention"}),u.jsxs("select",{id:"id-delegate",value:h,onChange:_=>m(_.target.value),className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:[u.jsx("option",{value:"",children:"None"}),(N=w.data)==null?void 0:N.map(_=>u.jsx("option",{value:_.uuid,children:_.displayName?`${_.displayName} (${_.name??_.uuid})`:_.name??_.uuid},_.uuid))]}),u.jsx("p",{className:"text-xs text-muted-foreground",children:"Assistant that acts on behalf of this agent."})]}),x&&u.jsx("p",{className:"text-sm text-destructive",children:x}),u.jsxs(ta,{children:[u.jsx(de,{type:"button",variant:"ghost",onClick:()=>l(!1),disabled:g,children:"Cancel"}),u.jsx(de,{type:"submit",disabled:g,children:g?"Saving…":"Save"})]})]})]})})}function jk(t){const[a,l]=y.useState(null),s=t.items.filter(o=>o.status!=="deleted").length;return u.jsxs("section",{className:"rounded-md border bg-white",children:[u.jsxs("header",{className:"flex items-center justify-between border-b px-4 py-2",children:[u.jsxs("h3",{className:"text-sm font-medium",children:["MCP Servers (",s,")"]}),!t.disabled&&u.jsxs(de,{size:"sm",variant:"outline",onClick:()=>l({mode:"add"}),children:[u.jsx(hl,{className:"h-3.5 w-3.5 mr-1.5"})," Add"]})]}),u.jsx("div",{className:"px-4 py-3 space-y-2",children:t.items.length===0?u.jsx("p",{className:"text-sm text-muted-foreground",children:"No MCP servers. Add one to extend the agent's tools."}):t.items.map(o=>u.jsxs(cm,{status:o.status,onEdit:()=>l({mode:"edit",key:o.key,initial:o.value}),onDelete:()=>t.onDelete(o.key),onUndo:()=>t.onUndoDelete(o.key),disabled:t.disabled,children:[u.jsx("span",{className:"text-xs rounded bg-gray-100 px-1.5 py-0.5 font-mono",children:o.value.transport}),u.jsx("span",{className:"font-medium font-mono",children:o.value.name}),u.jsx("span",{className:"text-xs text-muted-foreground truncate",children:Nk(o.value)})]},o.key))}),a&&u.jsx(wk,{open:!!a,onOpenChange:o=>!o&&l(null),initial:a.mode==="edit"?a.initial:null,forbiddenNames:t.otherNames(a.mode==="edit"?a.key:null),onSubmit:o=>{a.mode==="edit"?t.onUpdate(a.key,o):t.onAdd(o),l(null)}})]})}function Nk(t){var a;if(t.transport==="stdio"){const l=(a=t.args)!=null&&a.length?` ${t.args.join(" ")}`:"";return`${t.command}${l}`}return t.url}function wk({open:t,onOpenChange:a,initial:l,forbiddenNames:s,onSubmit:o}){const[d,h]=y.useState((l==null?void 0:l.transport)??"stdio"),[m,g]=y.useState((l==null?void 0:l.name)??""),[p,x]=y.useState((l==null?void 0:l.transport)==="stdio"?l.command:""),[b,j]=y.useState((l==null?void 0:l.transport)==="stdio"&&l.args?l.args.join(" "):""),[w,C]=y.useState(l&&(l.transport==="http"||l.transport==="sse")?l.url:""),[N,_]=y.useState(null);y.useEffect(()=>{t&&(h((l==null?void 0:l.transport)??"stdio"),g((l==null?void 0:l.name)??""),x((l==null?void 0:l.transport)==="stdio"?l.command:""),j((l==null?void 0:l.transport)==="stdio"&&l.args?l.args.join(" "):""),C(l&&(l.transport==="http"||l.transport==="sse")?l.url:""),_(null))},[t,l]);function R(Q){if(Q.preventDefault(),!m.match(/^[a-z0-9][a-z0-9_-]{0,63}$/i)){_("Name must start alphanumeric and contain only a-z0-9_-.");return}if(s.has(m.toLowerCase())){_(`Another MCP server is already named "${m}".`);return}let q;if(d==="stdio"){if(!p.trim()){_("stdio transport requires a command.");return}const B=b.trim().split(/\s+/).filter(F=>F.length>0);q={name:m,transport:"stdio",command:p.trim(),...B.length?{args:B}:{}}}else{const B=w.trim();try{new URL(B)}catch{_("URL is not valid.");return}q={name:m,transport:d,url:B}}o(q)}return u.jsx(Da,{open:t,onOpenChange:a,children:u.jsxs(na,{children:[u.jsx(Ua,{children:u.jsx(aa,{children:l?"Edit MCP server":"Add MCP server"})}),u.jsxs("form",{onSubmit:R,className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"mcp-transport",children:"Transport"}),u.jsxs("select",{id:"mcp-transport",value:d,onChange:Q=>h(Q.target.value),className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:[u.jsx("option",{value:"stdio",children:"stdio (local subprocess)"}),u.jsx("option",{value:"http",children:"http"}),u.jsx("option",{value:"sse",children:"sse"})]})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"mcp-name",children:"Name"}),u.jsx(tt,{id:"mcp-name",value:m,onChange:Q=>g(Q.target.value),placeholder:"playwright",className:"font-mono"})]}),d==="stdio"?u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"mcp-command",children:"Command"}),u.jsx(tt,{id:"mcp-command",value:p,onChange:Q=>x(Q.target.value),placeholder:"/usr/local/bin/playwright-mcp",className:"font-mono"})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"mcp-args",children:"Args (space-separated, optional)"}),u.jsx(tt,{id:"mcp-args",value:b,onChange:Q=>j(Q.target.value),placeholder:"--port 3000",className:"font-mono"})]})]}):u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"mcp-url",children:"URL"}),u.jsx(tt,{id:"mcp-url",value:w,onChange:Q=>C(Q.target.value),placeholder:"https://internal.api/mcp",className:"font-mono"})]}),N&&u.jsx("p",{className:"text-sm text-destructive",children:N}),u.jsxs(ta,{children:[u.jsx(de,{type:"button",variant:"ghost",onClick:()=>a(!1),children:"Cancel"}),u.jsx(de,{type:"submit",children:l?"Done":"Add"})]})]})]})})}const zb=[{value:"claude-opus-4-6",label:"claude-opus-4-6",hint:"most capable"},{value:"claude-sonnet-4-6",label:"claude-sonnet-4-6",hint:"default"},{value:"claude-haiku-4-5",label:"claude-haiku-4-5",hint:"fastest"}];function _k({value:t,baseline:a,onChange:l,onRevert:s,disabled:o}){const d=t!==a,h=!zb.some(m=>m.value===t)&&t!=="";return u.jsxs("section",{className:`rounded-md border bg-white ${d?"border-amber-300":"border-gray-200"}`,children:[u.jsxs("header",{className:"flex items-center justify-between border-b px-4 py-2",children:[u.jsxs("h3",{className:"text-sm font-medium flex items-center gap-2",children:["Model",d&&u.jsx("span",{className:"text-xs rounded bg-amber-100 px-1.5 py-0.5 text-amber-900",children:"changed"})]}),d&&u.jsx(de,{size:"sm",variant:"ghost",onClick:s,disabled:o,children:"Revert"})]}),u.jsxs("div",{className:"px-4 py-3 space-y-2",children:[u.jsxs("select",{value:t,onChange:m=>l(m.target.value),disabled:o,className:"flex h-9 w-full max-w-md rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50",children:[u.jsx("option",{value:"",children:"(agent default)"}),zb.map(m=>u.jsxs("option",{value:m.value,children:[m.label,m.hint?` — ${m.hint}`:""]},m.value)),h&&u.jsxs("option",{value:t,children:[t," — custom"]})]}),u.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose which Claude model powers this agent. Applies to new sessions immediately; active sessions switch on their next message."})]})]})}function Ek({value:t,baseline:a,onChange:l,onRevert:s,disabled:o}){const[d,h]=y.useState(!1),m=y.useRef(null),g=t!==a;return y.useEffect(()=>{var p;d&&((p=m.current)==null||p.focus())},[d]),u.jsxs("section",{className:`rounded-md border bg-white ${g?"border-amber-300":"border-gray-200"}`,children:[u.jsxs("header",{className:"flex items-center justify-between border-b px-4 py-2",children:[u.jsxs("h3",{className:"text-sm font-medium flex items-center gap-2",children:["System Prompt Append",g&&u.jsx("span",{className:"text-xs rounded bg-amber-100 px-1.5 py-0.5 text-amber-900",children:"changed"})]}),u.jsx("div",{className:"flex gap-2",children:!d&&!o&&u.jsxs(de,{size:"sm",variant:"outline",onClick:()=>h(!0),children:[u.jsx(Ux,{className:"h-3.5 w-3.5 mr-1.5"})," Edit"]})})]}),u.jsx("div",{className:"px-4 py-3",children:d?u.jsxs("div",{className:"space-y-2",children:[u.jsx("textarea",{ref:m,value:t,onChange:p=>l(p.target.value),onKeyDown:p=>{p.key==="Escape"&&(p.preventDefault(),h(!1))},rows:10,className:"w-full rounded border bg-transparent p-2 font-mono text-sm shadow-sm focus:outline-none focus:ring-1 focus:ring-ring",placeholder:"Appended to Claude Code's default system prompt.",maxLength:32e3,spellCheck:!1}),u.jsxs("div",{className:"flex justify-end gap-2",children:[u.jsx(de,{size:"sm",variant:"ghost",onClick:()=>{s(),h(!1)},disabled:!g,children:"Revert"}),u.jsx(de,{size:"sm",onClick:()=>h(!1),children:"Done"})]}),u.jsx("p",{className:"text-xs text-muted-foreground",children:"`Done` collapses this editor. The change is saved only when you click Save in the bar at the bottom of the page."})]}):u.jsx("pre",{className:"whitespace-pre-wrap break-words rounded bg-muted p-3 text-sm font-mono max-h-64 overflow-auto min-h-8",children:t||u.jsx("span",{className:"text-muted-foreground italic font-sans",children:"No prompt append."})})})]})}const Ck={prompt:"Prompt",model:"Model",mcp:"MCP",env:"Env",git:"Git"};function Ak(t){return!t.summary.anyDirty&&!t.conflictMessage&&!t.errorMessage?null:u.jsx("div",{className:"sticky bottom-0 z-30 -mx-6 border-t bg-yellow-50/95 px-6 py-3 backdrop-blur",children:u.jsxs("div",{className:"flex flex-col gap-2 md:flex-row md:items-center md:justify-between",children:[u.jsxs("div",{className:"flex flex-col gap-1 text-sm",children:[t.summary.anyDirty&&u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("span",{"aria-hidden":!0,children:"🟡"}),u.jsxs("span",{className:"font-medium",children:[t.summary.dirtySections.length," section",t.summary.dirtySections.length===1?"":"s"," with unsaved changes"]}),u.jsx("span",{className:"text-muted-foreground",children:"·"}),u.jsx("span",{className:"flex flex-wrap gap-1",children:t.summary.dirtySections.map(a=>u.jsx("button",{type:"button",className:"rounded bg-white px-2 py-0.5 text-xs border hover:bg-amber-100",onClick:()=>t.onJumpTo(a),children:Ck[a]},a))})]}),u.jsx("p",{className:"text-xs text-muted-foreground",children:t.saveHint}),t.conflictMessage&&u.jsx("p",{className:"text-xs text-amber-900 font-medium",children:t.conflictMessage}),t.errorMessage&&u.jsx("p",{className:"text-xs text-red-800 font-medium",children:t.errorMessage})]}),u.jsxs("div",{className:"flex gap-2",children:[t.conflictMessage&&u.jsx(de,{variant:"outline",size:"sm",onClick:t.onReloadRemote,children:"Discard mine, load latest"}),u.jsx(de,{variant:"ghost",size:"sm",onClick:t.onDiscard,disabled:t.saving,children:"Discard changes"}),u.jsx(de,{size:"sm",onClick:t.onSave,disabled:t.saving||!t.summary.anyDirty,children:t.saving?"Saving…":"Save"})]})]})})}function Jr(t){return`agent-cfg-${t}`}function Tk(t){switch(t){case"danger":return"border-red-300 bg-red-50 text-red-900";case"warning":return"border-amber-300 bg-amber-50 text-amber-900";case"muted":return"border-gray-300 bg-gray-50 text-gray-700";default:return"border-gray-200 bg-white text-gray-800"}}function zk(t){switch(t){case"danger":return"bg-red-500";case"warning":return"bg-amber-500";case"muted":return"bg-gray-400";default:return"bg-green-500"}}function Ok(t){const{agent:a,clientStatus:l,runtimeState:s,isHuman:o}=t;return a.status==="suspended"?{tone:"muted",symbol:"◌",label:"Suspended"}:o?{tone:"neutral",symbol:"●",label:"Active"}:l!=null&&l.offlineSince&&!l.clientId?{tone:"muted",symbol:"○",label:"Unclaimed"}:l&&!l.online?{tone:"warning",symbol:"⚠",label:"Client offline"}:s==="error"?{tone:"danger",symbol:"●",label:"Error"}:s==="working"?{tone:"neutral",symbol:"●",label:"Working"}:s==="idle"?{tone:"neutral",symbol:"●",label:"Idle"}:{tone:"neutral",symbol:"●",label:"Online"}}function Rk(t){if(!t)return"—";const a=new Date(t).getTime(),l=Date.now()-a;if(!Number.isFinite(l)||l<0)return un(t);const s=Math.floor(l/6e4);if(s<1)return"just now";if(s<60)return`${s}m ago`;const o=Math.floor(s/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function Mk(t){const{agent:a,cfg:l,clientStatus:s,runtimeType:o,activeSessions:d,isHuman:h}=t,m=Ok(t),g=[];!h&&o&&g.push(o),!h&&typeof d=="number"&&g.push(`${d} session${d===1?"":"s"}`),l&&g.push(`config v${l.version}`);const p=s==null?void 0:s.offlineSince,x=!h&&s&&!s.online;return u.jsxs("div",{className:je("rounded-md border px-4 py-3 text-sm space-y-1",Tk(m.tone)),children:[u.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[u.jsx("span",{className:je("inline-block h-2 w-2 rounded-full",zk(m.tone)),"aria-hidden":!0}),u.jsx("span",{children:m.symbol==="⚠"?m.symbol:null}),u.jsx("span",{children:m.label}),g.length>0&&u.jsxs("span",{className:"text-muted-foreground font-normal",children:["· ",g.join(" · ")]})]}),!h&&u.jsx("div",{className:"text-xs text-muted-foreground",children:s!=null&&s.clientId?u.jsxs(u.Fragment,{children:["Client ",u.jsx("span",{className:"font-mono",children:s.clientId}),s.online?null:u.jsxs(u.Fragment,{children:[" · offline since ",u.jsx("span",{children:un(p)})]})]}):u.jsx("span",{children:"No client bound yet"})}),l&&u.jsxs("div",{className:"text-xs text-muted-foreground",children:["Config updated by ",u.jsx("span",{className:"font-medium",children:l.updatedBy||"—"})," · ",Rk(l.updatedAt)]}),x&&u.jsx("p",{className:"mt-1 text-xs text-amber-900",children:"Changes saved here won't take effect until the client reconnects."}),!h&&!(s!=null&&s.clientId)&&a.status==="active"&&u.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Configure now; it will apply when a client claims this agent."})]})}function kk(t){return t.isUnclaimed?"Saving: configuration stored; will apply when a client claims this agent.":t.isOffline?"Saving: configuration stored; will apply when the client reconnects.":t.activeSessions>0?`Saving: new chats use this immediately; ${t.activeSessions} active chat${t.activeSessions===1?"":"s"} switch on their next message.`:"Saving: new chats use this immediately."}function Dk(t,a){let l=a.size+1;for(;a.has(`${t}-${l}`);)l++;return`${t}-${l}`}function Uk(t,a){return JSON.stringify(t)===JSON.stringify(a)}function Xf(t,a){return t.map((l,s)=>({key:`${a}-${s+1}`,value:l,baseline:l,status:"unchanged"}))}function Ob(t){return t.map(a=>a.status==="deleted"?a:a.baseline==null?{...a,status:"added"}:Uk(a.value,a.baseline)?{...a,status:"unchanged"}:{...a,status:"modified"})}function Jf(t,a){const l=t;return{add:s=>a(o=>{const d=o[t],h=new Set(d.map(p=>p.key)),m=Dk(l,h),g=[...d,{key:m,value:s,baseline:null,status:"added"}];return{...o,[t]:Ob(g)}}),update:(s,o)=>a(d=>{const m=d[t].map(g=>g.key===s?{...g,value:o}:g);return{...d,[t]:Ob(m)}}),remove:s=>a(o=>{const h=o[t].map(m=>m.key!==s?m:m.baseline==null?null:{...m,status:"deleted"}).filter(m=>m!==null);return{...o,[t]:h}}),undo:s=>a(o=>{const h=o[t].map(m=>m.key!==s||m.baseline==null?m:{...m,value:m.baseline,status:"unchanged"});return{...o,[t]:h}})}}function Lk(t){return{promptAppend:t.payload.prompt.append,model:t.payload.model,mcp:Xf(t.payload.mcpServers,"mcp"),env:Xf(t.payload.env,"env"),git:Xf(t.payload.gitRepos,"git")}}function Zk(t){const[a,l]=y.useState(null);y.useEffect(()=>{t&&a===null&&l(Lk(t))},[t,a]);const s=a??{promptAppend:"",model:"",mcp:[],env:[],git:[]},o=(t==null?void 0:t.payload.prompt.append)??"",d=(t==null?void 0:t.payload.model)??"",h=s.promptAppend!==o,m=s.model!==d,g=y.useMemo(()=>{const q=[],B=k=>k.reduce((ee,be)=>be.status==="unchanged"?ee:ee+1,0),F=B(s.mcp),J=B(s.env),K=B(s.git);return h&&q.push("prompt"),m&&q.push("model"),F>0&&q.push("mcp"),J>0&&q.push("env"),K>0&&q.push("git"),{anyDirty:q.length>0,dirtySections:q,counts:{prompt:h?1:0,model:m?1:0,mcp:F,env:J,git:K}}},[s,h,m]),p=y.useCallback(q=>{l(B=>B&&q(B))},[]),x=y.useCallback(q=>p(B=>({...B,promptAppend:q})),[p]),b=y.useCallback(()=>p(q=>({...q,promptAppend:o})),[p,o]),j=y.useCallback(q=>p(B=>({...B,model:q})),[p]),w=y.useCallback(()=>p(q=>({...q,model:d})),[p,d]),C=y.useMemo(()=>Jf("mcp",p),[p]),N=y.useMemo(()=>Jf("env",p),[p]),_=y.useMemo(()=>Jf("git",p),[p]),R=y.useCallback(()=>{l(null)},[]),Q=y.useCallback(()=>{if(!a||!t)return{};const q={};h&&(q.prompt={append:a.promptAppend}),m&&(q.model=a.model);const B=g.counts.mcp>0,F=g.counts.env>0,J=g.counts.git>0;return B&&(q.mcpServers=a.mcp.filter(K=>K.status!=="deleted").map(K=>K.value)),F&&(q.env=a.env.filter(K=>K.status!=="deleted").map(K=>{const k=K.value;return k.sensitive&&k.value===jh?{key:k.key,value:jh,sensitive:!0}:k})),J&&(q.gitRepos=a.git.filter(K=>K.status!=="deleted").map(K=>K.value)),q},[a,t,h,m,g]);return{draft:s,summary:g,promptDirty:h,modelDirty:m,setPromptAppend:x,revertPrompt:b,setModel:j,revertModel:w,addMcp:C.add,updateMcp:C.update,deleteMcp:C.remove,undoDeleteMcp:C.undo,addEnv:N.add,updateEnv:N.update,deleteEnv:N.remove,undoDeleteEnv:N.undo,addGit:_.add,updateGit:_.update,deleteGit:_.remove,undoDeleteGit:_.undo,resetAll:R,buildPayloadPatch:Q}}const qk=Object.values(_O);function Bk(){var Us,no,ao,Za,Ht,Zn,Qt,ro,lo;const a=_w().uuid??"",l=Ar(),s=Mn(),o=De({queryKey:["agent",a],queryFn:()=>s2(a),enabled:!!a}),d=De({queryKey:["agent-config",a],queryFn:()=>lk(a),enabled:!!a&&((Us=o.data)==null?void 0:Us.type)!=="human"}),h=De({queryKey:["agent-client-status",a],queryFn:()=>ok(a),enabled:!!a&&((no=o.data)==null?void 0:no.type)!=="human"}),m=De({queryKey:["agent-sessions-active",a],queryFn:()=>uc(a,{state:"active"}),enabled:!!a&&((ao=o.data)==null?void 0:ao.type)!=="human"}),g=De({queryKey:["adapters"],queryFn:a0}),p=De({queryKey:["adapter-mappings"],queryFn:t0}),{data:x}=De({queryKey:["adapter-statuses"],queryFn:n0,refetchInterval:15e3}),b=((Za=g.data)==null?void 0:Za.filter(X=>X.agentId===a))??[],j=((Ht=p.data)==null?void 0:Ht.filter(X=>X.agentId===a))??[],w=Zk(d.data),[C,N]=y.useState(null),[_,R]=y.useState(null),Q=st({mutationFn:async()=>{if(!d.data)throw new Error("config not loaded");const X=w.buildPayloadPatch();return sk(a,{expectedVersion:d.data.version,payload:X})},onSuccess:X=>{s.setQueryData(["agent-config",a],X),N(null),R(null)},onError:X=>{if(X instanceof $h&&X.status===409){R("Someone else saved a newer version while you were editing."),N(null);return}N(X instanceof Error?X.message:String(X))}}),q=y.useCallback(()=>{R(null),N(null),s.invalidateQueries({queryKey:["agent-config",a]}),w.resetAll()},[s,a,w]),B=y.useCallback(X=>{const Re=document.getElementById(Jr(X));Re&&Re.scrollIntoView({behavior:"smooth",block:"start"})},[]),F=st({mutationFn:X=>o2(a,X),onSuccess:()=>{s.invalidateQueries({queryKey:["agent",a]}),s.invalidateQueries({queryKey:["agents"]})}}),J=st({mutationFn:()=>c2(a),onSuccess:()=>s.invalidateQueries({queryKey:["agent",a]})}),K=st({mutationFn:()=>d2(a),onSuccess:()=>s.invalidateQueries({queryKey:["agent",a]})}),k=st({mutationFn:()=>u2(a),onSuccess:()=>l("/agents")}),ee=st({mutationFn:()=>f2(a)}),[be,_e]=y.useState(!1),Ue=y.useRef(null);y.useEffect(()=>{if(!be)return;function X(Re){Ue.current&&!Ue.current.contains(Re.target)&&_e(!1)}return window.addEventListener("mousedown",X),()=>window.removeEventListener("mousedown",X)},[be]);const[jt,Ge]=y.useState(!1),[xe,$]=y.useState(null),[D,ae]=y.useState(Wf),[ze,W]=y.useState(""),O=st({mutationFn:async()=>{const X=Rb(D);if(!X)throw new Error("Credentials are required");return x2({platform:D.platform,agentId:a,credentials:X,status:D.status})},onSuccess:()=>{s.invalidateQueries({queryKey:["adapters"]}),Rr()}}),Y=st({mutationFn:()=>{if(!xe)throw new Error("No adapter selected");const X={status:D.status},Re=Rb(D);return Re&&(X.credentials=Re),S2(xe,X)},onSuccess:()=>{s.invalidateQueries({queryKey:["adapters"]}),Rr()}}),te=st({mutationFn:j2,onSuccess:()=>s.invalidateQueries({queryKey:["adapters"]})}),le=st({mutationFn:()=>y2({platform:D.platform,externalUserId:D.externalUserId,agentId:a,boundVia:"manual",displayName:D.displayName||void 0}),onSuccess:()=>{s.invalidateQueries({queryKey:["adapter-mappings"]}),Rr()}}),ue=st({mutationFn:b2,onSuccess:()=>s.invalidateQueries({queryKey:["adapter-mappings"]})}),[me,Oe]=y.useState(null),pt=st({mutationFn:()=>ik(a,w.buildPayloadPatch()),onSuccess:X=>{const Re=X.diff.length?X.diff.map(Jt=>`${Jt.op} ${Jt.path}`).join(`
308
- `):"(no changes)";Oe(Re)},onError:X=>Oe(`Dry run failed: ${X instanceof Error?X.message:String(X)}`)});if(y.useEffect(()=>{if(!w.summary.anyDirty)return;const X=Re=>{Re.preventDefault(),Re.returnValue=""};return window.addEventListener("beforeunload",X),()=>window.removeEventListener("beforeunload",X)},[w.summary.anyDirty]),o.isLoading)return u.jsx("div",{className:"text-muted-foreground",children:"Loading..."});if(o.error)return u.jsxs("div",{className:"text-destructive",children:["Failed to load agent: ",o.error instanceof Error?o.error.message:"Unknown error"]});const fe=o.data;if(!fe)return u.jsx("div",{className:"text-muted-foreground",children:"Agent not found"});const gt=fe.type==="human",Dt=h.data,Ln=((Zn=m.data)==null?void 0:Zn.length)??0,La=!gt&&!(Dt!=null&&Dt.clientId),Xt=!gt&&Dt?!Dt.online&&!!Dt.clientId:!1,vl=fe,Ms=vl.runtimeState??null,cc=vl.runtimeType??null;function Rr(){Ge(!1),$(null),ae(Wf),W("")}function ks(X){$(X.id),ae({...Wf,platform:X.platform,status:X.status}),Ge(!0)}function Ds(X){if(X.preventDefault(),W(""),gt){if(!D.externalUserId)return;le.mutate();return}if(D.platform==="feishu"){if(!xe&&(!D.feishuAppId||!D.feishuAppSecret)){W("App ID and App Secret are required");return}}else if(D.platform==="kael"){if(!xe&&(!D.kaelUserId||!D.kaelProjectId)){W("User ID and Project ID are required");return}}else{const Re=D.credentialsJson.trim();if(!xe&&!Re){W("Credentials are required");return}if(Re)try{JSON.parse(Re)}catch{W("Invalid JSON");return}}xe?Y.mutate():O.mutate()}const yl=O.error??Y.error??le.error,Wi=O.isPending||Y.isPending||le.isPending,dc=kk({activeSessions:Ln,isUnclaimed:La,isOffline:Xt}),Vt=w.draft.mcp.filter(X=>X.status!=="deleted"),fc=w.draft.env.filter(X=>X.status!=="deleted"),eo=w.draft.git.filter(X=>X.status!=="deleted"),to=X=>new Set(Vt.filter(Re=>Re.key!==X).map(Re=>Re.value.name.toLowerCase())),bl=X=>new Set(fc.filter(Re=>Re.key!==X).map(Re=>Re.value.key)),hc=X=>new Set(eo.filter(Re=>Re.key!==X).map(Re=>{const{value:Jt}=Re;return Jt.localPath?Jt.localPath:((Jt.url.split(/[?#]/)[0]??"").split(/[/:]/).filter(Boolean).pop()??"").replace(/\.git$/i,"")}).filter(Boolean));return u.jsxs("div",{className:"space-y-5 pb-24",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx(de,{variant:"ghost",size:"icon",onClick:()=>l("/agents"),children:u.jsx(Rx,{className:"h-4 w-4"})}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("h1",{className:"text-2xl font-semibold truncate",children:fe.displayName??fe.name}),u.jsxs("p",{className:"text-xs text-muted-foreground font-mono truncate",children:["@",fe.name??fe.uuid," · ",fe.type]})]}),u.jsxs("div",{className:"relative",ref:Ue,children:[u.jsx(de,{variant:"outline",size:"icon",onClick:()=>_e(X=>!X),title:"More actions",children:u.jsx(Dx,{className:"h-4 w-4"})}),be&&u.jsx("div",{className:"absolute right-0 mt-1 z-40 min-w-48 rounded-md border bg-white shadow-lg text-sm",children:u.jsxs("ul",{className:"py-1",children:[!gt&&fe.status==="active"&&u.jsx("li",{children:u.jsxs("button",{type:"button",onClick:()=>{_e(!1),ee.reset(),ee.mutate()},className:"w-full text-left px-3 py-1.5 hover:bg-gray-50 flex items-center gap-2",disabled:ee.isPending,children:[u.jsx(aE,{className:"h-3.5 w-3.5"}),ee.isPending?"Testing…":"Test connection"]})}),fe.status==="active"?u.jsx("li",{children:u.jsx("button",{type:"button",onClick:()=>{_e(!1),confirm("Suspend this agent? All tokens will be revoked.")&&J.mutate()},className:"w-full text-left px-3 py-1.5 hover:bg-gray-50",children:"Suspend"})}):u.jsx("li",{children:u.jsx("button",{type:"button",onClick:()=>{_e(!1),K.mutate()},className:"w-full text-left px-3 py-1.5 hover:bg-gray-50",children:"Reactivate"})}),u.jsx("li",{className:"border-t",children:u.jsx("a",{href:`#${Jr("prompt")}`,onClick:()=>_e(!1),className:"block px-3 py-1.5 text-xs text-muted-foreground hover:bg-gray-50",children:"Jump to Behavior"})})]})})]})]}),(ee.data||ee.error)&&u.jsx(Gk,{result:ee.data??{status:"error",message:"Failed to reach server"},onDismiss:()=>ee.reset()}),u.jsx(Mk,{agent:fe,cfg:d.data,clientStatus:Dt,runtimeState:Ms,runtimeType:cc,activeSessions:Ln,isHuman:gt}),u.jsx(xk,{agent:fe,onSave:async X=>{await F.mutateAsync(X)}}),!gt&&u.jsxs($k,{loaded:!!d.data,loading:d.isLoading,error:d.error?String(d.error):null,version:((Qt=d.data)==null?void 0:Qt.version)??null,dirty:w.summary.anyDirty,children:[u.jsx("div",{id:Jr("prompt"),children:u.jsx(Ek,{value:w.draft.promptAppend,baseline:((ro=d.data)==null?void 0:ro.payload.prompt.append)??"",onChange:w.setPromptAppend,onRevert:w.revertPrompt,disabled:fe.status!=="active"})}),u.jsx("div",{id:Jr("model"),children:u.jsx(_k,{value:w.draft.model,baseline:((lo=d.data)==null?void 0:lo.payload.model)??"",onChange:w.setModel,onRevert:w.revertModel,disabled:fe.status!=="active"})}),u.jsx("div",{id:Jr("mcp"),children:u.jsx(jk,{items:w.draft.mcp,otherNames:to,onAdd:w.addMcp,onUpdate:w.updateMcp,onDelete:w.deleteMcp,onUndoDelete:w.undoDeleteMcp,disabled:fe.status!=="active"})}),u.jsx("div",{id:Jr("env"),children:u.jsx(gk,{items:w.draft.env,otherKeys:bl,onAdd:w.addEnv,onUpdate:w.updateEnv,onDelete:w.deleteEnv,onUndoDelete:w.undoDeleteEnv,disabled:fe.status!=="active"})}),u.jsx("div",{id:Jr("git"),children:u.jsx(yk,{items:w.draft.git,otherPaths:hc,onAdd:w.addGit,onUpdate:w.updateGit,onDelete:w.deleteGit,onUndoDelete:w.undoDeleteGit,disabled:fe.status!=="active"})}),me&&u.jsx("pre",{className:"whitespace-pre-wrap rounded border bg-gray-50 p-2 text-xs",children:me})]}),u.jsxs(cl,{children:[u.jsxs(Ns,{className:"flex flex-row items-center justify-between",children:[u.jsxs(ws,{className:"flex items-center gap-2 text-base",children:[gt?u.jsx(G_,{className:"h-4 w-4"}):u.jsx(U_,{className:"h-4 w-4"}),"Platform Bindings"]}),u.jsxs(de,{size:"sm",variant:"outline",onClick:()=>Ge(!0),children:[u.jsx(hl,{className:"h-4 w-4 mr-2"}),gt?"Bind User":"Bind Bot"]})]}),u.jsx(dl,{children:gt?u.jsxs(Oa,{children:[u.jsx(Ra,{children:u.jsxs(at,{children:[u.jsx(ye,{children:"Platform"}),u.jsx(ye,{children:"External User ID"}),u.jsx(ye,{children:"Display Name"}),u.jsx(ye,{children:"Bound Via"}),u.jsx(ye,{children:"Created"}),u.jsx(ye,{className:"w-16"})]})}),u.jsx(Ma,{children:j.length===0?u.jsx(at,{children:u.jsx(ve,{colSpan:6,className:"text-center py-4 text-muted-foreground",children:"No platform bindings"})}):j.map(X=>u.jsxs(at,{children:[u.jsx(ve,{children:u.jsx($t,{variant:"secondary",children:X.platform})}),u.jsx(ve,{className:"font-mono text-sm",children:X.externalUserId}),u.jsx(ve,{children:X.displayName??"—"}),u.jsx(ve,{children:u.jsx($t,{variant:"outline",children:X.boundVia??"—"})}),u.jsx(ve,{className:"text-muted-foreground",children:un(X.createdAt)}),u.jsx(ve,{children:u.jsx(de,{variant:"ghost",size:"icon",onClick:()=>{confirm("Remove this binding?")&&ue.mutate(X.id)},disabled:ue.isPending,children:u.jsx(Zi,{className:"h-4 w-4"})})})]},X.id))})]}):u.jsxs(Oa,{children:[u.jsx(Ra,{children:u.jsxs(at,{children:[u.jsx(ye,{children:"Platform"}),u.jsx(ye,{children:"Status"}),u.jsx(ye,{children:"Connection"}),u.jsx(ye,{children:"Created"}),u.jsx(ye,{className:"w-24"})]})}),u.jsx(Ma,{children:b.length===0?u.jsx(at,{children:u.jsx(ve,{colSpan:5,className:"text-center py-4 text-muted-foreground",children:"No platform bindings"})}):b.map(X=>{const Re=x==null?void 0:x.find(Mr=>Mr.configId===X.id),Jt=X.platform==="kael"?X.status==="active":!!(Re!=null&&Re.connected);return u.jsxs(at,{children:[u.jsx(ve,{children:u.jsx($t,{variant:"secondary",children:X.platform})}),u.jsx(ve,{children:u.jsx($t,{variant:X.status==="active"?"default":"destructive",children:X.status})}),u.jsx(ve,{children:u.jsxs("span",{className:"flex items-center gap-1.5",children:[u.jsx("span",{className:je("inline-block h-2 w-2 rounded-full",Jt?"bg-green-500":"bg-gray-300")}),u.jsx("span",{className:"text-xs text-muted-foreground",children:Jt?"Online":"Offline"})]})}),u.jsx(ve,{className:"text-muted-foreground",children:un(X.createdAt)}),u.jsx(ve,{children:u.jsxs("div",{className:"flex gap-1",children:[u.jsx(de,{variant:"ghost",size:"icon",onClick:()=>ks(X),title:"Edit",children:"…"}),u.jsx(de,{variant:"ghost",size:"icon",onClick:()=>{confirm("Remove this bot binding?")&&te.mutate(X.id)},disabled:te.isPending,title:"Delete",children:u.jsx(Zi,{className:"h-4 w-4"})})]})})]},X.id)})})]})})]}),u.jsx(fk,{agent:fe,suspendPending:J.isPending,reactivatePending:K.isPending,deletePending:k.isPending,onSuspend:()=>{confirm("Suspend this agent? Runtime binds and HTTP calls will be refused.")&&J.mutate()},onReactivate:()=>K.mutate(),onDelete:()=>k.mutate()}),!gt&&u.jsx(Ak,{summary:w.summary,saveHint:dc,conflictMessage:_,errorMessage:C,saving:Q.isPending,onSave:()=>Q.mutate(),onDiscard:()=>{(!w.summary.anyDirty||confirm("Discard all unsaved changes?"))&&(w.resetAll(),N(null),R(null))},onReloadRemote:q,onJumpTo:B}),!gt&&w.summary.anyDirty&&u.jsx("div",{className:"text-xs text-muted-foreground",children:u.jsx("button",{type:"button",onClick:()=>pt.mutate(),className:"underline hover:text-gray-900",disabled:pt.isPending,children:pt.isPending?"Computing dry-run…":"Preview server-side diff"})}),u.jsx(Da,{open:jt,onOpenChange:X=>X?Ge(!0):Rr(),children:u.jsxs(na,{children:[u.jsx(Ua,{children:u.jsx(aa,{children:gt?"Bind External User":xe?"Edit Bot Binding":"Bind Bot"})}),u.jsxs("form",{onSubmit:Ds,className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"binding-platform",children:"Platform"}),u.jsx("select",{id:"binding-platform",value:D.platform,onChange:X=>ae({...D,platform:X.target.value}),disabled:!!xe,className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50",children:qk.map(X=>u.jsx("option",{value:X,children:X},X))})]}),gt?u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"binding-ext-id",children:"External User ID"}),u.jsx(tt,{id:"binding-ext-id",value:D.externalUserId,onChange:X=>ae({...D,externalUserId:X.target.value}),placeholder:"ou_xxxxxxxx...",className:"font-mono",required:!0})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"binding-name",children:"Display Name (optional)"}),u.jsx(tt,{id:"binding-name",value:D.displayName,onChange:X=>ae({...D,displayName:X.target.value})})]})]}):u.jsxs(u.Fragment,{children:[D.platform==="feishu"?u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"space-y-2",children:[u.jsxs($e,{htmlFor:"feishu-app-id",children:["App ID",xe?" — leave empty to keep existing":""]}),u.jsx(tt,{id:"feishu-app-id",value:D.feishuAppId,onChange:X=>ae({...D,feishuAppId:X.target.value}),placeholder:"cli_xxxxxxxx",className:"font-mono",autoComplete:"off"})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsxs($e,{htmlFor:"feishu-app-secret",children:["App Secret",xe?" — leave empty to keep existing":""]}),u.jsx(tt,{id:"feishu-app-secret",type:"password",autoComplete:"new-password",value:D.feishuAppSecret,onChange:X=>ae({...D,feishuAppSecret:X.target.value}),placeholder:"••••••••"})]})]}):D.platform==="kael"?u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"space-y-2",children:[u.jsxs($e,{htmlFor:"kael-user-id",children:["User ID",xe?" — leave empty to keep existing":""]}),u.jsx(tt,{id:"kael-user-id",value:D.kaelUserId,onChange:X=>ae({...D,kaelUserId:X.target.value}),placeholder:"user_xxxxxxxx",className:"font-mono",autoComplete:"off"})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsxs($e,{htmlFor:"kael-project-id",children:["Project ID",xe?" — leave empty to keep existing":""]}),u.jsx(tt,{id:"kael-project-id",value:D.kaelProjectId,onChange:X=>ae({...D,kaelProjectId:X.target.value}),placeholder:"proj_xxxxxxxx",className:"font-mono",autoComplete:"off"})]}),!xe&&u.jsx("p",{className:"text-sm text-muted-foreground",children:"Agent Token will be created automatically when you save."})]}):u.jsxs("div",{className:"space-y-2",children:[u.jsxs($e,{htmlFor:"binding-creds",children:["Credentials (JSON)",xe?" — leave empty to keep existing":""]}),u.jsx("textarea",{id:"binding-creds",value:D.credentialsJson,onChange:X=>ae({...D,credentialsJson:X.target.value}),rows:4,className:"flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm font-mono focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",placeholder:'{"bot_token": "xoxb-...", "signing_secret": "..."}'})]}),ze&&u.jsx("p",{className:"text-sm text-destructive",children:ze}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"binding-status",children:"Status"}),u.jsxs("select",{id:"binding-status",value:D.status,onChange:X=>ae({...D,status:X.target.value}),className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:[u.jsx("option",{value:"active",children:"active"}),u.jsx("option",{value:"inactive",children:"inactive"})]})]})]}),yl instanceof Error&&u.jsx("div",{className:"text-sm text-destructive",children:yl.message}),u.jsx(ta,{children:u.jsx(de,{type:"submit",disabled:Wi,children:Wi?"Saving...":xe?"Update":"Create"})})]})]})})]})}function $k(t){return u.jsxs("section",{className:"space-y-3",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("h2",{className:"text-base font-semibold",children:"Behavior"}),u.jsxs("div",{className:"text-xs text-muted-foreground",children:[t.version!=null&&u.jsxs("span",{children:["v",t.version]}),t.dirty&&u.jsx("span",{className:"ml-2 text-amber-700",children:"· draft"})]})]}),t.loading&&u.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading configuration…"}),t.error&&u.jsxs("div",{className:"text-sm text-destructive",children:["Failed to load configuration: ",t.error]}),t.loaded&&u.jsx("div",{className:"space-y-3",children:t.children})]})}const Wf={platform:"feishu",feishuAppId:"",feishuAppSecret:"",credentialsJson:"{}",status:"active",externalUserId:"",displayName:"",kaelUserId:"",kaelProjectId:"",kaelAgentToken:""};function Rb(t){if(t.platform==="feishu"){if(!t.feishuAppId&&!t.feishuAppSecret)return null;if(!t.feishuAppId||!t.feishuAppSecret)throw new Error("Both App ID and App Secret are required");return{app_id:t.feishuAppId,app_secret:t.feishuAppSecret}}if(t.platform==="kael"){if(!t.kaelUserId&&!t.kaelProjectId)return null;if(!t.kaelUserId||!t.kaelProjectId)throw new Error("User ID and Project ID are required");return{kaelUserId:t.kaelUserId,kaelProjectId:t.kaelProjectId}}const a=t.credentialsJson.trim();return a?JSON.parse(a):null}const Hk={success:"Connected",timeout:"Timed out",offline:"Offline",stale:"Stale",error:"Error"},Qk={connected:{icon:"●",color:"text-green-500",label:"Connected"},stale:{icon:"◐",color:"text-yellow-500",label:"Stale"},disconnected:{icon:"○",color:"text-gray-400",label:"Disconnected"}};function Gk({result:t,onDismiss:a}){const l={success:"border-l-green-500",timeout:"border-l-yellow-500",offline:"border-l-gray-400",stale:"border-l-yellow-500",error:"border-l-red-500"}[t.status],s=t.status==="success"?"default":t.status==="timeout"||t.status==="stale"?"secondary":"destructive",o=t.connection,d=o?Qk[o.health]:null;return u.jsx(cl,{className:je("border-l-4",l),children:u.jsx(dl,{className:"pt-4",children:u.jsxs("div",{className:"flex items-start justify-between",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx($t,{variant:s,children:Hk[t.status]}),t.responseTime!=null&&u.jsxs("span",{className:"text-xs text-muted-foreground",children:[(t.responseTime/1e3).toFixed(1),"s"]})]}),t.message&&u.jsx("p",{className:"text-sm text-muted-foreground",children:t.message}),o&&u.jsxs("div",{className:"text-xs space-y-1 border-t pt-2 mt-1",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[d&&u.jsxs("span",{className:d.color,children:[d.icon," ",d.label]}),o.runtimeState&&u.jsxs("span",{className:"text-muted-foreground",children:["runtime: ",o.runtimeState]})]}),o.client?u.jsxs("div",{className:"text-muted-foreground",children:["Client: ",o.client.hostname??o.client.id,o.client.os&&` (${o.client.os})`,o.client.sdkVersion&&` · SDK ${o.client.sdkVersion}`]}):u.jsx("div",{className:"text-muted-foreground",children:"No client bound"}),o.lastSeenAt&&u.jsxs("div",{className:"text-muted-foreground",children:["Last seen: ",new Date(o.lastSeenAt).toLocaleString()]})]}),t.responseContent&&u.jsx("p",{className:"text-sm mt-2 whitespace-pre-wrap bg-muted rounded p-2 max-h-40 overflow-auto",children:t.responseContent})]}),u.jsx(de,{variant:"ghost",size:"sm",onClick:a,children:"Dismiss"})]})})})}const Ik=Object.values(G0);function Vk(t){var xe,$;const{open:a,onOpenChange:l,onSubmit:s,isPending:o,error:d,mode:h}=t,m=h==="edit"?t.agent:void 0,{memberId:g,role:p}=Os(),x=p==="admin",[b,j]=y.useState(""),[w,C]=y.useState("personal_assistant"),[N,_]=y.useState(""),[R,Q]=y.useState(""),[q,B]=y.useState(""),[F,J]=y.useState(""),K=h==="create"&&w!=="human",k=De({queryKey:["clients-for-pin"],queryFn:Ih,enabled:a&&K}),ee=w==="human",be=De({queryKey:["agents-for-delegate"],queryFn:async()=>(await Ju({limit:100})).items.filter(ae=>ae.type==="personal_assistant"&&ae.status==="active"),enabled:a&&ee}),_e=De({queryKey:["members-for-manager"],queryFn:sm,enabled:a&&h==="create"&&x}),Ue=y.useMemo(()=>{var ze;const D=k.data??[];if(!K||!x)return D;if(!q)return[];const ae=(ze=_e.data)==null?void 0:ze.find(W=>W.id===q);return ae?D.filter(W=>(W.userId??null)===ae.userId):[]},[k.data,x,q,_e.data,K]);y.useEffect(()=>{a&&(m?(j(m.name??""),C(m.type),_(m.displayName??""),Q(m.delegateMention??""),B(m.managerId??"")):(j(""),C("personal_assistant"),_(""),Q(""),B(x?"":g??""),J("")))},[a,m,x,g]);const jt=D=>{D.preventDefault(),s({name:h==="create"&&b?b:void 0,type:w,displayName:N||null,delegateMention:R||null,managerId:q||null,clientId:F||null})},Ge=h==="edit";return u.jsx(Da,{open:a,onOpenChange:l,children:u.jsxs(na,{children:[u.jsx(Ua,{children:u.jsx(aa,{children:Ge?"Edit Agent":"New Agent"})}),u.jsxs("form",{onSubmit:jt,className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"agent-name",children:"Name"}),Ge?u.jsx(tt,{id:"agent-name",value:b,disabled:!0,className:"font-mono"}):u.jsx(tt,{id:"agent-name",value:b,onChange:D=>j(D.target.value),placeholder:"Leave empty to auto-generate",pattern:"^[a-z0-9_-]*$",title:"Only lowercase alphanumeric, hyphens, and underscores",className:"font-mono"})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"agent-type",children:"Type"}),u.jsx("select",{id:"agent-type",value:w,onChange:D=>{const ae=D.target.value;C(ae),ae!=="human"&&Q(""),J("")},disabled:Ge,className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50",children:Ik.map(D=>u.jsx("option",{value:D,children:D},D))})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"agent-display-name",children:"Display Name"}),u.jsx(tt,{id:"agent-display-name",value:N,onChange:D=>_(D.target.value),placeholder:"Optional",maxLength:200})]}),h==="create"&&x&&u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"agent-manager",children:"Manager"}),u.jsxs("select",{id:"agent-manager",value:q,onChange:D=>{B(D.target.value),J("")},className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:[u.jsx("option",{value:"",children:"Select a member…"}),(xe=_e.data)==null?void 0:xe.map(D=>u.jsxs("option",{value:D.id,children:[D.displayName," (",D.role,")"]},D.id))]}),u.jsx("p",{className:"text-xs text-muted-foreground",children:"Non-human agents must pin a client belonging to this user."})]}),ee&&u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"agent-delegate",children:"Delegate Mention"}),u.jsxs("select",{id:"agent-delegate",value:R,onChange:D=>Q(D.target.value),className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:[u.jsx("option",{value:"",children:"None"}),($=be.data)==null?void 0:$.map(D=>u.jsx("option",{value:D.uuid,children:D.displayName?`${D.displayName} (${D.name??D.uuid})`:D.name??D.uuid},D.uuid))]}),u.jsx("p",{className:"text-xs text-muted-foreground",children:"The personal assistant that acts on behalf of this agent"})]}),K&&u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"agent-client",children:"Client"}),Ue.length>0?u.jsxs("select",{id:"agent-client",value:F,onChange:D=>J(D.target.value),className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:[u.jsx("option",{value:"",children:"Select a client…"}),Ue.map(D=>u.jsx("option",{value:D.id,children:D.hostname??D.id.slice(0,12)},D.id))]}):u.jsx("p",{className:"text-xs text-muted-foreground",children:x&&!q?"Pick a manager first to see their clients.":"No eligible clients. Run `first-tree-hub connect` on the target machine to register one."}),u.jsx("p",{className:"text-xs text-muted-foreground",children:"Pinned at creation — clientId is immutable in this milestone. Move = delete + recreate."})]}),d&&u.jsx("div",{className:"text-sm text-destructive",children:d.message}),u.jsx(ta,{children:u.jsx(de,{type:"submit",disabled:o,children:o?"Saving...":Ge?"Save":"Create"})})]})]})})}const Yk=Object.values(G0);function Mb(t){return[...t].sort((a,l)=>{const s=(a.name??a.displayName??"").toLowerCase(),o=(l.name??l.displayName??"").toLowerCase();return s.localeCompare(o)})}function Kk(){const t=Ar(),a=Mn(),{memberId:l}=Os(),[s,o]=y.useState(),[d,h]=y.useState(""),[m,g]=y.useState(!1),[p,x]=y.useState(null),[b,j]=y.useState(!1),w=Qn(),C=zS(),{data:N,isLoading:_,error:R}=De({queryKey:["agents",s,d],queryFn:()=>Ju({limit:100,cursor:s,type:d||void 0})}),{myAgents:Q,teamAgents:q}=y.useMemo(()=>{if(!(N!=null&&N.items))return{myAgents:[],teamAgents:[]};const k=[],ee=[];for(const be of N.items)l&&be.managerId===l?k.push(be):ee.push(be);return{myAgents:Mb(k),teamAgents:Mb(ee)}},[N,l]),B=st({mutationFn:async k=>await i2({name:k.name,type:k.type,displayName:k.displayName??void 0,delegateMention:k.delegateMention??void 0,managerId:k.managerId??void 0,clientId:k.clientId??void 0}),onSuccess:k=>{if(g(!1),a.invalidateQueries({queryKey:["agents"]}),a.invalidateQueries({queryKey:["activity"]}),k.type==="human"){t(`/agents/${k.uuid}`);return}x(k),j(!1)}});function F(k){const be=k.runtimeState,_e={idle:"bg-green-500",working:"bg-blue-500",error:"bg-red-500"};return u.jsxs(at,{className:"cursor-pointer",onClick:()=>t(`/agents/${k.uuid}`),children:[u.jsx(ve,{className:"font-mono text-sm",children:k.name}),u.jsx(ve,{children:k.displayName??"—"}),u.jsx(ve,{children:u.jsx($t,{variant:"secondary",children:k.type})}),u.jsx(ve,{className:"font-mono text-sm text-muted-foreground",children:k.delegateMention?w(k.delegateMention):"—"}),u.jsx(ve,{className:"text-sm text-muted-foreground",children:C(k.managerId)}),u.jsx(ve,{children:be?u.jsxs("span",{className:"flex items-center gap-1.5",children:[u.jsx("span",{className:je("inline-block h-2 w-2 rounded-full",_e[be]??"bg-gray-300")}),u.jsx("span",{className:"text-xs text-muted-foreground",children:be})]}):u.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-gray-300",title:"not running"})}),u.jsx(ve,{children:u.jsx($t,{variant:k.status==="active"?"default":"destructive",children:k.status})}),u.jsx(ve,{className:"text-muted-foreground",children:un(k.createdAt)})]},k.uuid)}const J=p?`first-tree-hub agent add ${p.name??p.uuid} --agent-id ${p.uuid}`:"",K=()=>{navigator.clipboard.writeText(J),j(!0),setTimeout(()=>j(!1),2e3)};return u.jsxs("div",{className:"space-y-8",children:[u.jsxs("div",{className:"flex items-center gap-4",children:[u.jsx("h1",{className:"text-2xl font-semibold",children:"Agents"}),u.jsxs("select",{value:d,onChange:k=>{h(k.target.value),o(void 0)},className:"h-8 rounded-md border border-input bg-transparent px-2 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:[u.jsx("option",{value:"",children:"All types"}),Yk.map(k=>u.jsx("option",{value:k,children:k},k))]})]}),_?u.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):R?u.jsxs("div",{className:"text-center py-8 text-destructive",children:["Failed to load agents: ",R instanceof Error?R.message:"Unknown error"]}):u.jsxs(u.Fragment,{children:[u.jsxs("section",{children:[u.jsxs("div",{className:"flex items-center justify-between mb-3",children:[u.jsx("h2",{className:"text-lg font-medium",children:"My Agents"}),u.jsxs(de,{size:"sm",onClick:()=>g(!0),children:[u.jsx(hl,{className:"h-4 w-4 mr-2"}),"New Agent"]})]}),u.jsx("div",{className:"border rounded-lg",children:u.jsxs(Oa,{children:[u.jsx(Ra,{children:u.jsxs(at,{children:[u.jsx(ye,{children:"Name"}),u.jsx(ye,{children:"Display Name"}),u.jsx(ye,{children:"Type"}),u.jsx(ye,{children:"Delegate"}),u.jsx(ye,{children:"Owner"}),u.jsx(ye,{children:"Runtime"}),u.jsx(ye,{children:"Status"}),u.jsx(ye,{children:"Created"})]})}),u.jsx(Ma,{children:Q.length===0?u.jsx(at,{children:u.jsx(ve,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"No agents yet — create one to get started"})}):Q.map(k=>F(k))})]})})]}),q.length>0&&u.jsxs("section",{children:[u.jsx("h2",{className:"text-lg font-medium mb-3",children:"Team Agents"}),u.jsx("div",{className:"border rounded-lg",children:u.jsxs(Oa,{children:[u.jsx(Ra,{children:u.jsxs(at,{children:[u.jsx(ye,{children:"Name"}),u.jsx(ye,{children:"Display Name"}),u.jsx(ye,{children:"Type"}),u.jsx(ye,{children:"Delegate"}),u.jsx(ye,{children:"Owner"}),u.jsx(ye,{children:"Runtime"}),u.jsx(ye,{children:"Status"}),u.jsx(ye,{children:"Created"})]})}),u.jsx(Ma,{children:q.map(k=>F(k))})]})})]})]}),(N==null?void 0:N.nextCursor)&&u.jsx("div",{className:"flex justify-end",children:u.jsx(de,{variant:"outline",onClick:()=>o(N.nextCursor??void 0),children:"Next Page"})}),u.jsx(Vk,{mode:"create",open:m,onOpenChange:g,onSubmit:k=>B.mutate(k),isPending:B.isPending,error:B.error instanceof Error?B.error:null}),u.jsx(Da,{open:p!==null,onOpenChange:k=>{if(!k){const ee=p==null?void 0:p.uuid;x(null),ee&&t(`/agents/${ee}`)}},children:u.jsxs(na,{children:[u.jsx(Ua,{children:u.jsx(aa,{children:"Agent Created"})}),u.jsxs("div",{className:"space-y-3",children:[u.jsx("p",{className:"text-sm text-muted-foreground",children:"Run this on the pinned client machine to register a local alias; the client connects with your JWT, not a per-agent token."}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("code",{className:"flex-1 bg-muted rounded-md px-3 py-2 text-xs font-mono break-all select-all",children:J}),u.jsx(de,{variant:"outline",size:"icon",className:"shrink-0",onClick:K,children:b?u.jsx(Mx,{className:"h-4 w-4 text-green-600"}):u.jsx(Hh,{className:"h-4 w-4"})})]})]}),u.jsx(ta,{children:u.jsx(de,{onClick:()=>{const k=p==null?void 0:p.uuid;x(null),k&&t(`/agents/${k}`)},children:"Done"})})]})})]})}function Pk(){const{isAuthenticated:t,login:a}=Os(),[l,s]=y.useState(""),[o,d]=y.useState(""),[h,m]=y.useState(null),[g,p]=y.useState(!1);if(t)return u.jsx(bx,{to:"/",replace:!0});const x=async b=>{b.preventDefault(),m(null),p(!0);try{await a(l,o)}catch(j){m(j instanceof Error?j.message:"Login failed")}finally{p(!1)}};return u.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:u.jsxs(cl,{className:"w-full max-w-sm",children:[u.jsxs(Ns,{className:"text-center",children:[u.jsx(ws,{className:"text-2xl",children:"First Tree"}),u.jsx(l0,{children:"Sign in to your workspace"})]}),u.jsx(dl,{children:u.jsxs("form",{onSubmit:x,className:"space-y-4",children:[h&&u.jsx("div",{className:"rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:h}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"username",children:"Username"}),u.jsx(tt,{id:"username",value:l,onChange:b=>s(b.target.value),required:!0,autoFocus:!0})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"password",children:"Password"}),u.jsx(tt,{id:"password",type:"password",value:o,onChange:b=>d(b.target.value),required:!0})]}),u.jsx(de,{type:"submit",className:"w-full",disabled:g,children:g?"Signing in...":"Sign in"})]})})]})})}function Fk(t,a){return we.post(`/admin/chats/${encodeURIComponent(t)}/messages`,{format:"text",content:a})}function Xk(t){return we.post(`/admin/agents/${encodeURIComponent(t)}/chats`,{})}function Jk(t,a){const l=new URLSearchParams;l.set("limit",String(a.limit)),a!=null&&a.cursor&&l.set("cursor",a.cursor);const s=l.toString();return we.get(`/admin/chats/${encodeURIComponent(t)}/messages${s?`?${s}`:""}`)}function OS(){return we.get("/admin/overview")}const Wk=2e3,e3=3e4;function t3(t){const{onMessage:a,enabled:l=!0}={},s=Mn(),o=y.useRef(null),d=y.useRef(0),h=y.useRef(null),m=y.useRef(!1),g=y.useRef(a);g.current=a;const p=y.useRef(s);p.current=s,y.useEffect(()=>{if(!l)return;m.current=!1;function x(){const b=Bh();if(!(b!=null&&b.accessToken))return;const w=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws/admin?token=${b.accessToken}`,C=new WebSocket(w);o.current=C,C.onmessage=N=>{var _;try{const R=JSON.parse(N.data);(_=g.current)==null||_.call(g,R),R.type==="notification"?p.current.invalidateQueries({queryKey:["notifications"]}):R.type==="session:state"&&(p.current.invalidateQueries({queryKey:["activity"]}),p.current.invalidateQueries({queryKey:["sessions"]}))}catch{}},C.onopen=()=>{d.current=0},C.onclose=()=>{if(o.current=null,!m.current){d.current++;const N=Math.min(Wk*2**(d.current-1),e3);h.current=setTimeout(()=>{h.current=null,m.current||x()},N)}}}return x(),()=>{m.current=!0,h.current&&(clearTimeout(h.current),h.current=null),o.current&&(o.current.close(1e3,"unmount"),o.current=null)}},[l])}function RS(){const{data:t}=De({queryKey:["clients"],queryFn:Ih,staleTime:1e4,refetchInterval:1e4});return y.useMemo(()=>{const a=t??[],l=new Map;for(const s of a)l.set(s.id,s);return{resolve:s=>s?l.get(s)??null:null,clients:a,connectedClients:a.filter(s=>s.status==="connected")}},[t])}function n3(){const[t,a]=Ex(),l=t.get("a"),s=t.get("c"),[o,d]=y.useState(!0);t3();const h=y.useCallback(p=>{a(p?{a:p}:{})},[a]),m=y.useCallback((p,x)=>{a({a:p,c:x})},[a]),g=y.useCallback(()=>{l&&a({a:l})},[l,a]);return u.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[u.jsx(u3,{selectedAgentId:l,selectedChatId:s,onSelectAgent:h,onSelectChat:m}),u.jsx("div",{className:"flex-1 flex flex-col overflow-hidden border-x border-border",children:u.jsx(c3,{selectedAgentId:l,selectedChatId:s,onSelectChat:m,onClearChat:g})}),o?u.jsxs("div",{className:"w-80 shrink-0 flex flex-col overflow-hidden",children:[u.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border",children:[u.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:s?"Session":l?"Agent Info":"Dashboard"}),u.jsx("button",{type:"button",onClick:()=>d(!1),className:"text-muted-foreground hover:text-foreground",children:u.jsx(J_,{className:"h-4 w-4"})})]}),u.jsx(m3,{selectedAgentId:l,selectedChatId:s})]}):u.jsx("div",{className:"shrink-0 border-l border-border flex items-start pt-2 px-1",children:u.jsx("button",{type:"button",onClick:()=>d(!0),className:"text-muted-foreground hover:text-foreground p-1",children:u.jsx(eE,{className:"h-4 w-4"})})})]})}const a3={error:0,blocked:1,working:2,idle:3};function kb(t,a){return a?t?a3[t]??4:4:5}const r3={idle:"bg-green-500",working:"bg-green-500 animate-pulse",blocked:"bg-yellow-500",error:"bg-red-500"};function l3({runtimeState:t,clientId:a}){if(!a||!t)return u.jsx("span",{className:"h-2 w-2 rounded-full bg-gray-400 shrink-0 mt-1.5"});const l=r3[t]??"bg-gray-400";return u.jsx("span",{className:`h-2 w-2 rounded-full ${l} shrink-0 mt-1.5`})}function s3({state:t}){if(!t)return u.jsx("span",{className:"text-xs text-muted-foreground",children:"offline"});const a={idle:"text-green-600",working:"text-blue-600",blocked:"text-yellow-600",error:"text-red-600"};return u.jsx("span",{className:je("text-xs font-medium",a[t]??"text-muted-foreground"),children:t})}function i3({state:t}){const a={active:"border-green-500/50 text-green-600 bg-green-500/10",suspended:"border-yellow-500/50 text-yellow-600 bg-yellow-500/10",evicted:"border-muted text-muted-foreground"};return u.jsx($t,{variant:"outline",className:je("text-xs",a[t]),children:t})}function o3({msg:t,myAgentId:a}){if(!a||t.senderId!==a)return null;const l=t.deliveryStatus??"sent";return l==="acked"?u.jsx("span",{className:"text-blue-500 text-xs ml-1",title:"Agent has started processing",children:"✓✓"}):l==="delivered"?u.jsx("span",{className:"text-muted-foreground text-xs ml-1",title:"Delivered to agent inbox",children:"✓✓"}):u.jsx("span",{className:"text-muted-foreground text-xs ml-1",title:"Sent",children:"✓"})}function u3({selectedAgentId:t,selectedChatId:a,onSelectAgent:l,onSelectChat:s}){const o=Qn(),{resolve:d}=RS(),h=Mn(),{data:m}=De({queryKey:["activity"],queryFn:Ji,refetchInterval:1e4}),g=[...(m==null?void 0:m.agents)??[]].sort((b,j)=>kb(b.runtimeState,b.clientId)-kb(j.runtimeState,j.clientId)),{data:p}=De({queryKey:["agent-sessions",t],queryFn:()=>t?uc(t):Promise.resolve([]),enabled:!!t,refetchInterval:1e4}),x=st({mutationFn:b=>Xk(b),onSuccess:(b,j)=>{h.invalidateQueries({queryKey:["agent-sessions",j]}),s(j,b.id)}});return u.jsxs("aside",{className:"w-60 shrink-0 flex flex-col overflow-y-auto bg-card",children:[u.jsx("div",{className:"px-3 py-2 border-b border-border",children:u.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Agents"})}),u.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[g.length===0&&u.jsx("div",{className:"px-3 py-6 text-sm text-muted-foreground text-center",children:"No agents"}),g.map(b=>{var w;const j=t===b.agentId;return u.jsxs("div",{children:[u.jsxs("button",{type:"button",onClick:()=>l(j?null:b.agentId),className:je("w-full flex items-start gap-2 px-3 py-1.5 text-left transition-colors",j?"bg-accent":"hover:bg-accent/50"),children:[u.jsx(l3,{runtimeState:b.runtimeState,clientId:b.clientId}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("span",{className:"text-sm font-medium truncate flex-1",children:o(b.agentId)}),u.jsx(s3,{state:b.runtimeState})]}),u.jsx("span",{className:"text-xs text-muted-foreground truncate block",children:b.clientId?((w=d(b.clientId))==null?void 0:w.hostname)??b.clientId.slice(0,8):"disconnected"})]})]}),j&&u.jsxs("div",{className:"pl-5 pr-2 py-1 space-y-0.5",children:[(!p||p.length===0)&&u.jsx("div",{className:"text-xs text-muted-foreground py-1 pl-2",children:"No active sessions"}),p==null?void 0:p.map(C=>u.jsxs("button",{type:"button",onClick:()=>s(b.agentId,C.chatId),className:je("w-full flex items-center gap-1.5 px-2 py-1 rounded text-left text-xs transition-colors",a===C.chatId?"bg-primary/10 text-foreground":"text-muted-foreground hover:bg-accent/50"),children:[u.jsx(kx,{className:"h-3 w-3 shrink-0"}),u.jsxs("span",{className:"truncate flex-1",children:[C.chatId.slice(0,8),"..."]}),u.jsx("span",{className:je("h-1.5 w-1.5 rounded-full shrink-0",C.state==="active"&&"bg-green-500",C.state==="suspended"&&"bg-yellow-500",C.state==="evicted"&&"bg-gray-400"),title:C.state})]},C.chatId)),u.jsxs("button",{type:"button",onClick:()=>x.mutate(b.agentId),disabled:x.isPending,className:"w-full flex items-center gap-1.5 px-2 py-1 rounded text-xs text-muted-foreground hover:bg-accent/50 transition-colors",children:[u.jsx(hl,{className:"h-3 w-3"}),"New Chat"]})]})]},b.agentId)})]})]})}function c3({selectedAgentId:t,selectedChatId:a,onSelectChat:l,onClearChat:s}){return a&&t?u.jsx(h3,{agentId:t,chatId:a,onBack:s}):t?u.jsx(f3,{agentId:t,onSelectChat:l}):u.jsx(d3,{})}function d3(){const t=Qn(),{data:a}=De({queryKey:["overview"],queryFn:OS,refetchInterval:3e4}),{data:l}=De({queryKey:["activity"],queryFn:Ji,refetchInterval:1e4}),{data:s}=De({queryKey:["notifications","feed"],queryFn:()=>qi({limit:20}),refetchInterval:1e4});return u.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[u.jsx("h2",{className:"text-lg font-semibold mb-4",children:"Activity"}),u.jsx("div",{className:"grid grid-cols-4 gap-3 mb-6",children:[{label:"Agents",value:(a==null?void 0:a.agents)??0},{label:"Online",value:(a==null?void 0:a.onlineAgents)??0},{label:"Working",value:(l==null?void 0:l.byState.working)??0},{label:"Blocked",value:(l==null?void 0:l.byState.blocked)??0}].map(o=>u.jsxs("div",{className:"rounded-lg border border-border p-3",children:[u.jsx("div",{className:"text-xs text-muted-foreground",children:o.label}),u.jsx("div",{className:"text-xl font-bold",children:o.value})]},o.label))}),u.jsxs("div",{className:"space-y-1",children:[(!(s!=null&&s.items)||s.items.length===0)&&u.jsx("div",{className:"text-sm text-muted-foreground text-center py-8",children:"No recent activity"}),s==null?void 0:s.items.map(o=>u.jsxs("div",{className:je("flex items-start gap-2 px-3 py-2 rounded-md text-sm",!o.read&&"bg-accent/20"),children:[u.jsx(Lx,{className:je("h-4 w-4 mt-0.5 shrink-0",o.severity==="high"&&"text-red-500",o.severity==="medium"&&"text-yellow-500",o.severity==="low"&&"text-muted-foreground")}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("span",{className:"font-medium",children:o.agentId?t(o.agentId):""})," ",u.jsx("span",{className:"text-muted-foreground",children:o.message})]}),u.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:un(o.createdAt)})]},o.id))]})]})}function f3({agentId:t,onSelectChat:a}){const l=Qn(),{data:s}=De({queryKey:["agent-sessions-all",t],queryFn:()=>uc(t),refetchInterval:1e4}),o=(s==null?void 0:s.filter(m=>m.state==="active"))??[],d=(s==null?void 0:s.length)??0,h=(s==null?void 0:s.filter(m=>m.runtimeState==="error"))??[];return u.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[u.jsx("h2",{className:"text-lg font-semibold mb-1",children:l(t)}),u.jsx("p",{className:"text-sm text-muted-foreground mb-4 font-mono",children:t}),u.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-6",children:[u.jsxs("div",{className:"rounded-lg border border-border p-3",children:[u.jsx("div",{className:"text-xs text-muted-foreground",children:"Active"}),u.jsx("div",{className:"text-xl font-bold",children:o.length})]}),u.jsxs("div",{className:"rounded-lg border border-border p-3",children:[u.jsx("div",{className:"text-xs text-muted-foreground",children:"Total"}),u.jsx("div",{className:"text-xl font-bold",children:d})]}),u.jsxs("div",{className:"rounded-lg border border-border p-3",children:[u.jsx("div",{className:"text-xs text-muted-foreground",children:"Error"}),u.jsx("div",{className:"text-xl font-bold text-red-600",children:h.length})]})]}),u.jsx("h3",{className:"text-sm font-medium mb-2",children:"All Sessions"}),u.jsx("div",{className:"border rounded-lg overflow-hidden",children:u.jsxs("table",{className:"w-full text-sm",children:[u.jsx("thead",{children:u.jsxs("tr",{className:"border-b border-border bg-muted/50",children:[u.jsx("th",{className:"text-left px-3 py-2 font-medium text-muted-foreground",children:"Chat"}),u.jsx("th",{className:"text-left px-3 py-2 font-medium text-muted-foreground",children:"State"}),u.jsx("th",{className:"text-left px-3 py-2 font-medium text-muted-foreground",children:"Messages"}),u.jsx("th",{className:"text-left px-3 py-2 font-medium text-muted-foreground",children:"Last Active"})]})}),u.jsxs("tbody",{children:[(!s||s.length===0)&&u.jsx("tr",{children:u.jsx("td",{colSpan:4,className:"px-3 py-6 text-center text-muted-foreground",children:"No sessions"})}),s==null?void 0:s.map(m=>u.jsxs("tr",{className:"border-b border-border last:border-0 cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>a(t,m.chatId),children:[u.jsxs("td",{className:"px-3 py-2 font-mono text-xs",children:[m.chatId.slice(0,12),"..."]}),u.jsx("td",{className:"px-3 py-2",children:u.jsx(i3,{state:m.state})}),u.jsx("td",{className:"px-3 py-2 text-muted-foreground text-xs",children:m.messageCount}),u.jsx("td",{className:"px-3 py-2 text-muted-foreground text-xs",children:un(m.lastActivityAt)})]},m.chatId))]})]})})]})}function h3({agentId:t,chatId:a,onBack:l}){var w;const s=Mn(),o=Qn(),{agentId:d}=Os(),[h,m]=y.useState(""),g=y.useRef(null),{data:p}=De({queryKey:["chat-messages",a],queryFn:()=>Jk(a,{limit:50}),refetchInterval:5e3}),x=st({mutationFn:C=>Fk(a,C),onSuccess:()=>{m(""),s.invalidateQueries({queryKey:["chat-messages",a]})}}),b=()=>{const C=h.trim();C&&x.mutate(C)},j=((w=p==null?void 0:p.items)==null?void 0:w.length)??0;return y.useEffect(()=>{var C;j>0&&((C=g.current)==null||C.scrollIntoView({behavior:"smooth"}))},[j]),u.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[u.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border shrink-0",children:[u.jsx("button",{type:"button",onClick:l,className:"text-muted-foreground hover:text-foreground",children:u.jsx(Rx,{className:"h-4 w-4"})}),u.jsx("span",{className:"text-sm font-medium",children:o(t)}),u.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:[a.slice(0,8),"..."]})]}),u.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-3",children:[(!(p!=null&&p.items)||p.items.length===0)&&u.jsxs("div",{className:"text-sm text-muted-foreground text-center py-8",children:[u.jsx(F_,{className:"h-8 w-8 mx-auto mb-2 opacity-30"}),"Send a message to start the conversation"]}),[...(p==null?void 0:p.items)??[]].reverse().map(C=>u.jsxs("div",{className:"rounded-md border border-border p-3",children:[u.jsxs("div",{className:"flex items-center justify-between mb-1",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("span",{className:"text-sm font-medium",children:o(C.senderId)}),C.source&&u.jsx($t,{variant:"outline",className:"text-[10px] opacity-70 px-1 py-0",children:C.source})]}),u.jsxs("div",{className:"flex items-center gap-1",children:[u.jsx("span",{className:"text-xs text-muted-foreground",children:un(C.createdAt)}),u.jsx(o3,{msg:C,myAgentId:d})]})]}),u.jsx("div",{className:"text-sm",children:C.format==="text"?u.jsx("p",{className:"whitespace-pre-wrap",children:typeof C.content=="string"?C.content:JSON.stringify(C.content)}):u.jsx("pre",{className:"text-xs bg-muted p-2 rounded overflow-auto max-h-40",children:JSON.stringify(C.content,null,2)})})]},C.id)),u.jsx("div",{ref:g})]}),u.jsxs("div",{className:"shrink-0 border-t border-border p-3 flex gap-2",children:[u.jsx(tt,{placeholder:"Type a message...",value:h,onChange:C=>m(C.target.value),onKeyDown:C=>{C.key==="Enter"&&!C.shiftKey&&(C.preventDefault(),b())},disabled:x.isPending}),u.jsx(de,{size:"icon",onClick:b,disabled:x.isPending||!h.trim(),children:u.jsx(sE,{className:"h-4 w-4"})})]}),x.isError&&u.jsx("p",{className:"text-destructive text-xs px-3 pb-2",children:x.error instanceof Error?x.error.message:"Failed to send"})]})}function m3({selectedAgentId:t,selectedChatId:a}){return a&&t?u.jsx(x3,{agentId:t,chatId:a}):t?u.jsx(b3,{agentId:t}):u.jsx(p3,{})}function p3(){const t=Qn(),{data:a}=De({queryKey:["overview"],queryFn:OS,refetchInterval:3e4}),{data:l}=De({queryKey:["activity"],queryFn:Ji,refetchInterval:1e4}),{data:s}=De({queryKey:["notifications","context"],queryFn:()=>qi({limit:5}),refetchInterval:3e4});return u.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-4",children:[u.jsx("div",{className:"space-y-2",children:[{label:"Clients",value:(l==null?void 0:l.clients)??0},{label:"Agents",value:(a==null?void 0:a.agents)??0},{label:"Online",value:(a==null?void 0:a.onlineAgents)??0},{label:"Working",value:(l==null?void 0:l.byState.working)??0},{label:"Idle",value:(l==null?void 0:l.byState.idle)??0},{label:"Blocked",value:(l==null?void 0:l.byState.blocked)??0},{label:"Error",value:(l==null?void 0:l.byState.error)??0}].map(o=>u.jsxs("div",{className:"flex items-center justify-between text-sm",children:[u.jsx("span",{className:"text-muted-foreground",children:o.label}),u.jsx("span",{className:"font-medium",children:o.value})]},o.label))}),u.jsxs("div",{className:"border-t border-border pt-3",children:[u.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Notifications"}),!(s!=null&&s.items)||s.items.length===0?u.jsx("div",{className:"text-xs text-muted-foreground text-center py-3",children:"No notifications"}):u.jsx("div",{className:"space-y-2",children:s.items.map(o=>u.jsxs("div",{className:je("text-xs",!o.read&&"font-medium"),children:[u.jsx("span",{className:je(o.severity==="high"&&"text-red-500",o.severity==="medium"&&"text-yellow-500"),children:o.agentId?t(o.agentId):"System"})," ",u.jsx("span",{className:"text-muted-foreground",children:o.message})]},o.id))})]})]})}function g3(t){if(!t)return"—";const a=Date.now()-new Date(t).getTime(),l=Math.floor(a/6e4);if(l<60)return`${l}m`;const s=Math.floor(l/60);return s<24?`${s}h ${l%60}m`:`${Math.floor(s/24)}d ${s%24}h`}const v3={agent_error:"Error",session_error:"Error",agent_blocked:"Blocked",agent_stale:"Stale",agent_disconnected:"Disconnected",agent_connected:"Connected",agent_needs_decision:"Decision",session_completed:"Completed"};function y3({notifications:t,agentId:a}){const[,l]=Ex(),s=Mn(),o=st({mutationFn:d=>e0(d),onSuccess:()=>{s.invalidateQueries({queryKey:["notifications","agent",a]})}});return u.jsx("div",{className:"space-y-1",children:t.map(d=>{const h=!!d.chatId,m=v3[d.type]??d.type;return u.jsxs("button",{type:"button",className:je("w-full flex items-start gap-1.5 px-2 py-1.5 rounded text-xs text-left transition-colors",!d.read&&"bg-accent/30",h&&"cursor-pointer hover:bg-accent/50"),onClick:()=>{d.read||o.mutate(d.id),h&&l({a,c:d.chatId})},children:[u.jsx("span",{className:je("h-1.5 w-1.5 rounded-full mt-1 shrink-0",d.read?"bg-transparent":"bg-primary")}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"flex items-center gap-1",children:[u.jsx("span",{className:je("font-medium",d.severity==="high"&&"text-red-500",d.severity==="medium"&&"text-yellow-600",d.severity==="low"&&"text-muted-foreground"),children:m}),u.jsx("span",{className:"text-muted-foreground ml-auto shrink-0",children:un(d.createdAt)})]}),u.jsx("span",{className:"text-muted-foreground line-clamp-2",children:d.message})]})]},d.id)})})}function b3({agentId:t}){var m;const a=Qn(),{resolve:l}=RS(),{data:s}=De({queryKey:["activity"],queryFn:Ji,refetchInterval:1e4}),o=(m=s==null?void 0:s.agents)==null?void 0:m.find(g=>g.agentId===t),d=l(o==null?void 0:o.clientId),{data:h}=De({queryKey:["notifications","agent",t],queryFn:()=>qi({agentId:t,limit:5}),refetchInterval:3e4});return u.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-4",children:[u.jsx("div",{className:"space-y-2",children:[{label:"Name",value:a(t)},{label:"Status",value:(o==null?void 0:o.runtimeState)??"offline"},{label:"Runtime",value:(o==null?void 0:o.runtimeType)??"—"},{label:"Active",value:String((o==null?void 0:o.activeSessions)??0)},{label:"Total",value:String((o==null?void 0:o.totalSessions)??0)}].map(g=>u.jsxs("div",{className:"flex items-center justify-between text-sm",children:[u.jsx("span",{className:"text-muted-foreground",children:g.label}),u.jsx("span",{className:"font-medium",children:g.value})]},g.label))}),u.jsxs("div",{className:"border-t border-border pt-3",children:[u.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Client"}),d?u.jsx("div",{className:"space-y-2",children:[{label:"Hostname",value:d.hostname??"—"},{label:"OS",value:d.os??"—"},{label:"SDK",value:d.sdkVersion??"—"},{label:"Connected",value:g3(d.connectedAt)}].map(g=>u.jsxs("div",{className:"flex items-center justify-between text-sm",children:[u.jsx("span",{className:"text-muted-foreground",children:g.label}),u.jsx("span",{className:"font-medium",children:g.value})]},g.label))}):u.jsx("div",{className:"text-xs text-muted-foreground",children:"disconnected"})]}),u.jsxs("div",{className:"flex flex-col gap-1",children:[u.jsx("a",{href:`/agents/${t}`,className:"text-xs text-primary hover:underline",children:"Manage Agent →"}),u.jsx("a",{href:"/admin#clients",className:"text-xs text-primary hover:underline",children:"Admin: Clients →"})]}),u.jsxs("div",{className:"border-t border-border pt-3",children:[u.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Notifications"}),!(h!=null&&h.items)||h.items.length===0?u.jsx("div",{className:"text-xs text-muted-foreground text-center py-3",children:"No notifications for this agent"}):u.jsx(y3,{notifications:h.items,agentId:t})]})]})}function x3({agentId:t,chatId:a}){const l=Mn(),{data:s}=De({queryKey:["session",t,a],queryFn:()=>uc(t).then(j=>j.find(w=>w.chatId===a)??null),refetchInterval:5e3}),o=st({mutationFn:()=>uk(t,a),onSuccess:()=>l.invalidateQueries({queryKey:["session",t,a]})}),d=st({mutationFn:()=>ck(t,a),onSuccess:()=>l.invalidateQueries({queryKey:["session",t,a]})}),h=st({mutationFn:()=>dk(t,a),onSuccess:()=>l.invalidateQueries({queryKey:["session",t,a]})}),m=(s==null?void 0:s.state)==="active",g=(s==null?void 0:s.state)==="suspended",p=(s==null?void 0:s.state)==="evicted",x=s!=null&&s.startedAt?new Date(s.startedAt):null,b=x?Math.floor((Date.now()-x.getTime())/6e4):null;return u.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden p-3",children:[u.jsx("div",{className:"space-y-2 mb-3",children:[{label:"State",value:(s==null?void 0:s.state)??"—"},{label:"Runtime",value:(s==null?void 0:s.runtimeState)??"—"},{label:"Started",value:s!=null&&s.startedAt?un(s.startedAt):"—"},{label:"Duration",value:b!==null?`${b} min`:"—"},{label:"Messages",value:String((s==null?void 0:s.messageCount)??0)}].map(j=>u.jsxs("div",{className:"flex items-center justify-between text-sm",children:[u.jsx("span",{className:"text-muted-foreground",children:j.label}),u.jsx("span",{className:"font-medium",children:j.value})]},j.label))}),u.jsxs("div",{className:"flex gap-2 mb-3",children:[m&&u.jsx(de,{variant:"outline",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,children:"Suspend"}),g&&u.jsx(de,{variant:"outline",size:"sm",onClick:()=>d.mutate(),disabled:d.isPending,children:"Resume"}),!p&&u.jsx(de,{variant:"destructive",size:"sm",onClick:()=>{window.confirm("Terminate this session?")&&h.mutate()},disabled:h.isPending,children:"Terminate"})]}),u.jsxs("div",{className:"border-t border-border pt-3 flex-1 overflow-y-auto",children:[u.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Session Info"}),u.jsxs("div",{className:"text-xs text-muted-foreground",children:["Chat ID: ",u.jsxs("span",{className:"font-mono",children:[a.slice(0,12),"..."]})]})]})]})}const S3=new AN({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}});function j3(){return u.jsx(TN,{client:S3,children:u.jsx(N_,{children:u.jsx(d_,{children:u.jsxs(Bw,{children:[u.jsx(hr,{path:"/login",element:u.jsx(Pk,{})}),u.jsx(hr,{element:u.jsx(w_,{}),children:u.jsxs(hr,{element:u.jsx(v2,{}),children:[u.jsx(hr,{index:!0,element:u.jsx(n3,{})}),u.jsx(hr,{path:"agents",element:u.jsx(Kk,{})}),u.jsx(hr,{path:"agents/:uuid",element:u.jsx(Bk,{})}),u.jsx(hr,{path:"admin",element:u.jsx(rk,{})})]})})]})})})})}const MS=document.getElementById("root");if(!MS)throw new Error("Root element not found");aN.createRoot(MS).render(u.jsx(y.StrictMode,{children:u.jsx(j3,{})}));
308
+ `):"(no changes)";Oe(Re)},onError:X=>Oe(`Dry run failed: ${X instanceof Error?X.message:String(X)}`)});if(y.useEffect(()=>{if(!w.summary.anyDirty)return;const X=Re=>{Re.preventDefault(),Re.returnValue=""};return window.addEventListener("beforeunload",X),()=>window.removeEventListener("beforeunload",X)},[w.summary.anyDirty]),o.isLoading)return u.jsx("div",{className:"text-muted-foreground",children:"Loading..."});if(o.error)return u.jsxs("div",{className:"text-destructive",children:["Failed to load agent: ",o.error instanceof Error?o.error.message:"Unknown error"]});const fe=o.data;if(!fe)return u.jsx("div",{className:"text-muted-foreground",children:"Agent not found"});const gt=fe.type==="human",Dt=h.data,Ln=((Zn=m.data)==null?void 0:Zn.length)??0,La=!gt&&!(Dt!=null&&Dt.clientId),Xt=!gt&&Dt?!Dt.online&&!!Dt.clientId:!1,vl=fe,Ms=vl.runtimeState??null,cc=vl.runtimeType??null;function Rr(){Ge(!1),$(null),ae(Wf),W("")}function ks(X){$(X.id),ae({...Wf,platform:X.platform,status:X.status}),Ge(!0)}function Ds(X){if(X.preventDefault(),W(""),gt){if(!D.externalUserId)return;le.mutate();return}if(D.platform==="feishu"){if(!xe&&(!D.feishuAppId||!D.feishuAppSecret)){W("App ID and App Secret are required");return}}else if(D.platform==="kael"){if(!xe&&(!D.kaelUserId||!D.kaelProjectId)){W("User ID and Project ID are required");return}}else{const Re=D.credentialsJson.trim();if(!xe&&!Re){W("Credentials are required");return}if(Re)try{JSON.parse(Re)}catch{W("Invalid JSON");return}}xe?Y.mutate():O.mutate()}const yl=O.error??Y.error??le.error,Wi=O.isPending||Y.isPending||le.isPending,dc=kk({activeSessions:Ln,isUnclaimed:La,isOffline:Xt}),Vt=w.draft.mcp.filter(X=>X.status!=="deleted"),fc=w.draft.env.filter(X=>X.status!=="deleted"),eo=w.draft.git.filter(X=>X.status!=="deleted"),to=X=>new Set(Vt.filter(Re=>Re.key!==X).map(Re=>Re.value.name.toLowerCase())),bl=X=>new Set(fc.filter(Re=>Re.key!==X).map(Re=>Re.value.key)),hc=X=>new Set(eo.filter(Re=>Re.key!==X).map(Re=>{const{value:Jt}=Re;return Jt.localPath?Jt.localPath:((Jt.url.split(/[?#]/)[0]??"").split(/[/:]/).filter(Boolean).pop()??"").replace(/\.git$/i,"")}).filter(Boolean));return u.jsxs("div",{className:"space-y-5 pb-24",children:[u.jsxs("div",{className:"flex items-center gap-3",children:[u.jsx(de,{variant:"ghost",size:"icon",onClick:()=>l("/agents"),children:u.jsx(Rx,{className:"h-4 w-4"})}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("h1",{className:"text-2xl font-semibold truncate",children:fe.displayName??fe.name}),u.jsxs("p",{className:"text-xs text-muted-foreground font-mono truncate",children:["@",fe.name??fe.uuid," · ",fe.type]})]}),u.jsxs("div",{className:"relative",ref:Ue,children:[u.jsx(de,{variant:"outline",size:"icon",onClick:()=>_e(X=>!X),title:"More actions",children:u.jsx(Dx,{className:"h-4 w-4"})}),be&&u.jsx("div",{className:"absolute right-0 mt-1 z-40 min-w-48 rounded-md border bg-white shadow-lg text-sm",children:u.jsxs("ul",{className:"py-1",children:[!gt&&fe.status==="active"&&u.jsx("li",{children:u.jsxs("button",{type:"button",onClick:()=>{_e(!1),ee.reset(),ee.mutate()},className:"w-full text-left px-3 py-1.5 hover:bg-gray-50 flex items-center gap-2",disabled:ee.isPending,children:[u.jsx(aE,{className:"h-3.5 w-3.5"}),ee.isPending?"Testing…":"Test connection"]})}),fe.status==="active"?u.jsx("li",{children:u.jsx("button",{type:"button",onClick:()=>{_e(!1),confirm("Suspend this agent? All tokens will be revoked.")&&J.mutate()},className:"w-full text-left px-3 py-1.5 hover:bg-gray-50",children:"Suspend"})}):u.jsx("li",{children:u.jsx("button",{type:"button",onClick:()=>{_e(!1),K.mutate()},className:"w-full text-left px-3 py-1.5 hover:bg-gray-50",children:"Reactivate"})}),u.jsx("li",{className:"border-t",children:u.jsx("a",{href:`#${Jr("prompt")}`,onClick:()=>_e(!1),className:"block px-3 py-1.5 text-xs text-muted-foreground hover:bg-gray-50",children:"Jump to Behavior"})})]})})]})]}),(ee.data||ee.error)&&u.jsx(Gk,{result:ee.data??{status:"error",message:"Failed to reach server"},onDismiss:()=>ee.reset()}),u.jsx(Mk,{agent:fe,cfg:d.data,clientStatus:Dt,runtimeState:Ms,runtimeType:cc,activeSessions:Ln,isHuman:gt}),u.jsx(xk,{agent:fe,onSave:async X=>{await F.mutateAsync(X)}}),!gt&&u.jsxs($k,{loaded:!!d.data,loading:d.isLoading,error:d.error?String(d.error):null,version:((Qt=d.data)==null?void 0:Qt.version)??null,dirty:w.summary.anyDirty,children:[u.jsx("div",{id:Jr("prompt"),children:u.jsx(Ek,{value:w.draft.promptAppend,baseline:((ro=d.data)==null?void 0:ro.payload.prompt.append)??"",onChange:w.setPromptAppend,onRevert:w.revertPrompt,disabled:fe.status!=="active"})}),u.jsx("div",{id:Jr("model"),children:u.jsx(_k,{value:w.draft.model,baseline:((lo=d.data)==null?void 0:lo.payload.model)??"",onChange:w.setModel,onRevert:w.revertModel,disabled:fe.status!=="active"})}),u.jsx("div",{id:Jr("mcp"),children:u.jsx(jk,{items:w.draft.mcp,otherNames:to,onAdd:w.addMcp,onUpdate:w.updateMcp,onDelete:w.deleteMcp,onUndoDelete:w.undoDeleteMcp,disabled:fe.status!=="active"})}),u.jsx("div",{id:Jr("env"),children:u.jsx(gk,{items:w.draft.env,otherKeys:bl,onAdd:w.addEnv,onUpdate:w.updateEnv,onDelete:w.deleteEnv,onUndoDelete:w.undoDeleteEnv,disabled:fe.status!=="active"})}),u.jsx("div",{id:Jr("git"),children:u.jsx(yk,{items:w.draft.git,otherPaths:hc,onAdd:w.addGit,onUpdate:w.updateGit,onDelete:w.deleteGit,onUndoDelete:w.undoDeleteGit,disabled:fe.status!=="active"})}),me&&u.jsx("pre",{className:"whitespace-pre-wrap rounded border bg-gray-50 p-2 text-xs",children:me})]}),u.jsxs(cl,{children:[u.jsxs(Ns,{className:"flex flex-row items-center justify-between",children:[u.jsxs(ws,{className:"flex items-center gap-2 text-base",children:[gt?u.jsx(G_,{className:"h-4 w-4"}):u.jsx(U_,{className:"h-4 w-4"}),"Platform Bindings"]}),u.jsxs(de,{size:"sm",variant:"outline",onClick:()=>Ge(!0),children:[u.jsx(hl,{className:"h-4 w-4 mr-2"}),gt?"Bind User":"Bind Bot"]})]}),u.jsx(dl,{children:gt?u.jsxs(Oa,{children:[u.jsx(Ra,{children:u.jsxs(at,{children:[u.jsx(ye,{children:"Platform"}),u.jsx(ye,{children:"External User ID"}),u.jsx(ye,{children:"Display Name"}),u.jsx(ye,{children:"Bound Via"}),u.jsx(ye,{children:"Created"}),u.jsx(ye,{className:"w-16"})]})}),u.jsx(Ma,{children:j.length===0?u.jsx(at,{children:u.jsx(ve,{colSpan:6,className:"text-center py-4 text-muted-foreground",children:"No platform bindings"})}):j.map(X=>u.jsxs(at,{children:[u.jsx(ve,{children:u.jsx($t,{variant:"secondary",children:X.platform})}),u.jsx(ve,{className:"font-mono text-sm",children:X.externalUserId}),u.jsx(ve,{children:X.displayName??"—"}),u.jsx(ve,{children:u.jsx($t,{variant:"outline",children:X.boundVia??"—"})}),u.jsx(ve,{className:"text-muted-foreground",children:un(X.createdAt)}),u.jsx(ve,{children:u.jsx(de,{variant:"ghost",size:"icon",onClick:()=>{confirm("Remove this binding?")&&ue.mutate(X.id)},disabled:ue.isPending,children:u.jsx(Zi,{className:"h-4 w-4"})})})]},X.id))})]}):u.jsxs(Oa,{children:[u.jsx(Ra,{children:u.jsxs(at,{children:[u.jsx(ye,{children:"Platform"}),u.jsx(ye,{children:"Status"}),u.jsx(ye,{children:"Connection"}),u.jsx(ye,{children:"Created"}),u.jsx(ye,{className:"w-24"})]})}),u.jsx(Ma,{children:b.length===0?u.jsx(at,{children:u.jsx(ve,{colSpan:5,className:"text-center py-4 text-muted-foreground",children:"No platform bindings"})}):b.map(X=>{const Re=x==null?void 0:x.find(Mr=>Mr.configId===X.id),Jt=X.platform==="kael"?X.status==="active":!!(Re!=null&&Re.connected);return u.jsxs(at,{children:[u.jsx(ve,{children:u.jsx($t,{variant:"secondary",children:X.platform})}),u.jsx(ve,{children:u.jsx($t,{variant:X.status==="active"?"default":"destructive",children:X.status})}),u.jsx(ve,{children:u.jsxs("span",{className:"flex items-center gap-1.5",children:[u.jsx("span",{className:je("inline-block h-2 w-2 rounded-full",Jt?"bg-green-500":"bg-gray-300")}),u.jsx("span",{className:"text-xs text-muted-foreground",children:Jt?"Online":"Offline"})]})}),u.jsx(ve,{className:"text-muted-foreground",children:un(X.createdAt)}),u.jsx(ve,{children:u.jsxs("div",{className:"flex gap-1",children:[u.jsx(de,{variant:"ghost",size:"icon",onClick:()=>ks(X),title:"Edit",children:"…"}),u.jsx(de,{variant:"ghost",size:"icon",onClick:()=>{confirm("Remove this bot binding?")&&te.mutate(X.id)},disabled:te.isPending,title:"Delete",children:u.jsx(Zi,{className:"h-4 w-4"})})]})})]},X.id)})})]})})]}),u.jsx(fk,{agent:fe,suspendPending:J.isPending,reactivatePending:K.isPending,deletePending:k.isPending,onSuspend:()=>{confirm("Suspend this agent? Runtime binds and HTTP calls will be refused.")&&J.mutate()},onReactivate:()=>K.mutate(),onDelete:()=>k.mutate()}),!gt&&u.jsx(Ak,{summary:w.summary,saveHint:dc,conflictMessage:_,errorMessage:C,saving:Q.isPending,onSave:()=>Q.mutate(),onDiscard:()=>{(!w.summary.anyDirty||confirm("Discard all unsaved changes?"))&&(w.resetAll(),N(null),R(null))},onReloadRemote:q,onJumpTo:B}),!gt&&w.summary.anyDirty&&u.jsx("div",{className:"text-xs text-muted-foreground",children:u.jsx("button",{type:"button",onClick:()=>pt.mutate(),className:"underline hover:text-gray-900",disabled:pt.isPending,children:pt.isPending?"Computing dry-run…":"Preview server-side diff"})}),u.jsx(Da,{open:jt,onOpenChange:X=>X?Ge(!0):Rr(),children:u.jsxs(na,{children:[u.jsx(Ua,{children:u.jsx(aa,{children:gt?"Bind External User":xe?"Edit Bot Binding":"Bind Bot"})}),u.jsxs("form",{onSubmit:Ds,className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"binding-platform",children:"Platform"}),u.jsx("select",{id:"binding-platform",value:D.platform,onChange:X=>ae({...D,platform:X.target.value}),disabled:!!xe,className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50",children:qk.map(X=>u.jsx("option",{value:X,children:X},X))})]}),gt?u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"binding-ext-id",children:"External User ID"}),u.jsx(tt,{id:"binding-ext-id",value:D.externalUserId,onChange:X=>ae({...D,externalUserId:X.target.value}),placeholder:"ou_xxxxxxxx...",className:"font-mono",required:!0})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"binding-name",children:"Display Name (optional)"}),u.jsx(tt,{id:"binding-name",value:D.displayName,onChange:X=>ae({...D,displayName:X.target.value})})]})]}):u.jsxs(u.Fragment,{children:[D.platform==="feishu"?u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"space-y-2",children:[u.jsxs($e,{htmlFor:"feishu-app-id",children:["App ID",xe?" — leave empty to keep existing":""]}),u.jsx(tt,{id:"feishu-app-id",value:D.feishuAppId,onChange:X=>ae({...D,feishuAppId:X.target.value}),placeholder:"cli_xxxxxxxx",className:"font-mono",autoComplete:"off"})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsxs($e,{htmlFor:"feishu-app-secret",children:["App Secret",xe?" — leave empty to keep existing":""]}),u.jsx(tt,{id:"feishu-app-secret",type:"password",autoComplete:"new-password",value:D.feishuAppSecret,onChange:X=>ae({...D,feishuAppSecret:X.target.value}),placeholder:"••••••••"})]})]}):D.platform==="kael"?u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"space-y-2",children:[u.jsxs($e,{htmlFor:"kael-user-id",children:["User ID",xe?" — leave empty to keep existing":""]}),u.jsx(tt,{id:"kael-user-id",value:D.kaelUserId,onChange:X=>ae({...D,kaelUserId:X.target.value}),placeholder:"user_xxxxxxxx",className:"font-mono",autoComplete:"off"})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsxs($e,{htmlFor:"kael-project-id",children:["Project ID",xe?" — leave empty to keep existing":""]}),u.jsx(tt,{id:"kael-project-id",value:D.kaelProjectId,onChange:X=>ae({...D,kaelProjectId:X.target.value}),placeholder:"proj_xxxxxxxx",className:"font-mono",autoComplete:"off"})]}),!xe&&u.jsx("p",{className:"text-sm text-muted-foreground",children:"Agent Token will be created automatically when you save."})]}):u.jsxs("div",{className:"space-y-2",children:[u.jsxs($e,{htmlFor:"binding-creds",children:["Credentials (JSON)",xe?" — leave empty to keep existing":""]}),u.jsx("textarea",{id:"binding-creds",value:D.credentialsJson,onChange:X=>ae({...D,credentialsJson:X.target.value}),rows:4,className:"flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm font-mono focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",placeholder:'{"bot_token": "xoxb-...", "signing_secret": "..."}'})]}),ze&&u.jsx("p",{className:"text-sm text-destructive",children:ze}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"binding-status",children:"Status"}),u.jsxs("select",{id:"binding-status",value:D.status,onChange:X=>ae({...D,status:X.target.value}),className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:[u.jsx("option",{value:"active",children:"active"}),u.jsx("option",{value:"inactive",children:"inactive"})]})]})]}),yl instanceof Error&&u.jsx("div",{className:"text-sm text-destructive",children:yl.message}),u.jsx(ta,{children:u.jsx(de,{type:"submit",disabled:Wi,children:Wi?"Saving...":xe?"Update":"Create"})})]})]})})]})}function $k(t){return u.jsxs("section",{className:"space-y-3",children:[u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsx("h2",{className:"text-base font-semibold",children:"Behavior"}),u.jsxs("div",{className:"text-xs text-muted-foreground",children:[t.version!=null&&u.jsxs("span",{children:["v",t.version]}),t.dirty&&u.jsx("span",{className:"ml-2 text-amber-700",children:"· draft"})]})]}),t.loading&&u.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading configuration…"}),t.error&&u.jsxs("div",{className:"text-sm text-destructive",children:["Failed to load configuration: ",t.error]}),t.loaded&&u.jsx("div",{className:"space-y-3",children:t.children})]})}const Wf={platform:"feishu",feishuAppId:"",feishuAppSecret:"",credentialsJson:"{}",status:"active",externalUserId:"",displayName:"",kaelUserId:"",kaelProjectId:"",kaelAgentToken:""};function Rb(t){if(t.platform==="feishu"){if(!t.feishuAppId&&!t.feishuAppSecret)return null;if(!t.feishuAppId||!t.feishuAppSecret)throw new Error("Both App ID and App Secret are required");return{app_id:t.feishuAppId,app_secret:t.feishuAppSecret}}if(t.platform==="kael"){if(!t.kaelUserId&&!t.kaelProjectId)return null;if(!t.kaelUserId||!t.kaelProjectId)throw new Error("User ID and Project ID are required");return{kaelUserId:t.kaelUserId,kaelProjectId:t.kaelProjectId}}const a=t.credentialsJson.trim();return a?JSON.parse(a):null}const Hk={success:"Connected",timeout:"Timed out",offline:"Offline",stale:"Stale",error:"Error"},Qk={connected:{icon:"●",color:"text-green-500",label:"Connected"},stale:{icon:"◐",color:"text-yellow-500",label:"Stale"},disconnected:{icon:"○",color:"text-gray-400",label:"Disconnected"}};function Gk({result:t,onDismiss:a}){const l={success:"border-l-green-500",timeout:"border-l-yellow-500",offline:"border-l-gray-400",stale:"border-l-yellow-500",error:"border-l-red-500"}[t.status],s=t.status==="success"?"default":t.status==="timeout"||t.status==="stale"?"secondary":"destructive",o=t.connection,d=o?Qk[o.health]:null;return u.jsx(cl,{className:je("border-l-4",l),children:u.jsx(dl,{className:"pt-4",children:u.jsxs("div",{className:"flex items-start justify-between",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx($t,{variant:s,children:Hk[t.status]}),t.responseTime!=null&&u.jsxs("span",{className:"text-xs text-muted-foreground",children:[(t.responseTime/1e3).toFixed(1),"s"]})]}),t.message&&u.jsx("p",{className:"text-sm text-muted-foreground",children:t.message}),o&&u.jsxs("div",{className:"text-xs space-y-1 border-t pt-2 mt-1",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[d&&u.jsxs("span",{className:d.color,children:[d.icon," ",d.label]}),o.runtimeState&&u.jsxs("span",{className:"text-muted-foreground",children:["runtime: ",o.runtimeState]})]}),o.client?u.jsxs("div",{className:"text-muted-foreground",children:["Client: ",o.client.hostname??o.client.id,o.client.os&&` (${o.client.os})`,o.client.sdkVersion&&` · SDK ${o.client.sdkVersion}`]}):u.jsx("div",{className:"text-muted-foreground",children:"No client bound"}),o.lastSeenAt&&u.jsxs("div",{className:"text-muted-foreground",children:["Last seen: ",new Date(o.lastSeenAt).toLocaleString()]})]}),t.responseContent&&u.jsx("p",{className:"text-sm mt-2 whitespace-pre-wrap bg-muted rounded p-2 max-h-40 overflow-auto",children:t.responseContent})]}),u.jsx(de,{variant:"ghost",size:"sm",onClick:a,children:"Dismiss"})]})})})}const Ik=Object.values(G0);function Vk(t){var xe,$;const{open:a,onOpenChange:l,onSubmit:s,isPending:o,error:d,mode:h}=t,m=h==="edit"?t.agent:void 0,{memberId:g,role:p}=Os(),x=p==="admin",[b,j]=y.useState(""),[w,C]=y.useState("personal_assistant"),[N,_]=y.useState(""),[R,Q]=y.useState(""),[q,B]=y.useState(""),[F,J]=y.useState(""),K=h==="create"&&w!=="human",k=De({queryKey:["clients-for-pin"],queryFn:Ih,enabled:a&&K}),ee=w==="human",be=De({queryKey:["agents-for-delegate"],queryFn:async()=>(await Ju({limit:100})).items.filter(ae=>ae.type==="personal_assistant"&&ae.status==="active"),enabled:a&&ee}),_e=De({queryKey:["members-for-manager"],queryFn:sm,enabled:a&&h==="create"&&x}),Ue=y.useMemo(()=>{var ze;const D=k.data??[];if(!K||!x)return D;if(!q)return[];const ae=(ze=_e.data)==null?void 0:ze.find(W=>W.id===q);return ae?D.filter(W=>(W.userId??null)===ae.userId):[]},[k.data,x,q,_e.data,K]);y.useEffect(()=>{a&&(m?(j(m.name??""),C(m.type),_(m.displayName??""),Q(m.delegateMention??""),B(m.managerId??"")):(j(""),C("personal_assistant"),_(""),Q(""),B(x?"":g??""),J("")))},[a,m,x,g]);const jt=D=>{D.preventDefault(),s({name:h==="create"&&b?b:void 0,type:w,displayName:N||null,delegateMention:R||null,managerId:q||null,clientId:F||null})},Ge=h==="edit";return u.jsx(Da,{open:a,onOpenChange:l,children:u.jsxs(na,{children:[u.jsx(Ua,{children:u.jsx(aa,{children:Ge?"Edit Agent":"New Agent"})}),u.jsxs("form",{onSubmit:jt,className:"space-y-4",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"agent-name",children:"Name"}),Ge?u.jsx(tt,{id:"agent-name",value:b,disabled:!0,className:"font-mono"}):u.jsx(tt,{id:"agent-name",value:b,onChange:D=>j(D.target.value),placeholder:"Leave empty to auto-generate",pattern:"^[a-z0-9_-]*$",title:"Only lowercase alphanumeric, hyphens, and underscores",className:"font-mono"})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"agent-type",children:"Type"}),u.jsx("select",{id:"agent-type",value:w,onChange:D=>{const ae=D.target.value;C(ae),ae!=="human"&&Q(""),J("")},disabled:Ge,className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50",children:Ik.map(D=>u.jsx("option",{value:D,children:D},D))})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"agent-display-name",children:"Display Name"}),u.jsx(tt,{id:"agent-display-name",value:N,onChange:D=>_(D.target.value),placeholder:"Optional",maxLength:200})]}),h==="create"&&x&&u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"agent-manager",children:"Manager"}),u.jsxs("select",{id:"agent-manager",value:q,onChange:D=>{B(D.target.value),J("")},className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:[u.jsx("option",{value:"",children:"Select a member…"}),(xe=_e.data)==null?void 0:xe.map(D=>u.jsxs("option",{value:D.id,children:[D.displayName," (",D.role,")"]},D.id))]}),u.jsx("p",{className:"text-xs text-muted-foreground",children:"Non-human agents must pin a client belonging to this user."})]}),ee&&u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"agent-delegate",children:"Delegate Mention"}),u.jsxs("select",{id:"agent-delegate",value:R,onChange:D=>Q(D.target.value),className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:[u.jsx("option",{value:"",children:"None"}),($=be.data)==null?void 0:$.map(D=>u.jsx("option",{value:D.uuid,children:D.displayName?`${D.displayName} (${D.name??D.uuid})`:D.name??D.uuid},D.uuid))]}),u.jsx("p",{className:"text-xs text-muted-foreground",children:"The personal assistant that acts on behalf of this agent"})]}),K&&u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"agent-client",children:"Client"}),Ue.length>0?u.jsxs("select",{id:"agent-client",value:F,onChange:D=>J(D.target.value),className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:[u.jsx("option",{value:"",children:"Select a client…"}),Ue.map(D=>u.jsx("option",{value:D.id,children:D.hostname??D.id.slice(0,12)},D.id))]}):u.jsx("p",{className:"text-xs text-muted-foreground",children:x&&!q?"Pick a manager first to see their clients.":"No eligible clients. Run `first-tree-hub client connect` on the target machine to register one."}),u.jsx("p",{className:"text-xs text-muted-foreground",children:"Pinned at creation — clientId is immutable in this milestone. Move = delete + recreate."})]}),d&&u.jsx("div",{className:"text-sm text-destructive",children:d.message}),u.jsx(ta,{children:u.jsx(de,{type:"submit",disabled:o,children:o?"Saving...":Ge?"Save":"Create"})})]})]})})}const Yk=Object.values(G0);function Mb(t){return[...t].sort((a,l)=>{const s=(a.name??a.displayName??"").toLowerCase(),o=(l.name??l.displayName??"").toLowerCase();return s.localeCompare(o)})}function Kk(){const t=Ar(),a=Mn(),{memberId:l}=Os(),[s,o]=y.useState(),[d,h]=y.useState(""),[m,g]=y.useState(!1),[p,x]=y.useState(null),[b,j]=y.useState(!1),w=Qn(),C=zS(),{data:N,isLoading:_,error:R}=De({queryKey:["agents",s,d],queryFn:()=>Ju({limit:100,cursor:s,type:d||void 0})}),{myAgents:Q,teamAgents:q}=y.useMemo(()=>{if(!(N!=null&&N.items))return{myAgents:[],teamAgents:[]};const k=[],ee=[];for(const be of N.items)l&&be.managerId===l?k.push(be):ee.push(be);return{myAgents:Mb(k),teamAgents:Mb(ee)}},[N,l]),B=st({mutationFn:async k=>await i2({name:k.name,type:k.type,displayName:k.displayName??void 0,delegateMention:k.delegateMention??void 0,managerId:k.managerId??void 0,clientId:k.clientId??void 0}),onSuccess:k=>{if(g(!1),a.invalidateQueries({queryKey:["agents"]}),a.invalidateQueries({queryKey:["activity"]}),k.type==="human"){t(`/agents/${k.uuid}`);return}x(k),j(!1)}});function F(k){const be=k.runtimeState,_e={idle:"bg-green-500",working:"bg-blue-500",error:"bg-red-500"};return u.jsxs(at,{className:"cursor-pointer",onClick:()=>t(`/agents/${k.uuid}`),children:[u.jsx(ve,{className:"font-mono text-sm",children:k.name}),u.jsx(ve,{children:k.displayName??"—"}),u.jsx(ve,{children:u.jsx($t,{variant:"secondary",children:k.type})}),u.jsx(ve,{className:"font-mono text-sm text-muted-foreground",children:k.delegateMention?w(k.delegateMention):"—"}),u.jsx(ve,{className:"text-sm text-muted-foreground",children:C(k.managerId)}),u.jsx(ve,{children:be?u.jsxs("span",{className:"flex items-center gap-1.5",children:[u.jsx("span",{className:je("inline-block h-2 w-2 rounded-full",_e[be]??"bg-gray-300")}),u.jsx("span",{className:"text-xs text-muted-foreground",children:be})]}):u.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-gray-300",title:"not running"})}),u.jsx(ve,{children:u.jsx($t,{variant:k.status==="active"?"default":"destructive",children:k.status})}),u.jsx(ve,{className:"text-muted-foreground",children:un(k.createdAt)})]},k.uuid)}const J=p?`first-tree-hub agent add ${p.name??p.uuid} --agent-id ${p.uuid}`:"",K=()=>{navigator.clipboard.writeText(J),j(!0),setTimeout(()=>j(!1),2e3)};return u.jsxs("div",{className:"space-y-8",children:[u.jsxs("div",{className:"flex items-center gap-4",children:[u.jsx("h1",{className:"text-2xl font-semibold",children:"Agents"}),u.jsxs("select",{value:d,onChange:k=>{h(k.target.value),o(void 0)},className:"h-8 rounded-md border border-input bg-transparent px-2 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",children:[u.jsx("option",{value:"",children:"All types"}),Yk.map(k=>u.jsx("option",{value:k,children:k},k))]})]}),_?u.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):R?u.jsxs("div",{className:"text-center py-8 text-destructive",children:["Failed to load agents: ",R instanceof Error?R.message:"Unknown error"]}):u.jsxs(u.Fragment,{children:[u.jsxs("section",{children:[u.jsxs("div",{className:"flex items-center justify-between mb-3",children:[u.jsx("h2",{className:"text-lg font-medium",children:"My Agents"}),u.jsxs(de,{size:"sm",onClick:()=>g(!0),children:[u.jsx(hl,{className:"h-4 w-4 mr-2"}),"New Agent"]})]}),u.jsx("div",{className:"border rounded-lg",children:u.jsxs(Oa,{children:[u.jsx(Ra,{children:u.jsxs(at,{children:[u.jsx(ye,{children:"Name"}),u.jsx(ye,{children:"Display Name"}),u.jsx(ye,{children:"Type"}),u.jsx(ye,{children:"Delegate"}),u.jsx(ye,{children:"Owner"}),u.jsx(ye,{children:"Runtime"}),u.jsx(ye,{children:"Status"}),u.jsx(ye,{children:"Created"})]})}),u.jsx(Ma,{children:Q.length===0?u.jsx(at,{children:u.jsx(ve,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"No agents yet — create one to get started"})}):Q.map(k=>F(k))})]})})]}),q.length>0&&u.jsxs("section",{children:[u.jsx("h2",{className:"text-lg font-medium mb-3",children:"Team Agents"}),u.jsx("div",{className:"border rounded-lg",children:u.jsxs(Oa,{children:[u.jsx(Ra,{children:u.jsxs(at,{children:[u.jsx(ye,{children:"Name"}),u.jsx(ye,{children:"Display Name"}),u.jsx(ye,{children:"Type"}),u.jsx(ye,{children:"Delegate"}),u.jsx(ye,{children:"Owner"}),u.jsx(ye,{children:"Runtime"}),u.jsx(ye,{children:"Status"}),u.jsx(ye,{children:"Created"})]})}),u.jsx(Ma,{children:q.map(k=>F(k))})]})})]})]}),(N==null?void 0:N.nextCursor)&&u.jsx("div",{className:"flex justify-end",children:u.jsx(de,{variant:"outline",onClick:()=>o(N.nextCursor??void 0),children:"Next Page"})}),u.jsx(Vk,{mode:"create",open:m,onOpenChange:g,onSubmit:k=>B.mutate(k),isPending:B.isPending,error:B.error instanceof Error?B.error:null}),u.jsx(Da,{open:p!==null,onOpenChange:k=>{if(!k){const ee=p==null?void 0:p.uuid;x(null),ee&&t(`/agents/${ee}`)}},children:u.jsxs(na,{children:[u.jsx(Ua,{children:u.jsx(aa,{children:"Agent Created"})}),u.jsxs("div",{className:"space-y-3",children:[u.jsx("p",{className:"text-sm text-muted-foreground",children:"Run this on the pinned client machine to register a local alias; the client connects with your JWT, not a per-agent token."}),u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("code",{className:"flex-1 bg-muted rounded-md px-3 py-2 text-xs font-mono break-all select-all",children:J}),u.jsx(de,{variant:"outline",size:"icon",className:"shrink-0",onClick:K,children:b?u.jsx(Mx,{className:"h-4 w-4 text-green-600"}):u.jsx(Hh,{className:"h-4 w-4"})})]})]}),u.jsx(ta,{children:u.jsx(de,{onClick:()=>{const k=p==null?void 0:p.uuid;x(null),k&&t(`/agents/${k}`)},children:"Done"})})]})})]})}function Pk(){const{isAuthenticated:t,login:a}=Os(),[l,s]=y.useState(""),[o,d]=y.useState(""),[h,m]=y.useState(null),[g,p]=y.useState(!1);if(t)return u.jsx(bx,{to:"/",replace:!0});const x=async b=>{b.preventDefault(),m(null),p(!0);try{await a(l,o)}catch(j){m(j instanceof Error?j.message:"Login failed")}finally{p(!1)}};return u.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:u.jsxs(cl,{className:"w-full max-w-sm",children:[u.jsxs(Ns,{className:"text-center",children:[u.jsx(ws,{className:"text-2xl",children:"First Tree"}),u.jsx(l0,{children:"Sign in to your workspace"})]}),u.jsx(dl,{children:u.jsxs("form",{onSubmit:x,className:"space-y-4",children:[h&&u.jsx("div",{className:"rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:h}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"username",children:"Username"}),u.jsx(tt,{id:"username",value:l,onChange:b=>s(b.target.value),required:!0,autoFocus:!0})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx($e,{htmlFor:"password",children:"Password"}),u.jsx(tt,{id:"password",type:"password",value:o,onChange:b=>d(b.target.value),required:!0})]}),u.jsx(de,{type:"submit",className:"w-full",disabled:g,children:g?"Signing in...":"Sign in"})]})})]})})}function Fk(t,a){return we.post(`/admin/chats/${encodeURIComponent(t)}/messages`,{format:"text",content:a})}function Xk(t){return we.post(`/admin/agents/${encodeURIComponent(t)}/chats`,{})}function Jk(t,a){const l=new URLSearchParams;l.set("limit",String(a.limit)),a!=null&&a.cursor&&l.set("cursor",a.cursor);const s=l.toString();return we.get(`/admin/chats/${encodeURIComponent(t)}/messages${s?`?${s}`:""}`)}function OS(){return we.get("/admin/overview")}const Wk=2e3,e3=3e4;function t3(t){const{onMessage:a,enabled:l=!0}={},s=Mn(),o=y.useRef(null),d=y.useRef(0),h=y.useRef(null),m=y.useRef(!1),g=y.useRef(a);g.current=a;const p=y.useRef(s);p.current=s,y.useEffect(()=>{if(!l)return;m.current=!1;function x(){const b=Bh();if(!(b!=null&&b.accessToken))return;const w=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws/admin?token=${b.accessToken}`,C=new WebSocket(w);o.current=C,C.onmessage=N=>{var _;try{const R=JSON.parse(N.data);(_=g.current)==null||_.call(g,R),R.type==="notification"?p.current.invalidateQueries({queryKey:["notifications"]}):R.type==="session:state"&&(p.current.invalidateQueries({queryKey:["activity"]}),p.current.invalidateQueries({queryKey:["sessions"]}))}catch{}},C.onopen=()=>{d.current=0},C.onclose=()=>{if(o.current=null,!m.current){d.current++;const N=Math.min(Wk*2**(d.current-1),e3);h.current=setTimeout(()=>{h.current=null,m.current||x()},N)}}}return x(),()=>{m.current=!0,h.current&&(clearTimeout(h.current),h.current=null),o.current&&(o.current.close(1e3,"unmount"),o.current=null)}},[l])}function RS(){const{data:t}=De({queryKey:["clients"],queryFn:Ih,staleTime:1e4,refetchInterval:1e4});return y.useMemo(()=>{const a=t??[],l=new Map;for(const s of a)l.set(s.id,s);return{resolve:s=>s?l.get(s)??null:null,clients:a,connectedClients:a.filter(s=>s.status==="connected")}},[t])}function n3(){const[t,a]=Ex(),l=t.get("a"),s=t.get("c"),[o,d]=y.useState(!0);t3();const h=y.useCallback(p=>{a(p?{a:p}:{})},[a]),m=y.useCallback((p,x)=>{a({a:p,c:x})},[a]),g=y.useCallback(()=>{l&&a({a:l})},[l,a]);return u.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[u.jsx(u3,{selectedAgentId:l,selectedChatId:s,onSelectAgent:h,onSelectChat:m}),u.jsx("div",{className:"flex-1 flex flex-col overflow-hidden border-x border-border",children:u.jsx(c3,{selectedAgentId:l,selectedChatId:s,onSelectChat:m,onClearChat:g})}),o?u.jsxs("div",{className:"w-80 shrink-0 flex flex-col overflow-hidden",children:[u.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border",children:[u.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:s?"Session":l?"Agent Info":"Dashboard"}),u.jsx("button",{type:"button",onClick:()=>d(!1),className:"text-muted-foreground hover:text-foreground",children:u.jsx(J_,{className:"h-4 w-4"})})]}),u.jsx(m3,{selectedAgentId:l,selectedChatId:s})]}):u.jsx("div",{className:"shrink-0 border-l border-border flex items-start pt-2 px-1",children:u.jsx("button",{type:"button",onClick:()=>d(!0),className:"text-muted-foreground hover:text-foreground p-1",children:u.jsx(eE,{className:"h-4 w-4"})})})]})}const a3={error:0,blocked:1,working:2,idle:3};function kb(t,a){return a?t?a3[t]??4:4:5}const r3={idle:"bg-green-500",working:"bg-green-500 animate-pulse",blocked:"bg-yellow-500",error:"bg-red-500"};function l3({runtimeState:t,clientId:a}){if(!a||!t)return u.jsx("span",{className:"h-2 w-2 rounded-full bg-gray-400 shrink-0 mt-1.5"});const l=r3[t]??"bg-gray-400";return u.jsx("span",{className:`h-2 w-2 rounded-full ${l} shrink-0 mt-1.5`})}function s3({state:t}){if(!t)return u.jsx("span",{className:"text-xs text-muted-foreground",children:"offline"});const a={idle:"text-green-600",working:"text-blue-600",blocked:"text-yellow-600",error:"text-red-600"};return u.jsx("span",{className:je("text-xs font-medium",a[t]??"text-muted-foreground"),children:t})}function i3({state:t}){const a={active:"border-green-500/50 text-green-600 bg-green-500/10",suspended:"border-yellow-500/50 text-yellow-600 bg-yellow-500/10",evicted:"border-muted text-muted-foreground"};return u.jsx($t,{variant:"outline",className:je("text-xs",a[t]),children:t})}function o3({msg:t,myAgentId:a}){if(!a||t.senderId!==a)return null;const l=t.deliveryStatus??"sent";return l==="acked"?u.jsx("span",{className:"text-blue-500 text-xs ml-1",title:"Agent has started processing",children:"✓✓"}):l==="delivered"?u.jsx("span",{className:"text-muted-foreground text-xs ml-1",title:"Delivered to agent inbox",children:"✓✓"}):u.jsx("span",{className:"text-muted-foreground text-xs ml-1",title:"Sent",children:"✓"})}function u3({selectedAgentId:t,selectedChatId:a,onSelectAgent:l,onSelectChat:s}){const o=Qn(),{resolve:d}=RS(),h=Mn(),{data:m}=De({queryKey:["activity"],queryFn:Ji,refetchInterval:1e4}),g=[...(m==null?void 0:m.agents)??[]].sort((b,j)=>kb(b.runtimeState,b.clientId)-kb(j.runtimeState,j.clientId)),{data:p}=De({queryKey:["agent-sessions",t],queryFn:()=>t?uc(t):Promise.resolve([]),enabled:!!t,refetchInterval:1e4}),x=st({mutationFn:b=>Xk(b),onSuccess:(b,j)=>{h.invalidateQueries({queryKey:["agent-sessions",j]}),s(j,b.id)}});return u.jsxs("aside",{className:"w-60 shrink-0 flex flex-col overflow-y-auto bg-card",children:[u.jsx("div",{className:"px-3 py-2 border-b border-border",children:u.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Agents"})}),u.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[g.length===0&&u.jsx("div",{className:"px-3 py-6 text-sm text-muted-foreground text-center",children:"No agents"}),g.map(b=>{var w;const j=t===b.agentId;return u.jsxs("div",{children:[u.jsxs("button",{type:"button",onClick:()=>l(j?null:b.agentId),className:je("w-full flex items-start gap-2 px-3 py-1.5 text-left transition-colors",j?"bg-accent":"hover:bg-accent/50"),children:[u.jsx(l3,{runtimeState:b.runtimeState,clientId:b.clientId}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("span",{className:"text-sm font-medium truncate flex-1",children:o(b.agentId)}),u.jsx(s3,{state:b.runtimeState})]}),u.jsx("span",{className:"text-xs text-muted-foreground truncate block",children:b.clientId?((w=d(b.clientId))==null?void 0:w.hostname)??b.clientId.slice(0,8):"disconnected"})]})]}),j&&u.jsxs("div",{className:"pl-5 pr-2 py-1 space-y-0.5",children:[(!p||p.length===0)&&u.jsx("div",{className:"text-xs text-muted-foreground py-1 pl-2",children:"No active sessions"}),p==null?void 0:p.map(C=>u.jsxs("button",{type:"button",onClick:()=>s(b.agentId,C.chatId),className:je("w-full flex items-center gap-1.5 px-2 py-1 rounded text-left text-xs transition-colors",a===C.chatId?"bg-primary/10 text-foreground":"text-muted-foreground hover:bg-accent/50"),children:[u.jsx(kx,{className:"h-3 w-3 shrink-0"}),u.jsxs("span",{className:"truncate flex-1",children:[C.chatId.slice(0,8),"..."]}),u.jsx("span",{className:je("h-1.5 w-1.5 rounded-full shrink-0",C.state==="active"&&"bg-green-500",C.state==="suspended"&&"bg-yellow-500",C.state==="evicted"&&"bg-gray-400"),title:C.state})]},C.chatId)),u.jsxs("button",{type:"button",onClick:()=>x.mutate(b.agentId),disabled:x.isPending,className:"w-full flex items-center gap-1.5 px-2 py-1 rounded text-xs text-muted-foreground hover:bg-accent/50 transition-colors",children:[u.jsx(hl,{className:"h-3 w-3"}),"New Chat"]})]})]},b.agentId)})]})]})}function c3({selectedAgentId:t,selectedChatId:a,onSelectChat:l,onClearChat:s}){return a&&t?u.jsx(h3,{agentId:t,chatId:a,onBack:s}):t?u.jsx(f3,{agentId:t,onSelectChat:l}):u.jsx(d3,{})}function d3(){const t=Qn(),{data:a}=De({queryKey:["overview"],queryFn:OS,refetchInterval:3e4}),{data:l}=De({queryKey:["activity"],queryFn:Ji,refetchInterval:1e4}),{data:s}=De({queryKey:["notifications","feed"],queryFn:()=>qi({limit:20}),refetchInterval:1e4});return u.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[u.jsx("h2",{className:"text-lg font-semibold mb-4",children:"Activity"}),u.jsx("div",{className:"grid grid-cols-4 gap-3 mb-6",children:[{label:"Agents",value:(a==null?void 0:a.agents)??0},{label:"Online",value:(a==null?void 0:a.onlineAgents)??0},{label:"Working",value:(l==null?void 0:l.byState.working)??0},{label:"Blocked",value:(l==null?void 0:l.byState.blocked)??0}].map(o=>u.jsxs("div",{className:"rounded-lg border border-border p-3",children:[u.jsx("div",{className:"text-xs text-muted-foreground",children:o.label}),u.jsx("div",{className:"text-xl font-bold",children:o.value})]},o.label))}),u.jsxs("div",{className:"space-y-1",children:[(!(s!=null&&s.items)||s.items.length===0)&&u.jsx("div",{className:"text-sm text-muted-foreground text-center py-8",children:"No recent activity"}),s==null?void 0:s.items.map(o=>u.jsxs("div",{className:je("flex items-start gap-2 px-3 py-2 rounded-md text-sm",!o.read&&"bg-accent/20"),children:[u.jsx(Lx,{className:je("h-4 w-4 mt-0.5 shrink-0",o.severity==="high"&&"text-red-500",o.severity==="medium"&&"text-yellow-500",o.severity==="low"&&"text-muted-foreground")}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("span",{className:"font-medium",children:o.agentId?t(o.agentId):""})," ",u.jsx("span",{className:"text-muted-foreground",children:o.message})]}),u.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:un(o.createdAt)})]},o.id))]})]})}function f3({agentId:t,onSelectChat:a}){const l=Qn(),{data:s}=De({queryKey:["agent-sessions-all",t],queryFn:()=>uc(t),refetchInterval:1e4}),o=(s==null?void 0:s.filter(m=>m.state==="active"))??[],d=(s==null?void 0:s.length)??0,h=(s==null?void 0:s.filter(m=>m.runtimeState==="error"))??[];return u.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[u.jsx("h2",{className:"text-lg font-semibold mb-1",children:l(t)}),u.jsx("p",{className:"text-sm text-muted-foreground mb-4 font-mono",children:t}),u.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-6",children:[u.jsxs("div",{className:"rounded-lg border border-border p-3",children:[u.jsx("div",{className:"text-xs text-muted-foreground",children:"Active"}),u.jsx("div",{className:"text-xl font-bold",children:o.length})]}),u.jsxs("div",{className:"rounded-lg border border-border p-3",children:[u.jsx("div",{className:"text-xs text-muted-foreground",children:"Total"}),u.jsx("div",{className:"text-xl font-bold",children:d})]}),u.jsxs("div",{className:"rounded-lg border border-border p-3",children:[u.jsx("div",{className:"text-xs text-muted-foreground",children:"Error"}),u.jsx("div",{className:"text-xl font-bold text-red-600",children:h.length})]})]}),u.jsx("h3",{className:"text-sm font-medium mb-2",children:"All Sessions"}),u.jsx("div",{className:"border rounded-lg overflow-hidden",children:u.jsxs("table",{className:"w-full text-sm",children:[u.jsx("thead",{children:u.jsxs("tr",{className:"border-b border-border bg-muted/50",children:[u.jsx("th",{className:"text-left px-3 py-2 font-medium text-muted-foreground",children:"Chat"}),u.jsx("th",{className:"text-left px-3 py-2 font-medium text-muted-foreground",children:"State"}),u.jsx("th",{className:"text-left px-3 py-2 font-medium text-muted-foreground",children:"Messages"}),u.jsx("th",{className:"text-left px-3 py-2 font-medium text-muted-foreground",children:"Last Active"})]})}),u.jsxs("tbody",{children:[(!s||s.length===0)&&u.jsx("tr",{children:u.jsx("td",{colSpan:4,className:"px-3 py-6 text-center text-muted-foreground",children:"No sessions"})}),s==null?void 0:s.map(m=>u.jsxs("tr",{className:"border-b border-border last:border-0 cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>a(t,m.chatId),children:[u.jsxs("td",{className:"px-3 py-2 font-mono text-xs",children:[m.chatId.slice(0,12),"..."]}),u.jsx("td",{className:"px-3 py-2",children:u.jsx(i3,{state:m.state})}),u.jsx("td",{className:"px-3 py-2 text-muted-foreground text-xs",children:m.messageCount}),u.jsx("td",{className:"px-3 py-2 text-muted-foreground text-xs",children:un(m.lastActivityAt)})]},m.chatId))]})]})})]})}function h3({agentId:t,chatId:a,onBack:l}){var w;const s=Mn(),o=Qn(),{agentId:d}=Os(),[h,m]=y.useState(""),g=y.useRef(null),{data:p}=De({queryKey:["chat-messages",a],queryFn:()=>Jk(a,{limit:50}),refetchInterval:5e3}),x=st({mutationFn:C=>Fk(a,C),onSuccess:()=>{m(""),s.invalidateQueries({queryKey:["chat-messages",a]})}}),b=()=>{const C=h.trim();C&&x.mutate(C)},j=((w=p==null?void 0:p.items)==null?void 0:w.length)??0;return y.useEffect(()=>{var C;j>0&&((C=g.current)==null||C.scrollIntoView({behavior:"smooth"}))},[j]),u.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[u.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border shrink-0",children:[u.jsx("button",{type:"button",onClick:l,className:"text-muted-foreground hover:text-foreground",children:u.jsx(Rx,{className:"h-4 w-4"})}),u.jsx("span",{className:"text-sm font-medium",children:o(t)}),u.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:[a.slice(0,8),"..."]})]}),u.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-3",children:[(!(p!=null&&p.items)||p.items.length===0)&&u.jsxs("div",{className:"text-sm text-muted-foreground text-center py-8",children:[u.jsx(F_,{className:"h-8 w-8 mx-auto mb-2 opacity-30"}),"Send a message to start the conversation"]}),[...(p==null?void 0:p.items)??[]].reverse().map(C=>u.jsxs("div",{className:"rounded-md border border-border p-3",children:[u.jsxs("div",{className:"flex items-center justify-between mb-1",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("span",{className:"text-sm font-medium",children:o(C.senderId)}),C.source&&u.jsx($t,{variant:"outline",className:"text-[10px] opacity-70 px-1 py-0",children:C.source})]}),u.jsxs("div",{className:"flex items-center gap-1",children:[u.jsx("span",{className:"text-xs text-muted-foreground",children:un(C.createdAt)}),u.jsx(o3,{msg:C,myAgentId:d})]})]}),u.jsx("div",{className:"text-sm",children:C.format==="text"?u.jsx("p",{className:"whitespace-pre-wrap",children:typeof C.content=="string"?C.content:JSON.stringify(C.content)}):u.jsx("pre",{className:"text-xs bg-muted p-2 rounded overflow-auto max-h-40",children:JSON.stringify(C.content,null,2)})})]},C.id)),u.jsx("div",{ref:g})]}),u.jsxs("div",{className:"shrink-0 border-t border-border p-3 flex gap-2",children:[u.jsx(tt,{placeholder:"Type a message...",value:h,onChange:C=>m(C.target.value),onKeyDown:C=>{C.key==="Enter"&&!C.shiftKey&&(C.preventDefault(),b())},disabled:x.isPending}),u.jsx(de,{size:"icon",onClick:b,disabled:x.isPending||!h.trim(),children:u.jsx(sE,{className:"h-4 w-4"})})]}),x.isError&&u.jsx("p",{className:"text-destructive text-xs px-3 pb-2",children:x.error instanceof Error?x.error.message:"Failed to send"})]})}function m3({selectedAgentId:t,selectedChatId:a}){return a&&t?u.jsx(x3,{agentId:t,chatId:a}):t?u.jsx(b3,{agentId:t}):u.jsx(p3,{})}function p3(){const t=Qn(),{data:a}=De({queryKey:["overview"],queryFn:OS,refetchInterval:3e4}),{data:l}=De({queryKey:["activity"],queryFn:Ji,refetchInterval:1e4}),{data:s}=De({queryKey:["notifications","context"],queryFn:()=>qi({limit:5}),refetchInterval:3e4});return u.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-4",children:[u.jsx("div",{className:"space-y-2",children:[{label:"Clients",value:(l==null?void 0:l.clients)??0},{label:"Agents",value:(a==null?void 0:a.agents)??0},{label:"Online",value:(a==null?void 0:a.onlineAgents)??0},{label:"Working",value:(l==null?void 0:l.byState.working)??0},{label:"Idle",value:(l==null?void 0:l.byState.idle)??0},{label:"Blocked",value:(l==null?void 0:l.byState.blocked)??0},{label:"Error",value:(l==null?void 0:l.byState.error)??0}].map(o=>u.jsxs("div",{className:"flex items-center justify-between text-sm",children:[u.jsx("span",{className:"text-muted-foreground",children:o.label}),u.jsx("span",{className:"font-medium",children:o.value})]},o.label))}),u.jsxs("div",{className:"border-t border-border pt-3",children:[u.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Notifications"}),!(s!=null&&s.items)||s.items.length===0?u.jsx("div",{className:"text-xs text-muted-foreground text-center py-3",children:"No notifications"}):u.jsx("div",{className:"space-y-2",children:s.items.map(o=>u.jsxs("div",{className:je("text-xs",!o.read&&"font-medium"),children:[u.jsx("span",{className:je(o.severity==="high"&&"text-red-500",o.severity==="medium"&&"text-yellow-500"),children:o.agentId?t(o.agentId):"System"})," ",u.jsx("span",{className:"text-muted-foreground",children:o.message})]},o.id))})]})]})}function g3(t){if(!t)return"—";const a=Date.now()-new Date(t).getTime(),l=Math.floor(a/6e4);if(l<60)return`${l}m`;const s=Math.floor(l/60);return s<24?`${s}h ${l%60}m`:`${Math.floor(s/24)}d ${s%24}h`}const v3={agent_error:"Error",session_error:"Error",agent_blocked:"Blocked",agent_stale:"Stale",agent_disconnected:"Disconnected",agent_connected:"Connected",agent_needs_decision:"Decision",session_completed:"Completed"};function y3({notifications:t,agentId:a}){const[,l]=Ex(),s=Mn(),o=st({mutationFn:d=>e0(d),onSuccess:()=>{s.invalidateQueries({queryKey:["notifications","agent",a]})}});return u.jsx("div",{className:"space-y-1",children:t.map(d=>{const h=!!d.chatId,m=v3[d.type]??d.type;return u.jsxs("button",{type:"button",className:je("w-full flex items-start gap-1.5 px-2 py-1.5 rounded text-xs text-left transition-colors",!d.read&&"bg-accent/30",h&&"cursor-pointer hover:bg-accent/50"),onClick:()=>{d.read||o.mutate(d.id),h&&l({a,c:d.chatId})},children:[u.jsx("span",{className:je("h-1.5 w-1.5 rounded-full mt-1 shrink-0",d.read?"bg-transparent":"bg-primary")}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"flex items-center gap-1",children:[u.jsx("span",{className:je("font-medium",d.severity==="high"&&"text-red-500",d.severity==="medium"&&"text-yellow-600",d.severity==="low"&&"text-muted-foreground"),children:m}),u.jsx("span",{className:"text-muted-foreground ml-auto shrink-0",children:un(d.createdAt)})]}),u.jsx("span",{className:"text-muted-foreground line-clamp-2",children:d.message})]})]},d.id)})})}function b3({agentId:t}){var m;const a=Qn(),{resolve:l}=RS(),{data:s}=De({queryKey:["activity"],queryFn:Ji,refetchInterval:1e4}),o=(m=s==null?void 0:s.agents)==null?void 0:m.find(g=>g.agentId===t),d=l(o==null?void 0:o.clientId),{data:h}=De({queryKey:["notifications","agent",t],queryFn:()=>qi({agentId:t,limit:5}),refetchInterval:3e4});return u.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-4",children:[u.jsx("div",{className:"space-y-2",children:[{label:"Name",value:a(t)},{label:"Status",value:(o==null?void 0:o.runtimeState)??"offline"},{label:"Runtime",value:(o==null?void 0:o.runtimeType)??"—"},{label:"Active",value:String((o==null?void 0:o.activeSessions)??0)},{label:"Total",value:String((o==null?void 0:o.totalSessions)??0)}].map(g=>u.jsxs("div",{className:"flex items-center justify-between text-sm",children:[u.jsx("span",{className:"text-muted-foreground",children:g.label}),u.jsx("span",{className:"font-medium",children:g.value})]},g.label))}),u.jsxs("div",{className:"border-t border-border pt-3",children:[u.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Client"}),d?u.jsx("div",{className:"space-y-2",children:[{label:"Hostname",value:d.hostname??"—"},{label:"OS",value:d.os??"—"},{label:"SDK",value:d.sdkVersion??"—"},{label:"Connected",value:g3(d.connectedAt)}].map(g=>u.jsxs("div",{className:"flex items-center justify-between text-sm",children:[u.jsx("span",{className:"text-muted-foreground",children:g.label}),u.jsx("span",{className:"font-medium",children:g.value})]},g.label))}):u.jsx("div",{className:"text-xs text-muted-foreground",children:"disconnected"})]}),u.jsxs("div",{className:"flex flex-col gap-1",children:[u.jsx("a",{href:`/agents/${t}`,className:"text-xs text-primary hover:underline",children:"Manage Agent →"}),u.jsx("a",{href:"/admin#clients",className:"text-xs text-primary hover:underline",children:"Admin: Clients →"})]}),u.jsxs("div",{className:"border-t border-border pt-3",children:[u.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Notifications"}),!(h!=null&&h.items)||h.items.length===0?u.jsx("div",{className:"text-xs text-muted-foreground text-center py-3",children:"No notifications for this agent"}):u.jsx(y3,{notifications:h.items,agentId:t})]})]})}function x3({agentId:t,chatId:a}){const l=Mn(),{data:s}=De({queryKey:["session",t,a],queryFn:()=>uc(t).then(j=>j.find(w=>w.chatId===a)??null),refetchInterval:5e3}),o=st({mutationFn:()=>uk(t,a),onSuccess:()=>l.invalidateQueries({queryKey:["session",t,a]})}),d=st({mutationFn:()=>ck(t,a),onSuccess:()=>l.invalidateQueries({queryKey:["session",t,a]})}),h=st({mutationFn:()=>dk(t,a),onSuccess:()=>l.invalidateQueries({queryKey:["session",t,a]})}),m=(s==null?void 0:s.state)==="active",g=(s==null?void 0:s.state)==="suspended",p=(s==null?void 0:s.state)==="evicted",x=s!=null&&s.startedAt?new Date(s.startedAt):null,b=x?Math.floor((Date.now()-x.getTime())/6e4):null;return u.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden p-3",children:[u.jsx("div",{className:"space-y-2 mb-3",children:[{label:"State",value:(s==null?void 0:s.state)??"—"},{label:"Runtime",value:(s==null?void 0:s.runtimeState)??"—"},{label:"Started",value:s!=null&&s.startedAt?un(s.startedAt):"—"},{label:"Duration",value:b!==null?`${b} min`:"—"},{label:"Messages",value:String((s==null?void 0:s.messageCount)??0)}].map(j=>u.jsxs("div",{className:"flex items-center justify-between text-sm",children:[u.jsx("span",{className:"text-muted-foreground",children:j.label}),u.jsx("span",{className:"font-medium",children:j.value})]},j.label))}),u.jsxs("div",{className:"flex gap-2 mb-3",children:[m&&u.jsx(de,{variant:"outline",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,children:"Suspend"}),g&&u.jsx(de,{variant:"outline",size:"sm",onClick:()=>d.mutate(),disabled:d.isPending,children:"Resume"}),!p&&u.jsx(de,{variant:"destructive",size:"sm",onClick:()=>{window.confirm("Terminate this session?")&&h.mutate()},disabled:h.isPending,children:"Terminate"})]}),u.jsxs("div",{className:"border-t border-border pt-3 flex-1 overflow-y-auto",children:[u.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Session Info"}),u.jsxs("div",{className:"text-xs text-muted-foreground",children:["Chat ID: ",u.jsxs("span",{className:"font-mono",children:[a.slice(0,12),"..."]})]})]})]})}const S3=new AN({defaultOptions:{queries:{retry:!1,refetchOnWindowFocus:!1}}});function j3(){return u.jsx(TN,{client:S3,children:u.jsx(N_,{children:u.jsx(d_,{children:u.jsxs(Bw,{children:[u.jsx(hr,{path:"/login",element:u.jsx(Pk,{})}),u.jsx(hr,{element:u.jsx(w_,{}),children:u.jsxs(hr,{element:u.jsx(v2,{}),children:[u.jsx(hr,{index:!0,element:u.jsx(n3,{})}),u.jsx(hr,{path:"agents",element:u.jsx(Kk,{})}),u.jsx(hr,{path:"agents/:uuid",element:u.jsx(Bk,{})}),u.jsx(hr,{path:"admin",element:u.jsx(rk,{})})]})})]})})})})}const MS=document.getElementById("root");if(!MS)throw new Error("Root element not found");aN.createRoot(MS).render(u.jsx(y.StrictMode,{children:u.jsx(j3,{})}));