local-operator-ui 0.31.18 → 0.31.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -0
- package/out/main/index.js +233 -106
- package/out/renderer/assets/{_basePickBy-D1XXNWdy.js → _basePickBy-_G13yD_N.js} +1 -1
- package/out/renderer/assets/{_baseUniq-DD_DKvaU.js → _baseUniq-cZFY6WR-.js} +1 -1
- package/out/renderer/assets/{agent-details-page-Q8dgdQp2.js → agent-details-page-DohUpAW5.js} +1 -1
- package/out/renderer/assets/{agent-hub-page-CBHsotVj.js → agent-hub-page-D2Wo_RcW.js} +2 -2
- package/out/renderer/assets/agents-page-Bme3mW2i.js +2 -0
- package/out/renderer/assets/{renderer-platform-RsXXlY5x.js → aida-control-DVTI-DZP.js} +19 -19
- package/out/renderer/assets/{arc-BII0LAll.js → arc-_ZSLPSD3.js} +1 -1
- package/out/renderer/assets/architectureDiagram-IEHRJDOE-BMozIO-d.js +36 -0
- package/out/renderer/assets/{blockDiagram-JOT3LUYC-BsfIO03o.js → blockDiagram-JOT3LUYC-CnCGGby6.js} +6 -6
- package/out/renderer/assets/{book-open-Bau36KjM.js → book-open-BWKY7M9P.js} +1 -1
- package/out/renderer/assets/browser-page-Ca86jJVo.js +1 -0
- package/out/renderer/assets/browser-webauthn-prompt-Zq7Sensn.js +1 -0
- package/out/renderer/assets/{c4Diagram-VJAJSXHY-CHKu8u4B.js → c4Diagram-VJAJSXHY-D6vlxi2G.js} +1 -1
- package/out/renderer/assets/channel-DBxTgGZs.js +1 -0
- package/out/renderer/assets/{chunk-4BMEZGHF-Do_SeY3I.js → chunk-4BMEZGHF-CgxwmKpR.js} +1 -1
- package/out/renderer/assets/{chunk-A2AXSNBT-C7_NoYUm.js → chunk-A2AXSNBT-DL4YbfpC.js} +1 -1
- package/out/renderer/assets/{chunk-AEK57VVT-C3I1E4qy.js → chunk-AEK57VVT-C7STzYq2.js} +1 -1
- package/out/renderer/assets/{chunk-D6G4REZN-BEkTCb-4.js → chunk-D6G4REZN-BiGlWxbN.js} +1 -1
- package/out/renderer/assets/{chunk-RZ5BOZE2-Ccs-Kaym.js → chunk-RZ5BOZE2-FPI-zkVi.js} +1 -1
- package/out/renderer/assets/{chunk-XZIHB7SX-Db28vmME.js → chunk-XZIHB7SX-pQtxBw7K.js} +1 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-oRXPz12L.js +1 -0
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-oRXPz12L.js +1 -0
- package/out/renderer/assets/clone-CWgQ1AK5.js +1 -0
- package/out/renderer/assets/{console-mirror-CUQyeXIE.js → console-mirror-CG9RcMIb.js} +1 -1
- package/out/renderer/assets/{consoleCapture-emgU7WyW.js → consoleCapture-CpTo2RAv.js} +1 -1
- package/out/renderer/assets/dagre-OKDRZEBW-BoM7akd9.js +4 -0
- package/out/renderer/assets/diagram-SSKATNLV-D9w1aNay.js +43 -0
- package/out/renderer/assets/diagram-VNBRO52H-D6xO4h26.js +24 -0
- package/out/renderer/assets/{erDiagram-Q7BY3M3F-BYRglvp5.js → erDiagram-Q7BY3M3F-lgEC_hRU.js} +1 -1
- package/out/renderer/assets/{error-boundary-BFYdHP26.js → error-boundary-DVk48CIF.js} +1 -1
- package/out/renderer/assets/{flowDiagram-4HSFHLVR-C6ReCJC9.js → flowDiagram-4HSFHLVR-B8gXHejR.js} +1 -1
- package/out/renderer/assets/{ganttDiagram-APWFNJXF-CMDShfzg.js → ganttDiagram-APWFNJXF-Ds8ML93J.js} +3 -3
- package/out/renderer/assets/gitGraphDiagram-7IBYFJ6S-D5gdmSVh.js +65 -0
- package/out/renderer/assets/{graph-BK-Vf19N.js → graph-DNi4FjaS.js} +1 -1
- package/out/renderer/assets/index-40tBsZ9r.js +7 -0
- package/out/renderer/assets/{index-BDPyvriR.js → index-BhRzR-VW.js} +391 -376
- package/out/renderer/assets/index-BlalL3ro.js +1 -0
- package/out/renderer/assets/index-FjyWTJXV.css +1 -0
- package/out/renderer/assets/infoDiagram-PH2N3AL5-BDTgzxhS.js +2 -0
- package/out/renderer/assets/{installer-DfFRjYBs.js → installer-BgW1Tkr8.js} +1 -1
- package/out/renderer/assets/{journeyDiagram-U35MCT3I-CeBVrNEA.js → journeyDiagram-U35MCT3I-BdnGNrZc.js} +1 -1
- package/out/renderer/assets/{kanban-definition-NDS4AKOZ-DnIH3R0V.js → kanban-definition-NDS4AKOZ-BuQLa1-R.js} +1 -1
- package/out/renderer/assets/{layout-IqcTjCQI.js → layout-Pvac8TnM.js} +1 -1
- package/out/renderer/assets/{legacy-agents-page-DbLTVwq0.js → legacy-agents-page-BR_oPhtA.js} +3 -3
- package/out/renderer/assets/{mermaid.core-BrRc254F.js → mermaid.core-Dol6F2oY.js} +5 -5
- package/out/renderer/assets/mesh-page-CcSpUIcL.js +2 -0
- package/out/renderer/assets/mindmap-definition-ALO5MXBD-DDnWPtbR.js +95 -0
- package/out/renderer/assets/mini-D1QQjR0V.js +1 -0
- package/out/renderer/assets/org-surface-gate-_kP5Dpsg.js +1 -0
- package/out/renderer/assets/{page-header-BtO13sx8.js → page-header-B3RA2AMB.js} +1 -1
- package/out/renderer/assets/{pieDiagram-IB7DONF6-CnRMxjLj.js → pieDiagram-IB7DONF6-Dc1zeStB.js} +1 -1
- package/out/renderer/assets/{projects-page-BgRRDkEz.js → projects-page-Cb7bJ1ue.js} +1 -1
- package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-bRLUBm5r.js → quadrantDiagram-7GDLP6J5-AlzvyKPw.js} +1 -1
- package/out/renderer/assets/{radar-MK3ICKWK-BV3WfB2Y.js → radar-MK3ICKWK-BLuijs-X.js} +1 -1
- package/out/renderer/assets/radient-auth-buttons-gtgUk3ts.js +1 -0
- package/out/renderer/assets/{requirementDiagram-KVF5MWMF-Bzqys165.js → requirementDiagram-KVF5MWMF-CfgMH9Xy.js} +1 -1
- package/out/renderer/assets/sankeyDiagram-QLVOVGJD-CGSaFjvZ.js +10 -0
- package/out/renderer/assets/{schedules-page-CbOATI1U.js → schedules-page-yCFUUqqb.js} +1 -1
- package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-bfcEv3LN.js → sequenceDiagram-X6HHIX6F-BKLpPHnF.js} +1 -1
- package/out/renderer/assets/settings-page-6S9zTaN7.js +297 -0
- package/out/renderer/assets/{settings-section-BXGO9Lv0.js → settings-section-D3WEX0WK.js} +1 -1
- package/out/renderer/assets/stateDiagram-DGXRK772-CukEj5Ge.js +1 -0
- package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-CaoB6DdD.js +1 -0
- package/out/renderer/assets/{textarea-B83uQCj2.js → textarea-BX6EeK34.js} +1 -1
- package/out/renderer/assets/{timeline-definition-BDJGKUSR-BlN_DgVS.js → timeline-definition-BDJGKUSR-ZSpHRGCR.js} +1 -1
- package/out/renderer/assets/{ui-preferences-store-DzXZGWGz.js → ui-preferences-store-DjUQd2R7.js} +1 -1
- package/out/renderer/assets/{use-download-agent-mutation-DrENBWNa.js → use-download-agent-mutation-BwZi8Zfx.js} +2 -2
- package/out/renderer/assets/use-memberships-query-CSOmeH29.js +1 -0
- package/out/renderer/assets/{xychartDiagram-VJFVF3MP-C1DOS4ES.js → xychartDiagram-VJFVF3MP-B4P41D_W.js} +1 -1
- package/out/renderer/console-capture.html +5 -5
- package/out/renderer/index.html +8 -8
- package/out/renderer/installer.html +5 -5
- package/out/renderer/mini.html +6 -6
- package/package.json +2 -2
- package/out/renderer/assets/agents-page-9zkhLfa8.js +0 -2
- package/out/renderer/assets/architectureDiagram-IEHRJDOE-Yh4i0oDy.js +0 -36
- package/out/renderer/assets/browser-page-CrHmmBk0.js +0 -1
- package/out/renderer/assets/browser-webauthn-prompt-_nNd3iSK.js +0 -1
- package/out/renderer/assets/channel-DXiH5yDB.js +0 -1
- package/out/renderer/assets/classDiagram-GIVACNV2-D2MG4USX.js +0 -1
- package/out/renderer/assets/classDiagram-v2-COTLJTTW-D2MG4USX.js +0 -1
- package/out/renderer/assets/clone-BDi6ICAs.js +0 -1
- package/out/renderer/assets/dagre-OKDRZEBW-k4D1AM8X.js +0 -4
- package/out/renderer/assets/diagram-SSKATNLV-B0DOtyf9.js +0 -43
- package/out/renderer/assets/diagram-VNBRO52H-BmzuI3Lr.js +0 -24
- package/out/renderer/assets/gitGraphDiagram-7IBYFJ6S-pvPc8CHP.js +0 -65
- package/out/renderer/assets/index-B5DwqFlK.js +0 -7
- package/out/renderer/assets/index-DITdBETY.css +0 -1
- package/out/renderer/assets/index-_oyU7kmX.js +0 -1
- package/out/renderer/assets/infoDiagram-PH2N3AL5-COePE42k.js +0 -2
- package/out/renderer/assets/mesh-page-W9oV_bPF.js +0 -2
- package/out/renderer/assets/mindmap-definition-ALO5MXBD-BMHndK7E.js +0 -95
- package/out/renderer/assets/mini-CbmMlUkq.js +0 -1
- package/out/renderer/assets/org-surface-gate-BgtTWHt3.js +0 -1
- package/out/renderer/assets/radient-auth-buttons-Briy2cZb.js +0 -1
- package/out/renderer/assets/sankeyDiagram-QLVOVGJD--IgSaXgN.js +0 -10
- package/out/renderer/assets/settings-page-Bn87mGZ1.js +0 -307
- package/out/renderer/assets/stateDiagram-DGXRK772-CDJAoYUf.js +0 -1
- package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-Di7PMVrt.js +0 -1
- package/out/renderer/assets/use-memberships-query-C2Yus1QJ.js +0 -1
- /package/out/renderer/assets/{index-CDaH3A1m.js → index-VKe88JN9.js} +0 -0
|
@@ -1,42 +1,42 @@
|
|
|
1
|
-
import{c as As,p as gi}from"./ui-preferences-store-DzXZGWGz.js";import{r as T,j as De}from"./index-CDaH3A1m.js";import{c as Tn}from"./textarea-B83uQCj2.js";var B;(function(e){e.assertEqual=r=>r;function t(r){}e.assertIs=t;function n(r){throw new Error}e.assertNever=n,e.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},e.getValidEnumValues=r=>{const i=e.objectKeys(r).filter(c=>typeof r[r[c]]!="number"),o={};for(const c of i)o[c]=r[c];return e.objectValues(o)},e.objectValues=r=>e.objectKeys(r).map(function(i){return r[i]}),e.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&i.push(o);return i},e.find=(r,i)=>{for(const o of r)if(i(o))return o},e.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&isFinite(r)&&Math.floor(r)===r;function s(r,i=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}e.joinValues=s,e.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(B||(B={}));var ts;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(ts||(ts={}));const b=B.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Me=e=>{switch(typeof e){case"undefined":return b.undefined;case"string":return b.string;case"number":return isNaN(e)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(e)?b.array:e===null?b.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?b.promise:typeof Map<"u"&&e instanceof Map?b.map:typeof Set<"u"&&e instanceof Set?b.set:typeof Date<"u"&&e instanceof Date?b.date:b.object;default:return b.unknown}},m=B.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Ko=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class ye extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(i){return i.message},s={_errors:[]},r=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)s._errors.push(n(o));else{let c=s,l=0;for(;l<o.path.length;){const d=o.path[l];l===o.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(o))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}};return r(this),s}static assert(t){if(!(t instanceof ye))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,B.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},s=[];for(const r of this.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):s.push(t(r));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}ye.create=e=>new ye(e);const bt=(e,t)=>{let n;switch(e.code){case m.invalid_type:e.received===b.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case m.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,B.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:n=`Unrecognized key(s) in object: ${B.joinValues(e.keys,", ")}`;break;case m.invalid_union:n="Invalid input";break;case m.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${B.joinValues(e.options)}`;break;case m.invalid_enum_value:n=`Invalid enum value. Expected ${B.joinValues(e.options)}, received '${e.received}'`;break;case m.invalid_arguments:n="Invalid function arguments";break;case m.invalid_return_type:n="Invalid function return type";break;case m.invalid_date:n="Invalid date";break;case m.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:B.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case m.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case m.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case m.custom:n="Invalid input";break;case m.invalid_intersection_types:n="Intersection results could not be merged";break;case m.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case m.not_finite:n="Number must be finite";break;default:n=t.defaultError,B.assertNever(e)}return{message:n}};let yi=bt;function Wo(e){yi=e}function pn(){return yi}const hn=e=>{const{data:t,path:n,errorMaps:s,issueData:r}=e,i=[...n,...r.path||[]],o={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let c="";const l=s.filter(d=>!!d).slice().reverse();for(const d of l)c=d(o,{data:t,defaultError:c}).message;return{...r,path:i,message:c}},Yo=[];function y(e,t){const n=pn(),s=hn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===bt?void 0:bt].filter(r=>!!r)});e.common.issues.push(s)}class ue{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const s=[];for(const r of n){if(r.status==="aborted")return R;r.status==="dirty"&&t.dirty(),s.push(r.value)}return{status:t.value,value:s}}static async mergeObjectAsync(t,n){const s=[];for(const r of n){const i=await r.key,o=await r.value;s.push({key:i,value:o})}return ue.mergeObjectSync(t,s)}static mergeObjectSync(t,n){const s={};for(const r of n){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return R;i.status==="dirty"&&t.dirty(),o.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(s[i.value]=o.value)}return{status:t.value,value:s}}}const R=Object.freeze({status:"aborted"}),yt=e=>({status:"dirty",value:e}),pe=e=>({status:"valid",value:e}),ns=e=>e.status==="aborted",ss=e=>e.status==="dirty",rt=e=>e.status==="valid",Mt=e=>typeof Promise<"u"&&e instanceof Promise;function mn(e,t,n,s){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function vi(e,t,n,s,r){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var S;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(S||(S={}));var It,Ct;class Oe{constructor(t,n,s,r){this._cachedPath=[],this.parent=t,this.data=n,this._path=s,this._key=r}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ys=(e,t)=>{if(rt(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new ye(e.common.issues);return this._error=n,this._error}}};function D(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:s,description:r}=e;if(t&&(n||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:r}:{errorMap:(o,c)=>{var l,d;const{message:u}=e;return o.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??s)!==null&&l!==void 0?l:c.defaultError}:o.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??n)!==null&&d!==void 0?d:c.defaultError}},description:r}}class N{get description(){return this._def.description}_getType(t){return Me(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Me(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ue,ctx:{common:t.parent.common,data:t.data,parsedType:Me(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Mt(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const s=this.safeParse(t,n);if(s.success)return s.data;throw s.error}safeParse(t,n){var s;const r={common:{issues:[],async:(s=n?.async)!==null&&s!==void 0?s:!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Me(t)},i=this._parseSync({data:t,path:r.path,parent:r});return Ys(r,i)}"~validate"(t){var n,s;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Me(t)};if(!this["~standard"].async)try{const i=this._parseSync({data:t,path:[],parent:r});return rt(i)?{value:i.value}:{issues:r.common.issues}}catch(i){!((s=(n=i?.message)===null||n===void 0?void 0:n.toLowerCase())===null||s===void 0)&&s.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(i=>rt(i)?{value:i.value}:{issues:r.common.issues})}async parseAsync(t,n){const s=await this.safeParseAsync(t,n);if(s.success)return s.data;throw s.error}async safeParseAsync(t,n){const s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Me(t)},r=this._parse({data:t,path:s.path,parent:s}),i=await(Mt(r)?r:Promise.resolve(r));return Ys(s,i)}refine(t,n){const s=r=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(r):n;return this._refinement((r,i)=>{const o=t(r),c=()=>i.addIssue({code:m.custom,...s(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(c(),!1)):o?!0:(c(),!1)})}refinement(t,n){return this._refinement((s,r)=>t(s)?!0:(r.addIssue(typeof n=="function"?n(s,r):n),!1))}_refinement(t){return new ke({schema:this,typeName:C.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Ae.create(this,this._def)}nullable(){return ze.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Se.create(this)}promise(){return St.create(this,this._def)}or(t){return Ft.create([this,t],this._def)}and(t){return Bt.create(this,t,this._def)}transform(t){return new ke({...D(this._def),schema:this,typeName:C.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new zt({...D(this._def),innerType:this,defaultValue:n,typeName:C.ZodDefault})}brand(){return new Os({typeName:C.ZodBranded,type:this,...D(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Kt({...D(this._def),innerType:this,catchValue:n,typeName:C.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Yt.create(this,t)}readonly(){return Wt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Qo=/^c[^\s-]{8,}$/i,Xo=/^[0-9a-z]+$/,Jo=/^[0-9A-HJKMNP-TV-Z]{26}$/i,qo=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ea=/^[a-z0-9_-]{21}$/i,ta=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,na=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,sa=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ra="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let jn;const ia=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,oa=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,aa=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ca=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,la=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,da=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_i="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ua=new RegExp(`^${_i}$`);function bi(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`),t}function fa(e){return new RegExp(`^${bi(e)}$`)}function wi(e){let t=`${_i}T${bi(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function pa(e,t){return!!((t==="v4"||!t)&&ia.test(e)||(t==="v6"||!t)&&aa.test(e))}function ha(e,t){if(!ta.test(e))return!1;try{const[n]=e.split("."),s=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(s));return!(typeof r!="object"||r===null||!r.typ||!r.alg||t&&r.alg!==t)}catch{return!1}}function ma(e,t){return!!((t==="v4"||!t)&&oa.test(e)||(t==="v6"||!t)&&ca.test(e))}class we extends N{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==b.string){const i=this._getOrReturnCtx(t);return y(i,{code:m.invalid_type,expected:b.string,received:i.parsedType}),R}const s=new ue;let r;for(const i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(r=this._getOrReturnCtx(t,r),y(r,{code:m.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")t.data.length>i.value&&(r=this._getOrReturnCtx(t,r),y(r,{code:m.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){const o=t.data.length>i.value,c=t.data.length<i.value;(o||c)&&(r=this._getOrReturnCtx(t,r),o?y(r,{code:m.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&y(r,{code:m.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")sa.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"email",code:m.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")jn||(jn=new RegExp(ra,"u")),jn.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"emoji",code:m.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")qo.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"uuid",code:m.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")ea.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"nanoid",code:m.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")Qo.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"cuid",code:m.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")Xo.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"cuid2",code:m.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")Jo.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"ulid",code:m.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{r=this._getOrReturnCtx(t,r),y(r,{validation:"url",code:m.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"regex",code:m.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(t,r),y(r,{code:m.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(r=this._getOrReturnCtx(t,r),y(r,{code:m.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(r=this._getOrReturnCtx(t,r),y(r,{code:m.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?wi(i).test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{code:m.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?ua.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{code:m.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?fa(i).test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{code:m.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?na.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"duration",code:m.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?pa(t.data,i.version)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"ip",code:m.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?ha(t.data,i.alg)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"jwt",code:m.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?ma(t.data,i.version)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"cidr",code:m.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?la.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"base64",code:m.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?da.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"base64url",code:m.invalid_string,message:i.message}),s.dirty()):B.assertNever(i);return{status:s.value,value:t.data}}_regex(t,n,s){return this.refinement(r=>t.test(r),{validation:n,code:m.invalid_string,...S.errToObj(s)})}_addCheck(t){return new we({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...S.errToObj(t)})}url(t){return this._addCheck({kind:"url",...S.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...S.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...S.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...S.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...S.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...S.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...S.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...S.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...S.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...S.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...S.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...S.errToObj(t)})}datetime(t){var n,s;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(n=t?.offset)!==null&&n!==void 0?n:!1,local:(s=t?.local)!==null&&s!==void 0?s:!1,...S.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...S.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...S.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...S.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...S.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...S.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...S.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...S.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...S.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...S.errToObj(n)})}nonempty(t){return this.min(1,S.errToObj(t))}trim(){return new we({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new we({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new we({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}we.create=e=>{var t;return new we({checks:[],typeName:C.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...D(e)})};function ga(e,t){const n=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,r=n>s?n:s,i=parseInt(e.toFixed(r).replace(".","")),o=parseInt(t.toFixed(r).replace(".",""));return i%o/Math.pow(10,r)}class Ge extends N{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==b.number){const i=this._getOrReturnCtx(t);return y(i,{code:m.invalid_type,expected:b.number,received:i.parsedType}),R}let s;const r=new ue;for(const i of this._def.checks)i.kind==="int"?B.isInteger(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{code:m.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(s=this._getOrReturnCtx(t,s),y(s,{code:m.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(s=this._getOrReturnCtx(t,s),y(s,{code:m.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?ga(t.data,i.value)!==0&&(s=this._getOrReturnCtx(t,s),y(s,{code:m.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{code:m.not_finite,message:i.message}),r.dirty()):B.assertNever(i);return{status:r.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,S.toString(n))}gt(t,n){return this.setLimit("min",t,!1,S.toString(n))}lte(t,n){return this.setLimit("max",t,!0,S.toString(n))}lt(t,n){return this.setLimit("max",t,!1,S.toString(n))}setLimit(t,n,s,r){return new Ge({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:S.toString(r)}]})}_addCheck(t){return new Ge({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:S.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:S.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:S.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:S.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:S.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:S.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:S.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:S.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:S.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&B.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(n===null||s.value>n)&&(n=s.value):s.kind==="max"&&(t===null||s.value<t)&&(t=s.value)}return Number.isFinite(n)&&Number.isFinite(t)}}Ge.create=e=>new Ge({checks:[],typeName:C.ZodNumber,coerce:e?.coerce||!1,...D(e)});class He extends N{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==b.bigint)return this._getInvalidInput(t);let s;const r=new ue;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(s=this._getOrReturnCtx(t,s),y(s,{code:m.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(s=this._getOrReturnCtx(t,s),y(s,{code:m.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(t,s),y(s,{code:m.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):B.assertNever(i);return{status:r.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return y(n,{code:m.invalid_type,expected:b.bigint,received:n.parsedType}),R}gte(t,n){return this.setLimit("min",t,!0,S.toString(n))}gt(t,n){return this.setLimit("min",t,!1,S.toString(n))}lte(t,n){return this.setLimit("max",t,!0,S.toString(n))}lt(t,n){return this.setLimit("max",t,!1,S.toString(n))}setLimit(t,n,s,r){return new He({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:S.toString(r)}]})}_addCheck(t){return new He({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:S.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:S.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:S.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:S.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:S.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}He.create=e=>{var t;return new He({checks:[],typeName:C.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...D(e)})};class jt extends N{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==b.boolean){const s=this._getOrReturnCtx(t);return y(s,{code:m.invalid_type,expected:b.boolean,received:s.parsedType}),R}return pe(t.data)}}jt.create=e=>new jt({typeName:C.ZodBoolean,coerce:e?.coerce||!1,...D(e)});class it extends N{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==b.date){const i=this._getOrReturnCtx(t);return y(i,{code:m.invalid_type,expected:b.date,received:i.parsedType}),R}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return y(i,{code:m.invalid_date}),R}const s=new ue;let r;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(r=this._getOrReturnCtx(t,r),y(r,{code:m.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(r=this._getOrReturnCtx(t,r),y(r,{code:m.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):B.assertNever(i);return{status:s.value,value:new Date(t.data.getTime())}}_addCheck(t){return new it({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:S.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:S.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}}it.create=e=>new it({checks:[],coerce:e?.coerce||!1,typeName:C.ZodDate,...D(e)});class gn extends N{_parse(t){if(this._getType(t)!==b.symbol){const s=this._getOrReturnCtx(t);return y(s,{code:m.invalid_type,expected:b.symbol,received:s.parsedType}),R}return pe(t.data)}}gn.create=e=>new gn({typeName:C.ZodSymbol,...D(e)});class $t extends N{_parse(t){if(this._getType(t)!==b.undefined){const s=this._getOrReturnCtx(t);return y(s,{code:m.invalid_type,expected:b.undefined,received:s.parsedType}),R}return pe(t.data)}}$t.create=e=>new $t({typeName:C.ZodUndefined,...D(e)});class Ut extends N{_parse(t){if(this._getType(t)!==b.null){const s=this._getOrReturnCtx(t);return y(s,{code:m.invalid_type,expected:b.null,received:s.parsedType}),R}return pe(t.data)}}Ut.create=e=>new Ut({typeName:C.ZodNull,...D(e)});class wt extends N{constructor(){super(...arguments),this._any=!0}_parse(t){return pe(t.data)}}wt.create=e=>new wt({typeName:C.ZodAny,...D(e)});class nt extends N{constructor(){super(...arguments),this._unknown=!0}_parse(t){return pe(t.data)}}nt.create=e=>new nt({typeName:C.ZodUnknown,...D(e)});class $e extends N{_parse(t){const n=this._getOrReturnCtx(t);return y(n,{code:m.invalid_type,expected:b.never,received:n.parsedType}),R}}$e.create=e=>new $e({typeName:C.ZodNever,...D(e)});class yn extends N{_parse(t){if(this._getType(t)!==b.undefined){const s=this._getOrReturnCtx(t);return y(s,{code:m.invalid_type,expected:b.void,received:s.parsedType}),R}return pe(t.data)}}yn.create=e=>new yn({typeName:C.ZodVoid,...D(e)});class Se extends N{_parse(t){const{ctx:n,status:s}=this._processInputParams(t),r=this._def;if(n.parsedType!==b.array)return y(n,{code:m.invalid_type,expected:b.array,received:n.parsedType}),R;if(r.exactLength!==null){const o=n.data.length>r.exactLength.value,c=n.data.length<r.exactLength.value;(o||c)&&(y(n,{code:o?m.too_big:m.too_small,minimum:c?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(r.minLength!==null&&n.data.length<r.minLength.value&&(y(n,{code:m.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&n.data.length>r.maxLength.value&&(y(n,{code:m.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),n.common.async)return Promise.all([...n.data].map((o,c)=>r.type._parseAsync(new Oe(n,o,n.path,c)))).then(o=>ue.mergeArray(s,o));const i=[...n.data].map((o,c)=>r.type._parseSync(new Oe(n,o,n.path,c)));return ue.mergeArray(s,i)}get element(){return this._def.type}min(t,n){return new Se({...this._def,minLength:{value:t,message:S.toString(n)}})}max(t,n){return new Se({...this._def,maxLength:{value:t,message:S.toString(n)}})}length(t,n){return new Se({...this._def,exactLength:{value:t,message:S.toString(n)}})}nonempty(t){return this.min(1,t)}}Se.create=(e,t)=>new Se({type:e,minLength:null,maxLength:null,exactLength:null,typeName:C.ZodArray,...D(t)});function gt(e){if(e instanceof Q){const t={};for(const n in e.shape){const s=e.shape[n];t[n]=Ae.create(gt(s))}return new Q({...e._def,shape:()=>t})}else return e instanceof Se?new Se({...e._def,type:gt(e.element)}):e instanceof Ae?Ae.create(gt(e.unwrap())):e instanceof ze?ze.create(gt(e.unwrap())):e instanceof Pe?Pe.create(e.items.map(t=>gt(t))):e}class Q extends N{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=B.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==b.object){const d=this._getOrReturnCtx(t);return y(d,{code:m.invalid_type,expected:b.object,received:d.parsedType}),R}const{status:s,ctx:r}=this._processInputParams(t),{shape:i,keys:o}=this._getCached(),c=[];if(!(this._def.catchall instanceof $e&&this._def.unknownKeys==="strip"))for(const d in r.data)o.includes(d)||c.push(d);const l=[];for(const d of o){const u=i[d],f=r.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new Oe(r,f,r.path,d)),alwaysSet:d in r.data})}if(this._def.catchall instanceof $e){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:r.data[u]}});else if(d==="strict")c.length>0&&(y(r,{code:m.unrecognized_keys,keys:c}),s.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const u of c){const f=r.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new Oe(r,f,r.path,u)),alwaysSet:u in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const d=[];for(const u of l){const f=await u.key,p=await u.value;d.push({key:f,value:p,alwaysSet:u.alwaysSet})}return d}).then(d=>ue.mergeObjectSync(s,d)):ue.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(t){return S.errToObj,new Q({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,s)=>{var r,i,o,c;const l=(o=(i=(r=this._def).errorMap)===null||i===void 0?void 0:i.call(r,n,s).message)!==null&&o!==void 0?o:s.defaultError;return n.code==="unrecognized_keys"?{message:(c=S.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new Q({...this._def,unknownKeys:"strip"})}passthrough(){return new Q({...this._def,unknownKeys:"passthrough"})}extend(t){return new Q({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Q({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:C.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Q({...this._def,catchall:t})}pick(t){const n={};return B.objectKeys(t).forEach(s=>{t[s]&&this.shape[s]&&(n[s]=this.shape[s])}),new Q({...this._def,shape:()=>n})}omit(t){const n={};return B.objectKeys(this.shape).forEach(s=>{t[s]||(n[s]=this.shape[s])}),new Q({...this._def,shape:()=>n})}deepPartial(){return gt(this)}partial(t){const n={};return B.objectKeys(this.shape).forEach(s=>{const r=this.shape[s];t&&!t[s]?n[s]=r:n[s]=r.optional()}),new Q({...this._def,shape:()=>n})}required(t){const n={};return B.objectKeys(this.shape).forEach(s=>{if(t&&!t[s])n[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof Ae;)i=i._def.innerType;n[s]=i}}),new Q({...this._def,shape:()=>n})}keyof(){return Si(B.objectKeys(this.shape))}}Q.create=(e,t)=>new Q({shape:()=>e,unknownKeys:"strip",catchall:$e.create(),typeName:C.ZodObject,...D(t)});Q.strictCreate=(e,t)=>new Q({shape:()=>e,unknownKeys:"strict",catchall:$e.create(),typeName:C.ZodObject,...D(t)});Q.lazycreate=(e,t)=>new Q({shape:e,unknownKeys:"strip",catchall:$e.create(),typeName:C.ZodObject,...D(t)});class Ft extends N{_parse(t){const{ctx:n}=this._processInputParams(t),s=this._def.options;function r(i){for(const c of i)if(c.result.status==="valid")return c.result;for(const c of i)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const o=i.map(c=>new ye(c.ctx.common.issues));return y(n,{code:m.invalid_union,unionErrors:o}),R}if(n.common.async)return Promise.all(s.map(async i=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const l of s){const d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const c=o.map(l=>new ye(l));return y(n,{code:m.invalid_union,unionErrors:c}),R}}get options(){return this._def.options}}Ft.create=(e,t)=>new Ft({options:e,typeName:C.ZodUnion,...D(t)});const Le=e=>e instanceof Gt?Le(e.schema):e instanceof ke?Le(e.innerType()):e instanceof Ht?[e.value]:e instanceof Ve?e.options:e instanceof Vt?B.objectValues(e.enum):e instanceof zt?Le(e._def.innerType):e instanceof $t?[void 0]:e instanceof Ut?[null]:e instanceof Ae?[void 0,...Le(e.unwrap())]:e instanceof ze?[null,...Le(e.unwrap())]:e instanceof Os||e instanceof Wt?Le(e.unwrap()):e instanceof Kt?Le(e._def.innerType):[];class En extends N{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.object)return y(n,{code:m.invalid_type,expected:b.object,received:n.parsedType}),R;const s=this.discriminator,r=n.data[s],i=this.optionsMap.get(r);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(y(n,{code:m.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),R)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,s){const r=new Map;for(const i of n){const o=Le(i.shape[t]);if(!o.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const c of o){if(r.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);r.set(c,i)}}return new En({typeName:C.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:r,...D(s)})}}function rs(e,t){const n=Me(e),s=Me(t);if(e===t)return{valid:!0,data:e};if(n===b.object&&s===b.object){const r=B.objectKeys(t),i=B.objectKeys(e).filter(c=>r.indexOf(c)!==-1),o={...e,...t};for(const c of i){const l=rs(e[c],t[c]);if(!l.valid)return{valid:!1};o[c]=l.data}return{valid:!0,data:o}}else if(n===b.array&&s===b.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let i=0;i<e.length;i++){const o=e[i],c=t[i],l=rs(o,c);if(!l.valid)return{valid:!1};r.push(l.data)}return{valid:!0,data:r}}else return n===b.date&&s===b.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Bt extends N{_parse(t){const{status:n,ctx:s}=this._processInputParams(t),r=(i,o)=>{if(ns(i)||ns(o))return R;const c=rs(i.value,o.value);return c.valid?((ss(i)||ss(o))&&n.dirty(),{status:n.value,value:c.data}):(y(s,{code:m.invalid_intersection_types}),R)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,o])=>r(i,o)):r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Bt.create=(e,t,n)=>new Bt({left:e,right:t,typeName:C.ZodIntersection,...D(n)});class Pe extends N{_parse(t){const{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==b.array)return y(s,{code:m.invalid_type,expected:b.array,received:s.parsedType}),R;if(s.data.length<this._def.items.length)return y(s,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),R;!this._def.rest&&s.data.length>this._def.items.length&&(y(s,{code:m.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...s.data].map((o,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new Oe(s,o,s.path,c)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>ue.mergeArray(n,o)):ue.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new Pe({...this._def,rest:t})}}Pe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Pe({items:e,typeName:C.ZodTuple,rest:null,...D(t)})};class Zt extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==b.object)return y(s,{code:m.invalid_type,expected:b.object,received:s.parsedType}),R;const r=[],i=this._def.keyType,o=this._def.valueType;for(const c in s.data)r.push({key:i._parse(new Oe(s,c,s.path,c)),value:o._parse(new Oe(s,s.data[c],s.path,c)),alwaysSet:c in s.data});return s.common.async?ue.mergeObjectAsync(n,r):ue.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(t,n,s){return n instanceof N?new Zt({keyType:t,valueType:n,typeName:C.ZodRecord,...D(s)}):new Zt({keyType:we.create(),valueType:t,typeName:C.ZodRecord,...D(n)})}}class vn extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==b.map)return y(s,{code:m.invalid_type,expected:b.map,received:s.parsedType}),R;const r=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([c,l],d)=>({key:r._parse(new Oe(s,c,s.path,[d,"key"])),value:i._parse(new Oe(s,l,s.path,[d,"value"]))}));if(s.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of o){const d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return R;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{const c=new Map;for(const l of o){const d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return R;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}vn.create=(e,t,n)=>new vn({valueType:t,keyType:e,typeName:C.ZodMap,...D(n)});class ot extends N{_parse(t){const{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==b.set)return y(s,{code:m.invalid_type,expected:b.set,received:s.parsedType}),R;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(y(s,{code:m.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()),r.maxSize!==null&&s.data.size>r.maxSize.value&&(y(s,{code:m.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty());const i=this._def.valueType;function o(l){const d=new Set;for(const u of l){if(u.status==="aborted")return R;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...s.data.values()].map((l,d)=>i._parse(new Oe(s,l,s.path,d)));return s.common.async?Promise.all(c).then(l=>o(l)):o(c)}min(t,n){return new ot({...this._def,minSize:{value:t,message:S.toString(n)}})}max(t,n){return new ot({...this._def,maxSize:{value:t,message:S.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}ot.create=(e,t)=>new ot({valueType:e,minSize:null,maxSize:null,typeName:C.ZodSet,...D(t)});class _t extends N{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.function)return y(n,{code:m.invalid_type,expected:b.function,received:n.parsedType}),R;function s(c,l){return hn({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,pn(),bt].filter(d=>!!d),issueData:{code:m.invalid_arguments,argumentsError:l}})}function r(c,l){return hn({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,pn(),bt].filter(d=>!!d),issueData:{code:m.invalid_return_type,returnTypeError:l}})}const i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof St){const c=this;return pe(async function(...l){const d=new ye([]),u=await c._def.args.parseAsync(l,i).catch(w=>{throw d.addIssue(s(l,w)),d}),f=await Reflect.apply(o,this,u);return await c._def.returns._def.type.parseAsync(f,i).catch(w=>{throw d.addIssue(r(f,w)),d})})}else{const c=this;return pe(function(...l){const d=c._def.args.safeParse(l,i);if(!d.success)throw new ye([s(l,d.error)]);const u=Reflect.apply(o,this,d.data),f=c._def.returns.safeParse(u,i);if(!f.success)throw new ye([r(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new _t({...this._def,args:Pe.create(t).rest(nt.create())})}returns(t){return new _t({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,s){return new _t({args:t||Pe.create([]).rest(nt.create()),returns:n||nt.create(),typeName:C.ZodFunction,...D(s)})}}class Gt extends N{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Gt.create=(e,t)=>new Gt({getter:e,typeName:C.ZodLazy,...D(t)});class Ht extends N{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return y(n,{received:n.data,code:m.invalid_literal,expected:this._def.value}),R}return{status:"valid",value:t.data}}get value(){return this._def.value}}Ht.create=(e,t)=>new Ht({value:e,typeName:C.ZodLiteral,...D(t)});function Si(e,t){return new Ve({values:e,typeName:C.ZodEnum,...D(t)})}class Ve extends N{constructor(){super(...arguments),It.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),s=this._def.values;return y(n,{expected:B.joinValues(s),received:n.parsedType,code:m.invalid_type}),R}if(mn(this,It)||vi(this,It,new Set(this._def.values)),!mn(this,It).has(t.data)){const n=this._getOrReturnCtx(t),s=this._def.values;return y(n,{received:n.data,code:m.invalid_enum_value,options:s}),R}return pe(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Ve.create(t,{...this._def,...n})}exclude(t,n=this._def){return Ve.create(this.options.filter(s=>!t.includes(s)),{...this._def,...n})}}It=new WeakMap;Ve.create=Si;class Vt extends N{constructor(){super(...arguments),Ct.set(this,void 0)}_parse(t){const n=B.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(t);if(s.parsedType!==b.string&&s.parsedType!==b.number){const r=B.objectValues(n);return y(s,{expected:B.joinValues(r),received:s.parsedType,code:m.invalid_type}),R}if(mn(this,Ct)||vi(this,Ct,new Set(B.getValidEnumValues(this._def.values))),!mn(this,Ct).has(t.data)){const r=B.objectValues(n);return y(s,{received:s.data,code:m.invalid_enum_value,options:r}),R}return pe(t.data)}get enum(){return this._def.values}}Ct=new WeakMap;Vt.create=(e,t)=>new Vt({values:e,typeName:C.ZodNativeEnum,...D(t)});class St extends N{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.promise&&n.common.async===!1)return y(n,{code:m.invalid_type,expected:b.promise,received:n.parsedType}),R;const s=n.parsedType===b.promise?n.data:Promise.resolve(n.data);return pe(s.then(r=>this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})))}}St.create=(e,t)=>new St({type:e,typeName:C.ZodPromise,...D(t)});class ke extends N{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===C.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:s}=this._processInputParams(t),r=this._def.effect||null,i={addIssue:o=>{y(s,o),o.fatal?n.abort():n.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async c=>{if(n.value==="aborted")return R;const l=await this._def.schema._parseAsync({data:c,path:s.path,parent:s});return l.status==="aborted"?R:l.status==="dirty"||n.value==="dirty"?yt(l.value):l});{if(n.value==="aborted")return R;const c=this._def.schema._parseSync({data:o,path:s.path,parent:s});return c.status==="aborted"?R:c.status==="dirty"||n.value==="dirty"?yt(c.value):c}}if(r.type==="refinement"){const o=c=>{const l=r.refinement(c,i);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(s.common.async===!1){const c=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return c.status==="aborted"?R:(c.status==="dirty"&&n.dirty(),o(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(c=>c.status==="aborted"?R:(c.status==="dirty"&&n.dirty(),o(c.value).then(()=>({status:n.value,value:c.value}))))}if(r.type==="transform")if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!rt(o))return o;const c=r.transform(o.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>rt(o)?Promise.resolve(r.transform(o.value,i)).then(c=>({status:n.value,value:c})):o);B.assertNever(r)}}ke.create=(e,t,n)=>new ke({schema:e,typeName:C.ZodEffects,effect:t,...D(n)});ke.createWithPreprocess=(e,t,n)=>new ke({schema:t,effect:{type:"preprocess",transform:e},typeName:C.ZodEffects,...D(n)});class Ae extends N{_parse(t){return this._getType(t)===b.undefined?pe(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:C.ZodOptional,...D(t)});class ze extends N{_parse(t){return this._getType(t)===b.null?pe(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ze.create=(e,t)=>new ze({innerType:e,typeName:C.ZodNullable,...D(t)});class zt extends N{_parse(t){const{ctx:n}=this._processInputParams(t);let s=n.data;return n.parsedType===b.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}zt.create=(e,t)=>new zt({innerType:e,typeName:C.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...D(t)});class Kt extends N{_parse(t){const{ctx:n}=this._processInputParams(t),s={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Mt(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ye(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new ye(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Kt.create=(e,t)=>new Kt({innerType:e,typeName:C.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...D(t)});class _n extends N{_parse(t){if(this._getType(t)!==b.nan){const s=this._getOrReturnCtx(t);return y(s,{code:m.invalid_type,expected:b.nan,received:s.parsedType}),R}return{status:"valid",value:t.data}}}_n.create=e=>new _n({typeName:C.ZodNaN,...D(e)});const ya=Symbol("zod_brand");class Os extends N{_parse(t){const{ctx:n}=this._processInputParams(t),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class Yt extends N{_parse(t){const{status:n,ctx:s}=this._processInputParams(t);if(s.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?R:i.status==="dirty"?(n.dirty(),yt(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{const r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?R:r.status==="dirty"?(n.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(t,n){return new Yt({in:t,out:n,typeName:C.ZodPipeline})}}class Wt extends N{_parse(t){const n=this._def.innerType._parse(t),s=r=>(rt(r)&&(r.value=Object.freeze(r.value)),r);return Mt(n)?n.then(r=>s(r)):s(n)}unwrap(){return this._def.innerType}}Wt.create=(e,t)=>new Wt({innerType:e,typeName:C.ZodReadonly,...D(t)});function Qs(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function ki(e,t={},n){return e?wt.create().superRefine((s,r)=>{var i,o;const c=e(s);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=Qs(t,s),p=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;r.addIssue({code:"custom",...f,fatal:p})}});if(!c){const l=Qs(t,s),d=(o=(i=l.fatal)!==null&&i!==void 0?i:n)!==null&&o!==void 0?o:!0;r.addIssue({code:"custom",...l,fatal:d})}}):wt.create()}const va={object:Q.lazycreate};var C;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(C||(C={}));const _a=(e,t={message:`Input not instance of ${e.name}`})=>ki(n=>n instanceof e,t),Ti=we.create,Ei=Ge.create,ba=_n.create,wa=He.create,xi=jt.create,Sa=it.create,ka=gn.create,Ta=$t.create,Ea=Ut.create,xa=wt.create,Ia=nt.create,Ca=$e.create,Ra=yn.create,Aa=Se.create,Oa=Q.create,Pa=Q.strictCreate,Da=Ft.create,La=En.create,Na=Bt.create,Ma=Pe.create,ja=Zt.create,$a=vn.create,Ua=ot.create,Fa=_t.create,Ba=Gt.create,Za=Ht.create,Ga=Ve.create,Ha=Vt.create,Va=St.create,Xs=ke.create,za=Ae.create,Ka=ze.create,Wa=ke.createWithPreprocess,Ya=Yt.create,Qa=()=>Ti().optional(),Xa=()=>Ei().optional(),Ja=()=>xi().optional(),qa={string:e=>we.create({...e,coerce:!0}),number:e=>Ge.create({...e,coerce:!0}),boolean:e=>jt.create({...e,coerce:!0}),bigint:e=>He.create({...e,coerce:!0}),date:e=>it.create({...e,coerce:!0})},ec=R;var a=Object.freeze({__proto__:null,defaultErrorMap:bt,setErrorMap:Wo,getErrorMap:pn,makeIssue:hn,EMPTY_PATH:Yo,addIssueToContext:y,ParseStatus:ue,INVALID:R,DIRTY:yt,OK:pe,isAborted:ns,isDirty:ss,isValid:rt,isAsync:Mt,get util(){return B},get objectUtil(){return ts},ZodParsedType:b,getParsedType:Me,ZodType:N,datetimeRegex:wi,ZodString:we,ZodNumber:Ge,ZodBigInt:He,ZodBoolean:jt,ZodDate:it,ZodSymbol:gn,ZodUndefined:$t,ZodNull:Ut,ZodAny:wt,ZodUnknown:nt,ZodNever:$e,ZodVoid:yn,ZodArray:Se,ZodObject:Q,ZodUnion:Ft,ZodDiscriminatedUnion:En,ZodIntersection:Bt,ZodTuple:Pe,ZodRecord:Zt,ZodMap:vn,ZodSet:ot,ZodFunction:_t,ZodLazy:Gt,ZodLiteral:Ht,ZodEnum:Ve,ZodNativeEnum:Vt,ZodPromise:St,ZodEffects:ke,ZodTransformer:ke,ZodOptional:Ae,ZodNullable:ze,ZodDefault:zt,ZodCatch:Kt,ZodNaN:_n,BRAND:ya,ZodBranded:Os,ZodPipeline:Yt,ZodReadonly:Wt,custom:ki,Schema:N,ZodSchema:N,late:va,get ZodFirstPartyTypeKind(){return C},coerce:qa,any:xa,array:Aa,bigint:wa,boolean:xi,date:Sa,discriminatedUnion:La,effect:Xs,enum:Ga,function:Fa,instanceof:_a,intersection:Na,lazy:Ba,literal:Za,map:$a,nan:ba,nativeEnum:Ha,never:Ca,null:Ea,nullable:Ka,number:Ei,object:Oa,oboolean:Ja,onumber:Xa,optional:za,ostring:Qa,pipeline:Ya,preprocess:Wa,promise:Va,record:ja,set:Ua,strictObject:Pa,string:Ti,symbol:ka,transformer:Xs,tuple:Ma,undefined:Ta,union:Da,unknown:Ia,void:Ra,NEVER:ec,ZodIssueCode:m,quotelessJson:Ko,ZodError:ye});const O=a.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),qt=a.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),en=a.string().min(1).max(32768),A=a.string().regex(/^[a-f0-9]{12}$/),$n=a.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),tn=a.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),Js=a.string().regex(/^[a-f0-9]{32}$/),Un=a.string().min(1).max(4096).regex(/^(\/|[A-Za-z]:[\\/])/),qs=/^[a-f0-9]{32}$/,Y=a.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),Et=a.string().regex(/^[A-Za-z0-9_-]{1,128}$/),er=a.object({data_b64:a.string().min(1).max(1e6),mime_type:a.enum(["image/png","image/jpeg","image/gif","image/webp"])}).strict(),tr=2e5,tc=256,nc=100,nr=16,sc=1e6,je=a.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),nn=a.object({kind:a.enum(["agent","team"]),name:je}).strict(),Fn=a.object({provider:a.string().min(1).max(128),model_id:a.string().min(1).max(512),reasoning_effort:a.string().min(1).max(64).nullable()}).strict(),sr=a.object({kind:a.enum(["role","specialist"]).optional(),description:a.string().max(8e3).optional(),instructions:a.string().max(8e3).optional(),tools:a.array(a.string().min(1).max(128)).max(256).optional(),effort:a.string().max(64).optional(),delegate:a.boolean().optional()}).strict(),rr=a.object({name:a.string().min(1).max(64).optional(),description:a.string().max(8e3).optional(),manager:je.optional(),members:a.array(a.object({role:je,count:a.number().int().min(1).max(16),kind:a.enum(["agent","team"])}).strict()).max(128).optional(),instructions:a.string().max(8e3).optional(),project:a.string().max(8e3).optional()}).strict(),rc=a.record(a.array(a.string().max(1024)).max(100)),ir=a.enum(["minutes","hours","days"]);function ic(e){return!/^\.+$/.test(e)}const ch=e=>cn.safeParse(e).success,cn=a.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(ic),or=a.enum(["str","int","float","bool","list","dict"]),ar=a.string().max(16384),oc=2e3,cr=a.string().min(1).max(oc),lr=a.string().min(1).max(64),dr=a.object({is_active:a.boolean().nullish(),one_time:a.boolean().nullish(),start_time_utc:a.string().max(64).nullish(),end_time_utc:a.string().max(64).nullish()}).strict(),ac=a.object({conversation_length:a.number().int().optional(),detail_length:a.number().int().optional(),max_learnings_history:a.number().int().optional(),hosting:a.string().max(256).optional(),model_name:a.string().max(1024).optional(),auto_save_conversation:a.boolean().optional()}).strict(),is=128,ur=2e3,fr=8e3,pr=64,hr=64,xn=e=>[...e].length,os=e=>e>=9&&e<=13||e>=28&&e<=32||e===133||e===160||e===5760||e>=8192&&e<=8202||e===8232||e===8233||e===8239||e===8287||e===12288,cc=e=>e===9||e===10||e===11||e===12||e===13||e===133,lc=e=>e<=31||e>=127&&e<=159,dc=e=>new RegExp("\\p{Cf}","u").test(String.fromCodePoint(e)),uc=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,sn=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},Ii=e=>{const t=[...e];let n=0,s=t.length;for(;n<s&&os(t[n].codePointAt(0)??0);)n++;for(;s>n&&os(t[s-1].codePointAt(0)??0);)s--;return t.slice(n,s).join("")},fc=e=>{let t="",n=!1;for(const s of e){if(os(s.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=s}return t};function pc(e){const t=Ii(e);if(!t)return"must not be empty";if(xn(t)>is)return`must be at most ${is} characters`;if(/[/\\:]/.test(t))return'must not contain "/", "\\" or ":"';if(sn(t,uc))return"must not contain Unicode bidirectional override characters";if(sn(t,cc))return"must not contain whitespace";if(sn(t,lc))return"must not contain control characters";if(sn(t,dc))return"must not contain invisible Unicode formatting characters";const n=[...t];return"-.".includes(n[0])||"-.".includes(n[n.length-1])?'must not begin or end with "-" or "."':null}function lh(e){return fc(Ii(e).normalize("NFKC").toLowerCase())}function hc(e){return e.trim()?xn(e)>ur?`must be at most ${ur} characters`:null:"must not be empty"}function mc(e){return e.trim()?xn(e)>fr?`must be at most ${fr} characters`:null:"must not be empty"}function gc(e){if(e.length>hr)return`must hold at most ${hr} items`;for(const t of e)if(!t.trim()||xn(t)>pr)return`must hold items of 1 to ${pr} characters`;return null}const yc=e=>pc(e)===null,vc=a.string().refine(yc,{message:"That is not a name the hub can publish."}),_c=a.string().refine(e=>mc(e)===null,{message:"That instruction body cannot be published."}),bc=a.string().refine(e=>hc(e)===null,{message:"That description cannot be published."}),wc=a.array(a.string()).refine(e=>gc(e)===null,{message:"That tool list cannot be published."}),mr=a.object({name:vc,description:bc,instructions:_c,kind:a.enum(["role","specialist"]),when_to_use:a.string(),tools:wc,effort:a.string(),delegate:a.boolean(),version:a.string(),categories:a.array(a.string()),tags:a.array(a.string())}).partial().strict(),Sc=a.enum(["team","agent"]),kc=a.string().min(1).max(64),Tc=a.string().min(1).max(256),Ci=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Bn=a.string().regex(Ci,{message:"Letters, digits, dot, underscore and dash; no spaces."}),Ec=["planning","active","qa","validation","done","paused","archived"],gr=a.enum(Ec),rn=a.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),yr=a.array(a.string().min(1).max(24)).max(8),Je=a.string().min(1).max(64),xc=1e3,vr=240,_r=80,Ic=/^[a-z0-9][a-z0-9_-]{0,23}$/;function dh(e){return e?Ci.test(e)?null:"Names start with a letter or digit and may use letters, digits, dot, underscore or dash.":"Give the project a name."}function uh(e){return Ic.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const Cc=a.discriminatedUnion("op",[a.object({op:a.literal("capabilities")}).strict(),a.object({op:a.literal("profiles.list")}).strict(),a.object({op:a.literal("profiles.get"),name:je}).strict(),a.object({op:a.literal("profiles.install"),name:je,requestId:Y}).strict(),a.object({op:a.literal("profiles.create"),name:je,requestId:Y,fields:sr.extend({description:a.string().max(8e3),instructions:a.string().min(1).max(8e3)})}).strict(),a.object({op:a.literal("profiles.update"),name:je,requestId:Y,fields:sr}).strict(),a.object({op:a.literal("teams.list")}).strict(),a.object({op:a.literal("teams.get"),name:je}).strict(),a.object({op:a.literal("teams.create"),requestId:Y,fields:rr.extend({name:a.string().min(1).max(64)})}).strict(),a.object({op:a.literal("teams.update"),name:je,requestId:Y,fields:rr}).strict(),a.object({op:a.literal("sessions.list"),limit:a.number().int().min(1).max(500).optional(),include_archived:a.boolean().optional(),include_peers:a.boolean().optional(),scope_kind:Sc.optional(),scope_name:kc.optional(),cursor:Tc.optional(),with_counts:a.boolean().optional()}).strict(),a.object({op:a.literal("sessions.search"),q:a.string().min(1).max(tc),limit:a.number().int().min(1).max(500).optional(),include_archived:a.boolean().optional()}).strict(),a.object({op:a.literal("sessions.archive"),sessionId:A,archived:a.boolean()}).strict(),a.object({op:a.literal("sessions.delete"),sessionId:A,confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("sessions.create"),requestId:Y,cwd:a.string().min(1).max(4096),target:nn.optional(),model:Fn.optional(),draftId:A.optional()}).strict(),a.object({op:a.literal("sessions.preview"),requestId:Y,cwd:a.string().min(1).max(4096),target:nn.optional(),model:Fn.optional()}).strict(),a.object({op:a.literal("sessions.draft"),requestId:Y,cwd:a.string().min(1).max(4096),target:nn.optional(),model:Fn.optional()}).strict(),a.object({op:a.literal("sessions.get"),sessionId:A}).strict(),a.object({op:a.literal("sessions.history"),sessionId:A,beforeId:O.optional(),limit:a.number().int().min(1).max(500).optional()}).strict(),a.object({op:a.literal("sessions.checkpoints"),sessionId:A}).strict(),a.object({op:a.literal("sessions.checkpoints.warm"),sessionId:A,ids:a.array(O).max(nr).optional(),limit:a.number().int().min(1).max(nr).optional()}).strict(),a.object({op:a.literal("subagents.transcript"),sessionId:A,childId:A,beforeId:O.optional(),limit:a.number().int().min(1).max(500).optional()}).strict(),a.object({op:a.literal("sessions.message"),sessionId:A,requestId:Y,text:a.string().max(tr),images:a.array(er).max(8).optional(),mode:a.enum(["prompt","steer"]).optional(),inputMode:a.enum(["typed","dictated","mixed"]).optional(),inputPath:a.string().max(1024).optional()}).strict(),a.object({op:a.literal("sessions.command"),sessionId:A,requestId:Y,command:a.string().regex(/^\/?[A-Za-z]+$/).max(64),args:a.string().max(tr).optional(),images:a.array(er).max(8).optional()}).strict(),a.object({op:a.literal("sessions.move"),sessionId:A,requestId:Y,cwd:a.string().min(1).max(4096)}).strict(),a.object({op:a.literal("sessions.answer"),sessionId:A,epoch:O,requestId:O,value:a.string().max(32768).optional(),approved:a.boolean().optional(),questionIndex:a.number().int().min(0).optional()}).strict(),a.object({op:a.literal("sessions.seen"),sessionId:A,completionToken:a.string().uuid()}).strict(),a.object({op:a.literal("attention.seen"),items:a.array(a.object({sessionId:A,completionToken:a.string().uuid()}).strict()).min(1).max(500)}).strict(),a.object({op:a.literal("sessions.notified"),sessionId:A,completionToken:a.string().uuid()}).strict(),a.object({op:a.literal("sessions.pin"),sessionId:A,pinned:a.boolean()}).strict(),a.object({op:a.literal("sessions.watch"),sessionId:A,subscriptionId:a.string().regex(qs),visible:a.boolean(),canNotify:a.boolean()}).strict(),a.object({op:a.literal("sessions.warm"),sessionId:A}).strict(),a.object({op:a.literal("sessions.interrupt"),sessionId:A,requestId:Y}).strict(),a.object({op:a.literal("sessions.variables.list"),sessionId:A}).strict(),a.object({op:a.literal("sessions.variables.create"),sessionId:A,key:cn,value:ar,type:or}).strict(),a.object({op:a.literal("sessions.variables.update"),sessionId:A,key:cn,value:ar,type:or}).strict(),a.object({op:a.literal("sessions.variables.delete"),sessionId:A,key:cn}).strict(),a.object({op:a.literal("sessions.presence"),subscriptionId:a.string().regex(/^[a-f0-9]{1,64}$/),canNotify:a.boolean(),canNotifyKinds:a.array(a.enum(["complete","error"])).max(4),sessionId:a.string().regex(/^([a-f0-9]{12})?$/),window:a.object({exists:a.boolean(),focused:a.boolean(),visible:a.boolean(),minimized:a.boolean()}).strict()}).strict(),a.object({op:a.literal("legacy.models"),provider:a.string().max(128).optional(),sort:a.enum(["id","name","provider","recommended"]).optional(),direction:a.enum(["ascending","descending"]).optional()}).strict(),a.object({op:a.literal("legacy.models.providers")}).strict(),a.object({op:a.literal("auth.probe"),provider:O}).strict(),a.object({op:a.literal("legacy.agent.upload"),agentId:O}).strict(),a.object({op:a.literal("agent.publish"),agentId:O,document:mr.optional(),visibility:a.literal("org").optional(),tenantId:O.optional()}).strict(),a.object({op:a.literal("agent.republish"),agentId:O,hubAgentId:O,document:mr.optional(),visibility:a.literal("org").optional(),tenantId:O.optional()}).strict(),a.object({op:a.literal("team.pull"),teamId:O,tenantId:O.optional()}).strict(),a.object({op:a.literal("agent.nameAvailability"),name:a.string().min(1).max(is)}).strict(),a.object({op:a.literal("legacy.agents.list"),page:a.number().int().min(1).optional(),perPage:a.number().int().min(1).max(500).optional(),name:a.string().max(256).optional(),sort:a.string().max(64).optional(),direction:a.enum(["asc","desc"]).optional()}).strict(),a.object({op:a.literal("legacy.agent.get"),agentId:O}).strict(),a.object({op:a.literal("legacy.agent.history"),agentId:O,page:a.number().int().min(1).optional(),perPage:a.number().int().min(1).max(500).optional()}).strict(),a.object({op:a.literal("legacy.jobs.list"),agentId:O.optional(),status:a.string().max(64).optional()}).strict(),a.object({op:a.literal("legacy.job.get"),jobId:O}).strict(),a.object({op:a.literal("legacy.schedules.list"),page:a.number().int().min(1).optional(),perPage:a.number().int().min(1).max(100).optional()}).strict(),a.object({op:a.literal("legacy.agent.schedules.list"),agentId:O,page:a.number().int().min(1).optional(),perPage:a.number().int().min(1).max(100).optional()}).strict(),a.object({op:a.literal("legacy.agent.schedule.create"),agentId:O,schedule:dr.extend({prompt:a.string().max(64e3),interval:a.number().int().min(1),unit:ir})}).strict(),a.object({op:a.literal("legacy.schedule.get"),scheduleId:O}).strict(),a.object({op:a.literal("legacy.schedule.edit"),scheduleId:O,schedule:dr.extend({prompt:a.string().max(64e3).nullish(),interval:a.number().int().min(1).nullish(),unit:ir.nullish()})}).strict(),a.object({op:a.literal("legacy.schedule.remove"),scheduleId:O}).strict(),a.object({op:a.literal("legacy.agent.create"),agent:a.record(a.unknown())}).strict(),a.object({op:a.literal("legacy.agent.update"),agentId:O,update:a.record(a.unknown())}).strict(),a.object({op:a.literal("legacy.agent.delete"),agentId:O}).strict(),a.object({op:a.literal("legacy.agent.conversation.clear"),agentId:O}).strict(),a.object({op:a.literal("legacy.agent.systemPrompt.get"),agentId:O}).strict(),a.object({op:a.literal("legacy.agent.systemPrompt.update"),agentId:O,systemPrompt:a.string().max(sc)}).strict(),a.object({op:a.literal("legacy.agent.download"),agentId:O}).strict(),a.object({op:a.literal("legacy.job.cancel"),jobId:O}).strict(),a.object({op:a.literal("commands.list")}).strict(),a.object({op:a.literal("commands.entities"),sessionId:A,command:O,name:a.string().max(128).optional()}).strict(),a.object({op:a.literal("models.catalogue"),live:a.boolean().optional()}).strict(),a.object({op:a.literal("usage.get"),provider:O.optional(),live:a.boolean().optional(),refresh:a.boolean().optional()}).strict(),a.object({op:a.literal("analytics.get"),sessionId:A.optional(),sinceMs:a.number().int().nonnegative().optional(),untilMs:a.number().int().nonnegative().optional(),days:a.number().int().min(1).max(366).optional()}).strict(),a.object({op:a.literal("analytics.models"),sessionId:A.optional(),sinceMs:a.number().int().nonnegative().optional(),untilMs:a.number().int().nonnegative().optional(),days:a.number().int().min(1).max(366).optional()}).strict(),a.object({op:a.literal("info.get")}).strict(),a.object({op:a.literal("sessions.report"),sessionId:A,recentLimit:a.number().int().min(0).max(50).optional()}).strict(),a.object({op:a.literal("skills.list"),sessionId:A,name:O.optional()}).strict(),a.object({op:a.literal("sessions.failovers"),sessionId:A}).strict(),a.object({op:a.literal("sessions.credential"),sessionId:A,action:a.enum(["list","store","forget"]),key:qt.optional(),value:en.optional(),confirmed:a.boolean().optional()}).strict(),a.object({op:a.literal("sessions.fork"),sessionId:A,requestId:Y,message:a.string().max(2e5).optional(),boundary:a.literal("next_safe").optional()}).strict(),a.object({op:a.literal("sessions.stop"),requestId:Y,targets:a.array(A).min(1).max(100),confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("sessions.aside"),sessionId:A,requestId:Y,text:a.string().min(1).max(32768),asideId:Y.optional(),subscriptionId:a.string().regex(qs).optional()}).strict(),a.object({op:a.literal("sessions.adopt"),sessionId:A,requestId:Y,asideId:Y,confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("sessions.aside.get"),sessionId:A,asideId:Y}).strict(),a.object({op:a.literal("sessions.aside.close"),sessionId:A,asideId:Y}).strict(),a.object({op:a.literal("wakes.list"),limit:a.number().int().min(1).max(500).optional(),includeDormant:a.boolean().optional()}).strict(),a.object({op:a.literal("wakes.create"),requestId:Y,sessionId:A.optional(),cwd:a.string().min(1).max(4096).optional(),target:nn.optional(),message:cr,in:a.string().min(1).max(64).optional(),at:a.string().min(1).max(64).optional(),every:a.string().min(1).max(64).optional(),until:a.string().min(1).max(64).optional(),limit:a.number().int().min(1).optional(),title:a.string().min(1).max(200).optional()}).strict(),a.object({op:a.literal("wakes.edit"),sessionId:A,wakeId:lr,message:cr.optional(),in:a.string().min(1).max(64).optional(),at:a.string().min(1).max(64).optional(),every:a.string().min(1).max(64).optional(),until:a.string().min(1).max(64).optional(),limit:a.number().int().min(1).optional()}).strict(),a.object({op:a.literal("wakes.remove"),sessionId:A,wakeId:lr}).strict(),a.object({op:a.literal("mcp.list"),sessionId:A}).strict(),a.object({op:a.literal("mcp.credentials.store"),sessionId:A,name:a.string().min(1).max(256),values:a.record(a.string().min(1).max(128),a.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:a.array(a.string().min(1).max(128)).max(32)}).strict(),a.object({op:a.literal("mcp.control"),sessionId:A,control:a.object({action:a.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:$n.optional(),scope:a.enum(["global","project"]).optional(),command:a.string().min(1).max(4096).optional(),args:a.array(a.string().max(8192)).max(128).optional(),env:a.record(tn).optional(),url:a.string().max(4096).optional(),headers:a.record(tn).optional(),oauth:a.boolean().optional(),confirmed:a.boolean().optional(),operation_id:Js.optional()}).strict()}).strict(),a.object({op:a.literal("mcp.catalog"),cwd:Un.optional(),sessionId:A.optional()}).strict(),a.object({op:a.literal("mcp.catalog.control"),cwd:Un.optional(),control:a.object({action:a.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:$n.optional(),scope:a.enum(["global","project"]).optional(),command:a.string().min(1).max(4096).optional(),args:a.array(a.string().max(8192)).max(128).optional(),env:a.record(tn).optional(),url:a.string().max(4096).optional(),headers:a.record(tn).optional(),confirmed:a.boolean().optional(),operation_id:Js.optional()}).strict()}).strict(),a.object({op:a.literal("mcp.catalog.credentials"),header:a.string().min(1).max(128).optional(),cwd:Un.optional(),name:$n,values:a.record(a.string().min(1).max(128),a.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:a.array(a.string().min(1).max(128)).max(32)}).strict(),a.object({op:a.literal("radient.request"),control:a.object({operation:a.enum(["account","prices","credits","usage","provision","application.create","agents.list","agents.get","agents.create","agents.update","agents.delete","agents.like","agents.unlike","agents.liked","agents.like_count","agents.favourite","agents.unfavourite","agents.favourited","agents.favourite_count","agents.download_count","agents.statuses","comments.list","comments.create","comments.update","comments.delete","account.agents","memberships.list","org_agents.list","org_team.get","org_teams.list"]),request_id:Y.optional(),tenant_id:O.optional(),account_id:O.optional(),agent_id:O.optional(),comment_id:O.optional(),team_id:O.optional(),query:a.record(a.union([a.string().max(1024),a.number().int()])).optional(),payload:a.record(a.unknown()).optional(),confirmed:a.boolean().optional()}).strict()}).strict(),a.object({op:a.literal("providers.list")}).strict(),a.object({op:a.literal("accounts.list")}).strict(),a.object({op:a.literal("accounts.remove"),accountId:a.number().int().positive(),confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("auth.start"),provider:O}).strict(),a.object({op:a.literal("auth.status"),id:O}).strict(),a.object({op:a.literal("auth.input"),id:O,promptId:O,value:en}).strict(),a.object({op:a.literal("auth.cancel"),id:O}).strict(),a.object({op:a.literal("auth.key"),provider:O,value:en}).strict(),a.object({op:a.literal("auth.logout"),provider:O}).strict(),a.object({op:a.literal("settings.list")}).strict(),a.object({op:a.literal("settings.edit"),key:qt,value:a.unknown().refine(e=>e!==void 0,"A setting value is required."),base:rc.optional()}).strict(),a.object({op:a.literal("settings.reset"),key:qt}).strict(),a.object({op:a.literal("config.get")}).strict(),a.object({op:a.literal("config.update"),value:ac}).strict(),a.object({op:a.literal("instructions.get")}).strict(),a.object({op:a.literal("instructions.update"),content:a.string().max(64e3)}).strict(),a.object({op:a.literal("credentials.list")}).strict(),a.object({op:a.literal("credentials.update"),key:qt,value:en}).strict(),a.object({op:a.literal("peers.list")}).strict(),a.object({op:a.literal("networks.list")}).strict(),a.object({op:a.literal("networks.invite"),networkId:Et,role:a.enum(["read","drive","admin"]),deviceId:Et.optional()}).strict(),a.object({op:a.literal("networks.member.remove"),networkId:Et,deviceId:Et,confirm:a.string().min(1).max(256)}).strict(),a.object({op:a.literal("sessions.transfer"),sessionId:A,to:a.union([a.literal("local"),Et]),keep:a.boolean().optional(),waitS:a.number().min(0).max(300).optional(),requestId:Y.optional()}).strict(),a.object({op:a.literal("projects.list")}).strict(),a.object({op:a.literal("projects.get"),key:Je}).strict(),a.object({op:a.literal("projects.create"),name:Bn,description:a.string().max(vr).optional(),status:gr.optional(),tags:yr.optional()}).strict(),a.object({op:a.literal("projects.update"),key:Je,fields:a.object({name:Bn.optional(),title:a.string().max(80).optional(),owner:a.string().max(80).optional(),team:a.string().max(80).optional(),description:a.string().max(vr).optional(),status:gr.optional(),progress:a.string().max(xc).optional(),tags:yr.optional(),start_date:rn.optional(),target_date:rn.optional(),completed_at:rn.optional(),estimate:a.number().positive().max(1e3).optional(),estimate_unit:a.enum(["points","days"]).optional()}).strict()}).strict(),a.object({op:a.literal("projects.delete"),key:Je,confirmed_name:Bn}).strict(),a.object({op:a.literal("projects.link"),key:Je,sessionId:A}).strict(),a.object({op:a.literal("projects.unlink"),key:Je,sessionId:A}).strict(),a.object({op:a.literal("projects.milestone"),key:Je,name:a.string().min(1).max(_r),targetDate:rn.optional(),completed:a.boolean().optional()}).strict(),a.object({op:a.literal("projects.milestone.remove"),key:Je,name:a.string().min(1).max(_r)}).strict(),a.object({op:a.literal("aida.status")}).strict(),a.object({op:a.literal("aida.control"),action:a.enum(["open","pause","resume","greet","status"])}).strict()]);Cc.superRefine((e,t)=>{e.op!=="agent.publish"&&e.op!=="agent.republish"||e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:a.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})});const _e={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},Rc={runtimeUnreachable:"runtime_unreachable"},Ps="runtime_busy",Ri="runtime_retiring",Ds={[_e.noCredential]:"This app is not paired with the running Local Operator server, so this control is unavailable.",[_e.refused]:"This app's credential for the running Local Operator server was refused, so this control is unavailable.",[_e.planeClosed]:"The running Local Operator server does not accept this app's desktop controls.",[_e.transportFailed]:"The Local Operator server did not answer this request."},as={noCredential:"Restart with a desktop-managed backend to use these controls.",transportFailed:"The backend could not complete this request. Check its connection and try again."};function Ls(e){return e!==void 0&&Object.values(_e).includes(e)}function Ac(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return _e.refused;if(t===503)return _e.planeClosed}}const Oc=88e4,Pc=11e5,Dc=2e4,Lc=9e4,Nc=new Set(["analytics.get","analytics.models","sessions.report"]),Mc=new Set(["usage.get"]),jc=new Set(["networks.list","peers.list"]),$c=new Set([...Nc,...Mc,...jc]),Uc=90,Fc=30,Bc=300,Zc=10,Gc=15,Hc=1e4;function Vc(e){const n=e.to==="local"||e.keep?Bc:Fc,s=Math.max(0,e.waitS??0);return(Uc+n+Zc+Gc)*1e3+s*1e3}function zc(e){if(typeof e!="string"&&e.op==="sessions.transfer")return Vc(e)+Hc;const t=typeof e=="string"?e:e.op;return $c.has(t)?Lc:Dc}const Kc=5e3;function Ai(e){return zc(e)+Kc}const Ns="deadline_exceeded",Wc="foreground_required",Oi="View these completions in the foreground before marking them read.",Yc=new Set(["capabilities","accounts.list","analytics.get","analytics.models","commands.entities","commands.list","config.get","credentials.list","info.get","instructions.get","legacy.agent.get","legacy.agent.history","legacy.agent.schedules.list","legacy.agents.list","legacy.job.get","legacy.jobs.list","legacy.models","legacy.models.providers","legacy.schedule.get","legacy.schedules.list","mcp.catalog","mcp.list","models.catalogue","networks.list","peers.list","profiles.get","profiles.list","providers.list","sessions.aside.get","sessions.checkpoints","sessions.failovers","sessions.get","sessions.history","sessions.list","sessions.preview","sessions.report","sessions.search","sessions.variables.list","skills.list","subagents.transcript","teams.get","teams.list","usage.get"]),Qc=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function Xc(e,t){const n=Math.round(t/1e3),s=Ns;return e==="sessions.transfer"?{code:s,message:`The app waits up to ${n} seconds for a move, and it was still running when the app stopped waiting. The move was asked for, so its outcome is unknown from here: read the session again before moving it anywhere else.`}:Yc.has(e)?{code:s,message:Qc.has(e)?`The app waits up to ${n} seconds for this panel's data, and the read was still running when the app stopped waiting. Nothing was read; reopen the panel to ask again.`:`The app waits up to ${n} seconds for this read, and it was still running when the app stopped waiting. Nothing was read; ask again.`}:{code:s,message:`The app waits up to ${n} seconds for this request, and it was still running when the app stopped waiting. It may or may not have reached the server; check the result before repeating it.`}}const fh=Oc,ph=Pc;function Jc(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function br(e){return{...e.in!==void 0?{in:e.in}:{},...e.at!==void 0?{at:e.at}:{},...e.every!==void 0?{every:e.every}:{},...e.until!==void 0?{until:e.until}:{},...e.limit!==void 0?{limit:e.limit}:{}}}function wr(e){if(e.visibility==="org"!=!!e.tenantId)throw new Error('A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.')}function qc(e){switch(e.op){case"capabilities":return{path:"/v1/capabilities",method:"GET"};case"peers.list":return{path:"/v1/desktop/peers",method:"GET"};case"networks.list":return{path:"/v1/desktop/networks",method:"GET"};case"networks.invite":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/invite`,method:"POST",body:{role:e.role,device:e.deviceId??null}};case"networks.member.remove":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/members/${encodeURIComponent(e.deviceId)}`,method:"DELETE",body:{confirm:e.confirm}};case"sessions.transfer":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/transfer`,method:"POST",body:{to:e.to,keep:e.keep??!1,wait_s:e.waitS??0,...e.requestId?{request_id:e.requestId}:{}}};case"profiles.list":return{path:"/v1/desktop/profiles",method:"GET"};case"profiles.get":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"GET"};case"profiles.install":return{path:"/v1/desktop/profiles/install",method:"POST",body:{request_id:e.requestId,name:e.name}};case"profiles.create":return{path:"/v1/desktop/profiles",method:"POST",body:{request_id:e.requestId,name:e.name,...e.fields}};case"profiles.update":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields}};case"teams.list":return{path:"/v1/desktop/teams",method:"GET"};case"teams.get":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"GET"};case"teams.create":return{path:"/v1/desktop/teams",method:"POST",body:{request_id:e.requestId,...e.fields}};case"teams.update":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields}};case"sessions.list":{const t=new URLSearchParams;return t.set("limit",String(e.limit??100)),e.include_archived&&t.set("include_archived","true"),e.scope_kind&&t.set("scope_kind",e.scope_kind),e.scope_name&&t.set("scope_name",e.scope_name),e.cursor&&t.set("cursor",e.cursor),e.with_counts&&t.set("with_counts","true"),e.include_peers&&t.set("include_peers","true"),{path:`/v1/desktop/sessions?${t}`,method:"GET"}}case"sessions.search":{const t=new URLSearchParams({q:e.q,limit:String(e.limit??nc)});return e.include_archived&&t.set("include_archived","true"),{path:`/v1/desktop/sessions/search?${t}`,method:"GET"}}case"sessions.archive":return{path:`/v1/desktop/sessions/${e.sessionId}/archive`,method:"POST",body:{archived:e.archived}};case"sessions.delete":return{path:`/v1/desktop/sessions/${e.sessionId}`,method:"DELETE",body:{confirmed:!0}};case"sessions.create":return{path:"/v1/desktop/sessions",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{},...e.draftId?{draft_id:e.draftId}:{}}};case"sessions.preview":return{path:"/v1/desktop/sessions/preview",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}}};case"sessions.draft":return{path:"/v1/desktop/sessions/draft",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}}};case"sessions.get":return{path:`/v1/desktop/sessions/${e.sessionId}`,method:"GET"};case"sessions.history":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),{path:`/v1/desktop/sessions/${e.sessionId}/history?${t}`,method:"GET"}}case"sessions.checkpoints":return{path:`/v1/desktop/sessions/${e.sessionId}/checkpoints`,method:"GET"};case"sessions.checkpoints.warm":return{path:`/v1/desktop/sessions/${e.sessionId}/checkpoints/warm`,method:"POST",body:{...e.ids?{ids:e.ids}:{},...e.limit!==void 0?{limit:e.limit}:{}}};case"subagents.transcript":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),{path:`/v1/desktop/sessions/${e.sessionId}/children/${e.childId}/transcript?${t}`,method:"GET"}}case"sessions.message":return{path:`/v1/desktop/sessions/${e.sessionId}/messages`,method:"POST",body:{request_id:e.requestId,text:e.text,images:e.images??[],mode:e.mode??"prompt",...e.inputMode?{input_mode:e.inputMode}:{},...e.inputPath?{input_path:e.inputPath}:{}}};case"sessions.command":return{path:`/v1/desktop/sessions/${e.sessionId}/commands`,method:"POST",body:{request_id:e.requestId,command:e.command,args:e.args??"",images:e.images??[]}};case"sessions.answer":return{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{epoch:e.epoch,request_id:e.requestId,value:e.value,approved:e.approved,question_index:e.questionIndex}};case"sessions.seen":return{path:`/v1/desktop/sessions/${e.sessionId}/seen`,method:"POST",body:{completion_token:e.completionToken}};case"attention.seen":return{path:"/v1/desktop/attention/seen",method:"POST",body:{items:e.items.map(t=>({session_id:t.sessionId,completion_token:t.completionToken}))}};case"sessions.notified":return{path:`/v1/desktop/sessions/${e.sessionId}/notified`,method:"POST",body:{completion_token:e.completionToken}};case"sessions.pin":return{path:`/v1/desktop/sessions/${e.sessionId}/pin`,method:"POST",body:{pinned:e.pinned}};case"sessions.watch":return{path:`/v1/desktop/sessions/${e.sessionId}/watch`,method:"POST",body:{subscription_id:e.subscriptionId,visible:e.visible,can_notify:e.canNotify}};case"sessions.presence":return{path:"/v1/desktop/presence",method:"POST",body:{subscription_id:e.subscriptionId,can_notify_kinds:e.canNotifyKinds,session_id:e.sessionId,window:e.window,can_notify:e.canNotify}};case"sessions.move":return{path:`/v1/desktop/sessions/${e.sessionId}/working-directory`,method:"POST",body:{request_id:e.requestId,cwd:e.cwd}};case"sessions.warm":return{path:`/v1/desktop/sessions/${e.sessionId}/warm`,method:"POST",body:{}};case"sessions.interrupt":return{path:`/v1/desktop/sessions/${e.sessionId}/interrupt`,method:"POST",body:{request_id:e.requestId}};case"sessions.variables.list":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"GET"};case"sessions.variables.create":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"POST",body:{key:e.key,value:e.value,type:e.type}};case"sessions.variables.update":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"PATCH",body:{value:e.value,type:e.type}};case"sessions.variables.delete":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"DELETE"};case"legacy.models":{const t=new URLSearchParams;return e.provider&&t.set("provider",e.provider),e.sort&&t.set("sort",e.sort),e.direction&&t.set("direction",e.direction),{path:t.size>0?`/v1/models?${t}`:"/v1/models",method:"GET"}}case"legacy.models.providers":return{path:"/v1/models/providers",method:"GET"};case"auth.probe":return{path:`/v1/auth/providers/${e.provider}/probe`,method:"POST"};case"legacy.agent.upload":return{path:`/v1/agents/${e.agentId}/upload`,method:"POST"};case"agent.publish":{wr(e);const t=new URLSearchParams;e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId));const n=t.toString();return{path:`/v1/agents/${e.agentId}/publish${n?`?${n}`:""}`,method:"POST",body:{document:e.document??{}}}}case"agent.republish":{wr(e);const t=new URLSearchParams;e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId));const n=t.toString();return{path:`/v1/agents/${e.agentId}/publish${n?`?${n}`:""}`,method:"PUT",body:{hub_agent_id:e.hubAgentId,document:e.document??{}}}}case"team.pull":{const t=new URLSearchParams;e.tenantId&&t.set("tenant_id",e.tenantId);const n=t.toString();return{path:`/v1/teams/pull/${e.teamId}${n?`?${n}`:""}`,method:"GET"}}case"agent.nameAvailability":return{path:`/v1/agent-name-availability?${new URLSearchParams({name:e.name})}`,method:"GET"};case"legacy.agents.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return e.name&&t.set("name",e.name),e.sort&&t.set("sort",e.sort),e.direction&&t.set("direction",e.direction),{path:`/v1/agents?${t}`,method:"GET"}}case"legacy.agent.get":return{path:`/v1/agents/${e.agentId}`,method:"GET"};case"legacy.agent.history":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/history?${t}`,method:"GET"}}case"wakes.list":{const t=new URLSearchParams;return e.limit!==void 0&&t.set("limit",String(e.limit)),e.includeDormant!==void 0&&t.set("include_dormant",String(e.includeDormant)),{path:t.size>0?`/v1/desktop/wakes?${t}`:"/v1/desktop/wakes",method:"GET"}}case"wakes.create":return{path:"/v1/desktop/wakes",method:"POST",body:{request_id:e.requestId,...Jc(e),message:e.message,...br(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...br(e)}};case"wakes.remove":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"DELETE"};case"legacy.jobs.list":{const t=new URLSearchParams;return e.agentId&&t.set("agent_id",e.agentId),e.status&&t.set("status",e.status),{path:t.size>0?`/v1/jobs?${t}`:"/v1/jobs",method:"GET"}}case"legacy.job.get":return{path:`/v1/jobs/${e.jobId}`,method:"GET"};case"legacy.schedules.list":return{path:`/v1/schedules?${new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)})}`,method:"GET"};case"legacy.agent.schedules.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/schedules?${t}`,method:"GET"}}case"legacy.agent.schedule.create":return{path:`/v1/agents/${e.agentId}/schedules`,method:"POST",body:e.schedule};case"legacy.schedule.get":return{path:`/v1/schedules/${e.scheduleId}`,method:"GET"};case"legacy.schedule.edit":return{path:`/v1/schedules/${e.scheduleId}`,method:"PATCH",body:e.schedule};case"legacy.schedule.remove":return{path:`/v1/schedules/${e.scheduleId}`,method:"DELETE"};case"legacy.agent.create":return{path:"/v1/agents",method:"POST",body:e.agent};case"legacy.agent.update":return{path:`/v1/agents/${e.agentId}`,method:"PATCH",body:e.update};case"legacy.agent.delete":return{path:`/v1/agents/${e.agentId}`,method:"DELETE"};case"legacy.agent.conversation.clear":return{path:`/v1/agents/${e.agentId}/conversation`,method:"DELETE"};case"legacy.agent.systemPrompt.get":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"GET"};case"legacy.agent.systemPrompt.update":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"PUT",body:{system_prompt:e.systemPrompt}};case"legacy.agent.download":return{path:`/v1/agents/${e.agentId}/download`,method:"GET"};case"legacy.job.cancel":return{path:`/v1/jobs/${e.jobId}`,method:"DELETE"};case"commands.list":return{path:"/v1/desktop/commands",method:"GET"};case"commands.entities":return{path:`/v1/desktop/sessions/${e.sessionId}/command-entities?command=${encodeURIComponent(e.command)}${e.name?`&name=${encodeURIComponent(e.name)}`:""}`,method:"GET"};case"models.catalogue":return{path:`/v1/desktop/models?live=${e.live??!1}`,method:"GET"};case"usage.get":{const t=new URLSearchParams({live:String(e.live??!1),refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),{path:`/v1/desktop/usage?${t}`,method:"GET"}}case"analytics.get":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics?${t}`,method:"GET"}}case"analytics.models":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics/models?${t}`,method:"GET"}}case"info.get":return{path:"/v1/desktop/info",method:"GET"};case"sessions.report":{const t=new URLSearchParams({recent_limit:String(e.recentLimit??12)});return{path:`/v1/desktop/sessions/${e.sessionId}/report?${t}`,method:"GET"}}case"skills.list":return{path:`/v1/desktop/skills?session_id=${e.sessionId}${e.name?`&name=${encodeURIComponent(e.name)}`:""}`,method:"GET"};case"sessions.failovers":return{path:`/v1/desktop/sessions/${e.sessionId}/failovers`,method:"GET"};case"sessions.credential":return{path:`/v1/desktop/sessions/${e.sessionId}/credentials`,method:"POST",body:{action:e.action,key:e.key,value:e.value,confirmed:e.confirmed}};case"sessions.fork":return{path:`/v1/desktop/sessions/${e.sessionId}/fork`,method:"POST",body:{request_id:e.requestId,message:e.message,boundary:e.boundary}};case"sessions.stop":return{path:"/v1/desktop/stop",method:"POST",body:{request_id:e.requestId,targets:e.targets,confirmed:e.confirmed}};case"sessions.aside":return{path:`/v1/desktop/sessions/${e.sessionId}/asides`,method:"POST",body:{request_id:e.requestId,text:e.text,aside_id:e.asideId,subscription_id:e.subscriptionId}};case"sessions.adopt":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}/adopt`,method:"POST",body:{request_id:e.requestId,confirmed:e.confirmed}};case"sessions.aside.get":case"sessions.aside.close":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}`,method:e.op==="sessions.aside.get"?"GET":"DELETE"};case"mcp.list":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"GET"};case"mcp.credentials.store":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp/credentials`,method:"POST",body:{name:e.name,values:e.values,confirmed_replace:e.confirmedReplace}};case"mcp.control":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"POST",body:e.control};case"mcp.catalog":{const t=new URLSearchParams;e.cwd&&t.set("cwd",e.cwd),e.sessionId&&t.set("session_id",e.sessionId);const n=t.toString();return{path:n?`/v1/desktop/mcp?${n}`:"/v1/desktop/mcp",method:"GET"}}case"mcp.catalog.control":return{path:"/v1/desktop/mcp",method:"POST",body:{...e.control,...e.cwd?{cwd:e.cwd}:{}}};case"mcp.catalog.credentials":return{path:"/v1/desktop/mcp/credentials",method:"POST",body:{name:e.name,values:e.values,...e.header?{header:e.header}:{},confirmed_replace:e.confirmedReplace,...e.cwd?{cwd:e.cwd}:{}}};case"radient.request":return{path:"/v1/desktop/radient",method:"POST",body:e.control};case"providers.list":return{path:"/v1/auth/providers",method:"GET"};case"accounts.list":return{path:"/v1/auth/status",method:"GET"};case"accounts.remove":return{path:`/v1/auth/accounts/${e.accountId}`,method:"DELETE"};case"auth.start":return{path:"/v1/auth/login",method:"POST",body:{provider:e.provider}};case"auth.status":return{path:`/v1/auth/operations/${e.id}`,method:"GET"};case"auth.input":return{path:`/v1/auth/operations/${e.id}/input`,method:"POST",body:{prompt_id:e.promptId,value:e.value}};case"auth.cancel":return{path:`/v1/auth/operations/${e.id}`,method:"DELETE"};case"auth.key":return{path:`/v1/auth/providers/${e.provider}/key`,method:"PUT",body:{value:e.value}};case"auth.logout":return{path:`/v1/auth/providers/${e.provider}/credentials`,method:"DELETE"};case"settings.list":return{path:"/v1/settings",method:"GET"};case"settings.edit":return{path:`/v1/settings/${e.key}`,method:"PATCH",body:{value:e.value,base:e.base}};case"settings.reset":return{path:`/v1/settings/${e.key}/reset`,method:"POST"};case"config.get":return{path:"/v1/config",method:"GET"};case"config.update":return{path:"/v1/config",method:"PATCH",body:e.value};case"instructions.get":return{path:"/v1/config/system-prompt",method:"GET"};case"instructions.update":return{path:"/v1/config/system-prompt",method:"PATCH",body:{content:e.content}};case"credentials.list":return{path:"/v1/credentials",method:"GET"};case"credentials.update":return{path:"/v1/credentials",method:"PATCH",body:{key:e.key,value:e.value}};case"projects.list":return{path:"/v1/desktop/projects",method:"GET"};case"projects.get":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"GET"};case"projects.create":return{path:"/v1/desktop/projects",method:"POST",body:{name:e.name,...e.description!==void 0?{description:e.description}:{},...e.status!==void 0?{status:e.status}:{},...e.tags!==void 0?{tags:e.tags}:{}}};case"projects.update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"PATCH",body:{...e.fields}};case"projects.delete":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"DELETE",body:{confirm:e.confirmed_name}};case"projects.link":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links`,method:"POST",body:{session_id:e.sessionId}};case"projects.unlink":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links/${encodeURIComponent(e.sessionId)}`,method:"DELETE"};case"projects.milestone":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones`,method:"POST",body:{name:e.name,...e.targetDate!==void 0?{target_date:e.targetDate}:{},...e.completed!==void 0?{completed:e.completed}:{}}};case"projects.milestone.remove":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones/${encodeURIComponent(e.name)}`,method:"DELETE"};case"aida.status":return{path:"/v1/desktop/aida",method:"GET"};case"aida.control":return{path:"/v1/desktop/aida",method:"POST",body:{op:e.action}}}}const hh=64,mh=64*1024*1024,Pt={notPaired:"This backend was not started with desktop controls.",serverDown:"The Local Operator server is not answering.",frameBudget:"The event stream exceeded its frame budget.",ended:"The event stream ended."},Sr={statement:"Lost the connection to this conversation — reconnect to keep reading.",action:"reconnect"},el={statement:"The Local Operator server is not running — reconnect once it is back, or restart the app if it stays down.",action:"reconnect"},tl={statement:"This app is not paired with the Local Operator server, so this conversation cannot be read yet.",action:null},nl={statement:"Could not load this conversation's history — reconnect to try again.",action:"reconnect"},sl={statement:"This conversation's updates were too large to display — reconnect to try again.",action:"reconnect"};function kr(e){return e?e===Pt.notPaired?tl:e===Pt.serverDown?el:e===Pt.frameBudget?sl:Sr:Sr}async function Pi(e){if(window.api?.desktop)try{return await rl(window.api.desktop.request(e),e)}catch(n){throw n instanceof X?n:al(n)?new at(Oi,Wc):new X(null,"Desktop controls could not reach the backend process.",n)}let t;try{t=await fetch("/__desktop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(n){throw new X(null,"Desktop controls could not reach the backend process.",n)}if(!t.ok)throw new X(t.status,"Desktop controls need a compatible backend connection.");return t.json()}function rl(e,t){const n=Ai(t);let s;return Promise.race([e,new Promise((r,i)=>{s=setTimeout(()=>{const o=Xc(t.op,n);i(new X(null,o.message,void 0,o.code))},n)})]).finally(()=>clearTimeout(s))}class X extends Error{status;cause;code;retryAfterMs;constructor(t,n,s,r,i){super(n),this.name="DesktopControlError",this.status=t,this.cause=s,this.code=r,this.retryAfterMs=i}}class at extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function In(e,t){return e instanceof X||e instanceof at?Ls(e.code)?Ds[e.code]:e.message:t}function il(e,t,n,s){return typeof s=="string"?s:n===as.noCredential?_e.noCredential:n===as.transportFailed?_e.transportFailed:Ac(qc(e).path,t)}async function ce(e){const t=await Pi(e),n=t.body;if(t.status<200||t.status>=300){const s=typeof n?.detail=="string"?n.detail:typeof n?.detail?.message=="string"?n.detail.message:null;throw new X(t.status,s??"This server did not answer the request for its desktop controls.",void 0,il(e,t.status,s,typeof n?.detail=="object"?n.detail?.code:void 0),typeof n?.detail=="object"&&typeof n.detail?.retry_after_ms=="number"&&Number.isFinite(n.detail.retry_after_ms)?n.detail.retry_after_ms:void 0)}return n?.result}function ol(e){return e instanceof X&&e.code===Ns}function gh(e){return e instanceof X?e.status===null||e.status===503:!1}function al(e){return e instanceof Error&&e.message.includes(Oi)}async function yh(e){const t=await Pi(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function vh(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await ce({op:"auth.status",id:e});if(!n.auth_url)throw new Error("This sign-in is no longer waiting for a browser.");const s=new URL(n.auth_url);if(s.username||s.password||s.protocol!=="https:"&&!(s.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(s.hostname)))throw new Error("The provider returned an invalid sign-in address.");window.open(s.href,"_blank","noopener,noreferrer")}function cl(e,t){const n=window.api?.desktop?.stream;if(n){const i=n.subscribe(e,t);return()=>i.dispose()}const s=new URLSearchParams({session:e.sessionId});e.epoch&&s.set("epoch",e.epoch),e.afterSeq!==void 0&&s.set("after_seq",String(e.afterSeq)),s.set("frontend_replace","1");const r=new EventSource(`/__desktop/stream?${s}`);return r.onmessage=i=>{t({kind:"data",data:i.data})},r.onerror=()=>{r.readyState===EventSource.CLOSED&&(t({kind:"error",detail:Pt.ended}),r.close())},()=>{r.close(),t({kind:"end"})}}async function ll(e,t){const n=window.api?.desktop?.media;if(n)return n(e,t);const s=await fetch("/__desktop/media",{method:"POST",headers:{"x-desktop-media":JSON.stringify(e),"Content-Type":"application/octet-stream"},body:t?new Blob([t]):void 0}),r=s.headers.get("content-type")??"";if(!s.ok){let i="The media request failed.";if(r.includes("application/json"))try{const o=await s.json();typeof o.detail=="string"&&(i=o.detail)}catch{}return{status:s.status,kind:"error",detail:i,code:i===as.noCredential?_e.noCredential:void 0}}return r.includes("application/json")?{status:s.status,kind:"json",body:await s.json()}:{status:s.status,kind:"bytes",mimeType:r||"application/octet-stream",data:new Uint8Array(await s.arrayBuffer())}}function dl(e){return e.kind==="error"?Ls(e.code)?new at(Ds[e.code],e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}const _h="superseded_completion_token",bh="store_busy";function wh(e,t,n){if(!e||typeof e!="object")return!1;const s=e;return s.unseen===!1&&s.conversation_id===`session/${t}`&&s.completion_token===n}function vt(e,t,n){return!t||t.conversation_id!==`session/${n}`||!Array.isArray(t.revision)||t.revision.length!==2||!t.revision.every(s=>Number.isSafeInteger(s)&&s>=0)||e?.conversation_id===t.conversation_id&&(t.revision[0]<e.revision[0]||t.revision[1]<e.revision[1])?e:t.supported===void 0&&e?.supported!==void 0?{...t,supported:e.supported}:t}function ul(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const Sh=e=>typeof e?.goal_status=="string",kh=e=>(e?.goal??"").trim().length>0;function fl(e,t,n){return n.session_id!==t||n.payload.frontend.snapshot.session_id!==t||!e?!1:e.epoch===n.epoch&&n.seq>e.seq}const Di=/\s+/,pl=/[\\/]+$/,hl=/[\\/]/,Li=`
|
|
1
|
+
import{c as As,p as gi}from"./ui-preferences-store-DjUQd2R7.js";import{r as T,j as De}from"./index-VKe88JN9.js";import{c as Tn}from"./textarea-BX6EeK34.js";var B;(function(e){e.assertEqual=r=>r;function t(r){}e.assertIs=t;function n(r){throw new Error}e.assertNever=n,e.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},e.getValidEnumValues=r=>{const i=e.objectKeys(r).filter(c=>typeof r[r[c]]!="number"),o={};for(const c of i)o[c]=r[c];return e.objectValues(o)},e.objectValues=r=>e.objectKeys(r).map(function(i){return r[i]}),e.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&i.push(o);return i},e.find=(r,i)=>{for(const o of r)if(i(o))return o},e.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&isFinite(r)&&Math.floor(r)===r;function s(r,i=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}e.joinValues=s,e.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(B||(B={}));var ts;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(ts||(ts={}));const b=B.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Me=e=>{switch(typeof e){case"undefined":return b.undefined;case"string":return b.string;case"number":return isNaN(e)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(e)?b.array:e===null?b.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?b.promise:typeof Map<"u"&&e instanceof Map?b.map:typeof Set<"u"&&e instanceof Set?b.set:typeof Date<"u"&&e instanceof Date?b.date:b.object;default:return b.unknown}},m=B.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Wo=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class ye extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(i){return i.message},s={_errors:[]},r=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)s._errors.push(n(o));else{let c=s,l=0;for(;l<o.path.length;){const d=o.path[l];l===o.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(n(o))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}};return r(this),s}static assert(t){if(!(t instanceof ye))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,B.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},s=[];for(const r of this.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):s.push(t(r));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}ye.create=e=>new ye(e);const bt=(e,t)=>{let n;switch(e.code){case m.invalid_type:e.received===b.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case m.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,B.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:n=`Unrecognized key(s) in object: ${B.joinValues(e.keys,", ")}`;break;case m.invalid_union:n="Invalid input";break;case m.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${B.joinValues(e.options)}`;break;case m.invalid_enum_value:n=`Invalid enum value. Expected ${B.joinValues(e.options)}, received '${e.received}'`;break;case m.invalid_arguments:n="Invalid function arguments";break;case m.invalid_return_type:n="Invalid function return type";break;case m.invalid_date:n="Invalid date";break;case m.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:B.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case m.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case m.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case m.custom:n="Invalid input";break;case m.invalid_intersection_types:n="Intersection results could not be merged";break;case m.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case m.not_finite:n="Number must be finite";break;default:n=t.defaultError,B.assertNever(e)}return{message:n}};let yi=bt;function Yo(e){yi=e}function pn(){return yi}const hn=e=>{const{data:t,path:n,errorMaps:s,issueData:r}=e,i=[...n,...r.path||[]],o={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let c="";const l=s.filter(d=>!!d).slice().reverse();for(const d of l)c=d(o,{data:t,defaultError:c}).message;return{...r,path:i,message:c}},Qo=[];function y(e,t){const n=pn(),s=hn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===bt?void 0:bt].filter(r=>!!r)});e.common.issues.push(s)}class ue{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const s=[];for(const r of n){if(r.status==="aborted")return A;r.status==="dirty"&&t.dirty(),s.push(r.value)}return{status:t.value,value:s}}static async mergeObjectAsync(t,n){const s=[];for(const r of n){const i=await r.key,o=await r.value;s.push({key:i,value:o})}return ue.mergeObjectSync(t,s)}static mergeObjectSync(t,n){const s={};for(const r of n){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return A;i.status==="dirty"&&t.dirty(),o.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(s[i.value]=o.value)}return{status:t.value,value:s}}}const A=Object.freeze({status:"aborted"}),yt=e=>({status:"dirty",value:e}),pe=e=>({status:"valid",value:e}),ns=e=>e.status==="aborted",ss=e=>e.status==="dirty",it=e=>e.status==="valid",Mt=e=>typeof Promise<"u"&&e instanceof Promise;function mn(e,t,n,s){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function vi(e,t,n,s,r){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}var S;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(S||(S={}));var It,Ct;class Oe{constructor(t,n,s,r){this._cachedPath=[],this.parent=t,this.data=n,this._path=s,this._key=r}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ys=(e,t)=>{if(it(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new ye(e.common.issues);return this._error=n,this._error}}};function D(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:s,description:r}=e;if(t&&(n||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:r}:{errorMap:(o,c)=>{var l,d;const{message:u}=e;return o.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??s)!==null&&l!==void 0?l:c.defaultError}:o.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??n)!==null&&d!==void 0?d:c.defaultError}},description:r}}class N{get description(){return this._def.description}_getType(t){return Me(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Me(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ue,ctx:{common:t.parent.common,data:t.data,parsedType:Me(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Mt(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const s=this.safeParse(t,n);if(s.success)return s.data;throw s.error}safeParse(t,n){var s;const r={common:{issues:[],async:(s=n?.async)!==null&&s!==void 0?s:!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Me(t)},i=this._parseSync({data:t,path:r.path,parent:r});return Ys(r,i)}"~validate"(t){var n,s;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Me(t)};if(!this["~standard"].async)try{const i=this._parseSync({data:t,path:[],parent:r});return it(i)?{value:i.value}:{issues:r.common.issues}}catch(i){!((s=(n=i?.message)===null||n===void 0?void 0:n.toLowerCase())===null||s===void 0)&&s.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(i=>it(i)?{value:i.value}:{issues:r.common.issues})}async parseAsync(t,n){const s=await this.safeParseAsync(t,n);if(s.success)return s.data;throw s.error}async safeParseAsync(t,n){const s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Me(t)},r=this._parse({data:t,path:s.path,parent:s}),i=await(Mt(r)?r:Promise.resolve(r));return Ys(s,i)}refine(t,n){const s=r=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(r):n;return this._refinement((r,i)=>{const o=t(r),c=()=>i.addIssue({code:m.custom,...s(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(c(),!1)):o?!0:(c(),!1)})}refinement(t,n){return this._refinement((s,r)=>t(s)?!0:(r.addIssue(typeof n=="function"?n(s,r):n),!1))}_refinement(t){return new ke({schema:this,typeName:C.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Ae.create(this,this._def)}nullable(){return Ve.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Se.create(this)}promise(){return St.create(this,this._def)}or(t){return Ft.create([this,t],this._def)}and(t){return Bt.create(this,t,this._def)}transform(t){return new ke({...D(this._def),schema:this,typeName:C.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Vt({...D(this._def),innerType:this,defaultValue:n,typeName:C.ZodDefault})}brand(){return new Os({typeName:C.ZodBranded,type:this,...D(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Kt({...D(this._def),innerType:this,catchValue:n,typeName:C.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Yt.create(this,t)}readonly(){return Wt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Xo=/^c[^\s-]{8,}$/i,Jo=/^[0-9a-z]+$/,qo=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ea=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ta=/^[a-z0-9_-]{21}$/i,na=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sa=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ra=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ia="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let jn;const oa=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,aa=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ca=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,la=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,da=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ua=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_i="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",fa=new RegExp(`^${_i}$`);function bi(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`),t}function pa(e){return new RegExp(`^${bi(e)}$`)}function wi(e){let t=`${_i}T${bi(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function ha(e,t){return!!((t==="v4"||!t)&&oa.test(e)||(t==="v6"||!t)&&ca.test(e))}function ma(e,t){if(!na.test(e))return!1;try{const[n]=e.split("."),s=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(s));return!(typeof r!="object"||r===null||!r.typ||!r.alg||t&&r.alg!==t)}catch{return!1}}function ga(e,t){return!!((t==="v4"||!t)&&aa.test(e)||(t==="v6"||!t)&&la.test(e))}class we extends N{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==b.string){const i=this._getOrReturnCtx(t);return y(i,{code:m.invalid_type,expected:b.string,received:i.parsedType}),A}const s=new ue;let r;for(const i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(r=this._getOrReturnCtx(t,r),y(r,{code:m.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")t.data.length>i.value&&(r=this._getOrReturnCtx(t,r),y(r,{code:m.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){const o=t.data.length>i.value,c=t.data.length<i.value;(o||c)&&(r=this._getOrReturnCtx(t,r),o?y(r,{code:m.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&y(r,{code:m.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")ra.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"email",code:m.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")jn||(jn=new RegExp(ia,"u")),jn.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"emoji",code:m.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")ea.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"uuid",code:m.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")ta.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"nanoid",code:m.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")Xo.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"cuid",code:m.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")Jo.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"cuid2",code:m.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")qo.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"ulid",code:m.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{r=this._getOrReturnCtx(t,r),y(r,{validation:"url",code:m.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"regex",code:m.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(t,r),y(r,{code:m.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(r=this._getOrReturnCtx(t,r),y(r,{code:m.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(r=this._getOrReturnCtx(t,r),y(r,{code:m.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?wi(i).test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{code:m.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?fa.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{code:m.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?pa(i).test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{code:m.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?sa.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"duration",code:m.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?ha(t.data,i.version)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"ip",code:m.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?ma(t.data,i.alg)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"jwt",code:m.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?ga(t.data,i.version)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"cidr",code:m.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?da.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"base64",code:m.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?ua.test(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{validation:"base64url",code:m.invalid_string,message:i.message}),s.dirty()):B.assertNever(i);return{status:s.value,value:t.data}}_regex(t,n,s){return this.refinement(r=>t.test(r),{validation:n,code:m.invalid_string,...S.errToObj(s)})}_addCheck(t){return new we({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...S.errToObj(t)})}url(t){return this._addCheck({kind:"url",...S.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...S.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...S.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...S.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...S.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...S.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...S.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...S.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...S.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...S.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...S.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...S.errToObj(t)})}datetime(t){var n,s;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(n=t?.offset)!==null&&n!==void 0?n:!1,local:(s=t?.local)!==null&&s!==void 0?s:!1,...S.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...S.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...S.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...S.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...S.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...S.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...S.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...S.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...S.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...S.errToObj(n)})}nonempty(t){return this.min(1,S.errToObj(t))}trim(){return new we({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new we({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new we({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}we.create=e=>{var t;return new we({checks:[],typeName:C.ZodString,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...D(e)})};function ya(e,t){const n=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,r=n>s?n:s,i=parseInt(e.toFixed(r).replace(".","")),o=parseInt(t.toFixed(r).replace(".",""));return i%o/Math.pow(10,r)}class Ge extends N{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==b.number){const i=this._getOrReturnCtx(t);return y(i,{code:m.invalid_type,expected:b.number,received:i.parsedType}),A}let s;const r=new ue;for(const i of this._def.checks)i.kind==="int"?B.isInteger(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{code:m.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(s=this._getOrReturnCtx(t,s),y(s,{code:m.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(s=this._getOrReturnCtx(t,s),y(s,{code:m.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?ya(t.data,i.value)!==0&&(s=this._getOrReturnCtx(t,s),y(s,{code:m.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(s=this._getOrReturnCtx(t,s),y(s,{code:m.not_finite,message:i.message}),r.dirty()):B.assertNever(i);return{status:r.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,S.toString(n))}gt(t,n){return this.setLimit("min",t,!1,S.toString(n))}lte(t,n){return this.setLimit("max",t,!0,S.toString(n))}lt(t,n){return this.setLimit("max",t,!1,S.toString(n))}setLimit(t,n,s,r){return new Ge({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:S.toString(r)}]})}_addCheck(t){return new Ge({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:S.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:S.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:S.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:S.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:S.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:S.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:S.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:S.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:S.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&B.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(n===null||s.value>n)&&(n=s.value):s.kind==="max"&&(t===null||s.value<t)&&(t=s.value)}return Number.isFinite(n)&&Number.isFinite(t)}}Ge.create=e=>new Ge({checks:[],typeName:C.ZodNumber,coerce:e?.coerce||!1,...D(e)});class He extends N{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==b.bigint)return this._getInvalidInput(t);let s;const r=new ue;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(s=this._getOrReturnCtx(t,s),y(s,{code:m.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(s=this._getOrReturnCtx(t,s),y(s,{code:m.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(t,s),y(s,{code:m.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):B.assertNever(i);return{status:r.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return y(n,{code:m.invalid_type,expected:b.bigint,received:n.parsedType}),A}gte(t,n){return this.setLimit("min",t,!0,S.toString(n))}gt(t,n){return this.setLimit("min",t,!1,S.toString(n))}lte(t,n){return this.setLimit("max",t,!0,S.toString(n))}lt(t,n){return this.setLimit("max",t,!1,S.toString(n))}setLimit(t,n,s,r){return new He({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:S.toString(r)}]})}_addCheck(t){return new He({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:S.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:S.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:S.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:S.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:S.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}He.create=e=>{var t;return new He({checks:[],typeName:C.ZodBigInt,coerce:(t=e?.coerce)!==null&&t!==void 0?t:!1,...D(e)})};class jt extends N{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==b.boolean){const s=this._getOrReturnCtx(t);return y(s,{code:m.invalid_type,expected:b.boolean,received:s.parsedType}),A}return pe(t.data)}}jt.create=e=>new jt({typeName:C.ZodBoolean,coerce:e?.coerce||!1,...D(e)});class ot extends N{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==b.date){const i=this._getOrReturnCtx(t);return y(i,{code:m.invalid_type,expected:b.date,received:i.parsedType}),A}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return y(i,{code:m.invalid_date}),A}const s=new ue;let r;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(r=this._getOrReturnCtx(t,r),y(r,{code:m.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(r=this._getOrReturnCtx(t,r),y(r,{code:m.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):B.assertNever(i);return{status:s.value,value:new Date(t.data.getTime())}}_addCheck(t){return new ot({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:S.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:S.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}}ot.create=e=>new ot({checks:[],coerce:e?.coerce||!1,typeName:C.ZodDate,...D(e)});class gn extends N{_parse(t){if(this._getType(t)!==b.symbol){const s=this._getOrReturnCtx(t);return y(s,{code:m.invalid_type,expected:b.symbol,received:s.parsedType}),A}return pe(t.data)}}gn.create=e=>new gn({typeName:C.ZodSymbol,...D(e)});class $t extends N{_parse(t){if(this._getType(t)!==b.undefined){const s=this._getOrReturnCtx(t);return y(s,{code:m.invalid_type,expected:b.undefined,received:s.parsedType}),A}return pe(t.data)}}$t.create=e=>new $t({typeName:C.ZodUndefined,...D(e)});class Ut extends N{_parse(t){if(this._getType(t)!==b.null){const s=this._getOrReturnCtx(t);return y(s,{code:m.invalid_type,expected:b.null,received:s.parsedType}),A}return pe(t.data)}}Ut.create=e=>new Ut({typeName:C.ZodNull,...D(e)});class wt extends N{constructor(){super(...arguments),this._any=!0}_parse(t){return pe(t.data)}}wt.create=e=>new wt({typeName:C.ZodAny,...D(e)});class st extends N{constructor(){super(...arguments),this._unknown=!0}_parse(t){return pe(t.data)}}st.create=e=>new st({typeName:C.ZodUnknown,...D(e)});class $e extends N{_parse(t){const n=this._getOrReturnCtx(t);return y(n,{code:m.invalid_type,expected:b.never,received:n.parsedType}),A}}$e.create=e=>new $e({typeName:C.ZodNever,...D(e)});class yn extends N{_parse(t){if(this._getType(t)!==b.undefined){const s=this._getOrReturnCtx(t);return y(s,{code:m.invalid_type,expected:b.void,received:s.parsedType}),A}return pe(t.data)}}yn.create=e=>new yn({typeName:C.ZodVoid,...D(e)});class Se extends N{_parse(t){const{ctx:n,status:s}=this._processInputParams(t),r=this._def;if(n.parsedType!==b.array)return y(n,{code:m.invalid_type,expected:b.array,received:n.parsedType}),A;if(r.exactLength!==null){const o=n.data.length>r.exactLength.value,c=n.data.length<r.exactLength.value;(o||c)&&(y(n,{code:o?m.too_big:m.too_small,minimum:c?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(r.minLength!==null&&n.data.length<r.minLength.value&&(y(n,{code:m.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&n.data.length>r.maxLength.value&&(y(n,{code:m.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),n.common.async)return Promise.all([...n.data].map((o,c)=>r.type._parseAsync(new Oe(n,o,n.path,c)))).then(o=>ue.mergeArray(s,o));const i=[...n.data].map((o,c)=>r.type._parseSync(new Oe(n,o,n.path,c)));return ue.mergeArray(s,i)}get element(){return this._def.type}min(t,n){return new Se({...this._def,minLength:{value:t,message:S.toString(n)}})}max(t,n){return new Se({...this._def,maxLength:{value:t,message:S.toString(n)}})}length(t,n){return new Se({...this._def,exactLength:{value:t,message:S.toString(n)}})}nonempty(t){return this.min(1,t)}}Se.create=(e,t)=>new Se({type:e,minLength:null,maxLength:null,exactLength:null,typeName:C.ZodArray,...D(t)});function gt(e){if(e instanceof Q){const t={};for(const n in e.shape){const s=e.shape[n];t[n]=Ae.create(gt(s))}return new Q({...e._def,shape:()=>t})}else return e instanceof Se?new Se({...e._def,type:gt(e.element)}):e instanceof Ae?Ae.create(gt(e.unwrap())):e instanceof Ve?Ve.create(gt(e.unwrap())):e instanceof Pe?Pe.create(e.items.map(t=>gt(t))):e}class Q extends N{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=B.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==b.object){const d=this._getOrReturnCtx(t);return y(d,{code:m.invalid_type,expected:b.object,received:d.parsedType}),A}const{status:s,ctx:r}=this._processInputParams(t),{shape:i,keys:o}=this._getCached(),c=[];if(!(this._def.catchall instanceof $e&&this._def.unknownKeys==="strip"))for(const d in r.data)o.includes(d)||c.push(d);const l=[];for(const d of o){const u=i[d],f=r.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new Oe(r,f,r.path,d)),alwaysSet:d in r.data})}if(this._def.catchall instanceof $e){const d=this._def.unknownKeys;if(d==="passthrough")for(const u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:r.data[u]}});else if(d==="strict")c.length>0&&(y(r,{code:m.unrecognized_keys,keys:c}),s.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const u of c){const f=r.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new Oe(r,f,r.path,u)),alwaysSet:u in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const d=[];for(const u of l){const f=await u.key,p=await u.value;d.push({key:f,value:p,alwaysSet:u.alwaysSet})}return d}).then(d=>ue.mergeObjectSync(s,d)):ue.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(t){return S.errToObj,new Q({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,s)=>{var r,i,o,c;const l=(o=(i=(r=this._def).errorMap)===null||i===void 0?void 0:i.call(r,n,s).message)!==null&&o!==void 0?o:s.defaultError;return n.code==="unrecognized_keys"?{message:(c=S.errToObj(t).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new Q({...this._def,unknownKeys:"strip"})}passthrough(){return new Q({...this._def,unknownKeys:"passthrough"})}extend(t){return new Q({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Q({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:C.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Q({...this._def,catchall:t})}pick(t){const n={};return B.objectKeys(t).forEach(s=>{t[s]&&this.shape[s]&&(n[s]=this.shape[s])}),new Q({...this._def,shape:()=>n})}omit(t){const n={};return B.objectKeys(this.shape).forEach(s=>{t[s]||(n[s]=this.shape[s])}),new Q({...this._def,shape:()=>n})}deepPartial(){return gt(this)}partial(t){const n={};return B.objectKeys(this.shape).forEach(s=>{const r=this.shape[s];t&&!t[s]?n[s]=r:n[s]=r.optional()}),new Q({...this._def,shape:()=>n})}required(t){const n={};return B.objectKeys(this.shape).forEach(s=>{if(t&&!t[s])n[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof Ae;)i=i._def.innerType;n[s]=i}}),new Q({...this._def,shape:()=>n})}keyof(){return Si(B.objectKeys(this.shape))}}Q.create=(e,t)=>new Q({shape:()=>e,unknownKeys:"strip",catchall:$e.create(),typeName:C.ZodObject,...D(t)});Q.strictCreate=(e,t)=>new Q({shape:()=>e,unknownKeys:"strict",catchall:$e.create(),typeName:C.ZodObject,...D(t)});Q.lazycreate=(e,t)=>new Q({shape:e,unknownKeys:"strip",catchall:$e.create(),typeName:C.ZodObject,...D(t)});class Ft extends N{_parse(t){const{ctx:n}=this._processInputParams(t),s=this._def.options;function r(i){for(const c of i)if(c.result.status==="valid")return c.result;for(const c of i)if(c.result.status==="dirty")return n.common.issues.push(...c.ctx.common.issues),c.result;const o=i.map(c=>new ye(c.ctx.common.issues));return y(n,{code:m.invalid_union,unionErrors:o}),A}if(n.common.async)return Promise.all(s.map(async i=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const l of s){const d={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const c=o.map(l=>new ye(l));return y(n,{code:m.invalid_union,unionErrors:c}),A}}get options(){return this._def.options}}Ft.create=(e,t)=>new Ft({options:e,typeName:C.ZodUnion,...D(t)});const Le=e=>e instanceof Gt?Le(e.schema):e instanceof ke?Le(e.innerType()):e instanceof Ht?[e.value]:e instanceof ze?e.options:e instanceof zt?B.objectValues(e.enum):e instanceof Vt?Le(e._def.innerType):e instanceof $t?[void 0]:e instanceof Ut?[null]:e instanceof Ae?[void 0,...Le(e.unwrap())]:e instanceof Ve?[null,...Le(e.unwrap())]:e instanceof Os||e instanceof Wt?Le(e.unwrap()):e instanceof Kt?Le(e._def.innerType):[];class En extends N{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.object)return y(n,{code:m.invalid_type,expected:b.object,received:n.parsedType}),A;const s=this.discriminator,r=n.data[s],i=this.optionsMap.get(r);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(y(n,{code:m.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),A)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,s){const r=new Map;for(const i of n){const o=Le(i.shape[t]);if(!o.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const c of o){if(r.has(c))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(c)}`);r.set(c,i)}}return new En({typeName:C.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:r,...D(s)})}}function rs(e,t){const n=Me(e),s=Me(t);if(e===t)return{valid:!0,data:e};if(n===b.object&&s===b.object){const r=B.objectKeys(t),i=B.objectKeys(e).filter(c=>r.indexOf(c)!==-1),o={...e,...t};for(const c of i){const l=rs(e[c],t[c]);if(!l.valid)return{valid:!1};o[c]=l.data}return{valid:!0,data:o}}else if(n===b.array&&s===b.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let i=0;i<e.length;i++){const o=e[i],c=t[i],l=rs(o,c);if(!l.valid)return{valid:!1};r.push(l.data)}return{valid:!0,data:r}}else return n===b.date&&s===b.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Bt extends N{_parse(t){const{status:n,ctx:s}=this._processInputParams(t),r=(i,o)=>{if(ns(i)||ns(o))return A;const c=rs(i.value,o.value);return c.valid?((ss(i)||ss(o))&&n.dirty(),{status:n.value,value:c.data}):(y(s,{code:m.invalid_intersection_types}),A)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,o])=>r(i,o)):r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Bt.create=(e,t,n)=>new Bt({left:e,right:t,typeName:C.ZodIntersection,...D(n)});class Pe extends N{_parse(t){const{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==b.array)return y(s,{code:m.invalid_type,expected:b.array,received:s.parsedType}),A;if(s.data.length<this._def.items.length)return y(s,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),A;!this._def.rest&&s.data.length>this._def.items.length&&(y(s,{code:m.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...s.data].map((o,c)=>{const l=this._def.items[c]||this._def.rest;return l?l._parse(new Oe(s,o,s.path,c)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>ue.mergeArray(n,o)):ue.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new Pe({...this._def,rest:t})}}Pe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Pe({items:e,typeName:C.ZodTuple,rest:null,...D(t)})};class Zt extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==b.object)return y(s,{code:m.invalid_type,expected:b.object,received:s.parsedType}),A;const r=[],i=this._def.keyType,o=this._def.valueType;for(const c in s.data)r.push({key:i._parse(new Oe(s,c,s.path,c)),value:o._parse(new Oe(s,s.data[c],s.path,c)),alwaysSet:c in s.data});return s.common.async?ue.mergeObjectAsync(n,r):ue.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(t,n,s){return n instanceof N?new Zt({keyType:t,valueType:n,typeName:C.ZodRecord,...D(s)}):new Zt({keyType:we.create(),valueType:t,typeName:C.ZodRecord,...D(n)})}}class vn extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==b.map)return y(s,{code:m.invalid_type,expected:b.map,received:s.parsedType}),A;const r=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([c,l],d)=>({key:r._parse(new Oe(s,c,s.path,[d,"key"])),value:i._parse(new Oe(s,l,s.path,[d,"value"]))}));if(s.common.async){const c=new Map;return Promise.resolve().then(async()=>{for(const l of o){const d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return A;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}})}else{const c=new Map;for(const l of o){const d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return A;(d.status==="dirty"||u.status==="dirty")&&n.dirty(),c.set(d.value,u.value)}return{status:n.value,value:c}}}}vn.create=(e,t,n)=>new vn({valueType:t,keyType:e,typeName:C.ZodMap,...D(n)});class at extends N{_parse(t){const{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==b.set)return y(s,{code:m.invalid_type,expected:b.set,received:s.parsedType}),A;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(y(s,{code:m.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()),r.maxSize!==null&&s.data.size>r.maxSize.value&&(y(s,{code:m.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty());const i=this._def.valueType;function o(l){const d=new Set;for(const u of l){if(u.status==="aborted")return A;u.status==="dirty"&&n.dirty(),d.add(u.value)}return{status:n.value,value:d}}const c=[...s.data.values()].map((l,d)=>i._parse(new Oe(s,l,s.path,d)));return s.common.async?Promise.all(c).then(l=>o(l)):o(c)}min(t,n){return new at({...this._def,minSize:{value:t,message:S.toString(n)}})}max(t,n){return new at({...this._def,maxSize:{value:t,message:S.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}at.create=(e,t)=>new at({valueType:e,minSize:null,maxSize:null,typeName:C.ZodSet,...D(t)});class _t extends N{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.function)return y(n,{code:m.invalid_type,expected:b.function,received:n.parsedType}),A;function s(c,l){return hn({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,pn(),bt].filter(d=>!!d),issueData:{code:m.invalid_arguments,argumentsError:l}})}function r(c,l){return hn({data:c,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,pn(),bt].filter(d=>!!d),issueData:{code:m.invalid_return_type,returnTypeError:l}})}const i={errorMap:n.common.contextualErrorMap},o=n.data;if(this._def.returns instanceof St){const c=this;return pe(async function(...l){const d=new ye([]),u=await c._def.args.parseAsync(l,i).catch(w=>{throw d.addIssue(s(l,w)),d}),f=await Reflect.apply(o,this,u);return await c._def.returns._def.type.parseAsync(f,i).catch(w=>{throw d.addIssue(r(f,w)),d})})}else{const c=this;return pe(function(...l){const d=c._def.args.safeParse(l,i);if(!d.success)throw new ye([s(l,d.error)]);const u=Reflect.apply(o,this,d.data),f=c._def.returns.safeParse(u,i);if(!f.success)throw new ye([r(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new _t({...this._def,args:Pe.create(t).rest(st.create())})}returns(t){return new _t({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,s){return new _t({args:t||Pe.create([]).rest(st.create()),returns:n||st.create(),typeName:C.ZodFunction,...D(s)})}}class Gt extends N{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Gt.create=(e,t)=>new Gt({getter:e,typeName:C.ZodLazy,...D(t)});class Ht extends N{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return y(n,{received:n.data,code:m.invalid_literal,expected:this._def.value}),A}return{status:"valid",value:t.data}}get value(){return this._def.value}}Ht.create=(e,t)=>new Ht({value:e,typeName:C.ZodLiteral,...D(t)});function Si(e,t){return new ze({values:e,typeName:C.ZodEnum,...D(t)})}class ze extends N{constructor(){super(...arguments),It.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),s=this._def.values;return y(n,{expected:B.joinValues(s),received:n.parsedType,code:m.invalid_type}),A}if(mn(this,It)||vi(this,It,new Set(this._def.values)),!mn(this,It).has(t.data)){const n=this._getOrReturnCtx(t),s=this._def.values;return y(n,{received:n.data,code:m.invalid_enum_value,options:s}),A}return pe(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return ze.create(t,{...this._def,...n})}exclude(t,n=this._def){return ze.create(this.options.filter(s=>!t.includes(s)),{...this._def,...n})}}It=new WeakMap;ze.create=Si;class zt extends N{constructor(){super(...arguments),Ct.set(this,void 0)}_parse(t){const n=B.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(t);if(s.parsedType!==b.string&&s.parsedType!==b.number){const r=B.objectValues(n);return y(s,{expected:B.joinValues(r),received:s.parsedType,code:m.invalid_type}),A}if(mn(this,Ct)||vi(this,Ct,new Set(B.getValidEnumValues(this._def.values))),!mn(this,Ct).has(t.data)){const r=B.objectValues(n);return y(s,{received:s.data,code:m.invalid_enum_value,options:r}),A}return pe(t.data)}get enum(){return this._def.values}}Ct=new WeakMap;zt.create=(e,t)=>new zt({values:e,typeName:C.ZodNativeEnum,...D(t)});class St extends N{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==b.promise&&n.common.async===!1)return y(n,{code:m.invalid_type,expected:b.promise,received:n.parsedType}),A;const s=n.parsedType===b.promise?n.data:Promise.resolve(n.data);return pe(s.then(r=>this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})))}}St.create=(e,t)=>new St({type:e,typeName:C.ZodPromise,...D(t)});class ke extends N{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===C.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:s}=this._processInputParams(t),r=this._def.effect||null,i={addIssue:o=>{y(s,o),o.fatal?n.abort():n.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async c=>{if(n.value==="aborted")return A;const l=await this._def.schema._parseAsync({data:c,path:s.path,parent:s});return l.status==="aborted"?A:l.status==="dirty"||n.value==="dirty"?yt(l.value):l});{if(n.value==="aborted")return A;const c=this._def.schema._parseSync({data:o,path:s.path,parent:s});return c.status==="aborted"?A:c.status==="dirty"||n.value==="dirty"?yt(c.value):c}}if(r.type==="refinement"){const o=c=>{const l=r.refinement(c,i);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(s.common.async===!1){const c=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return c.status==="aborted"?A:(c.status==="dirty"&&n.dirty(),o(c.value),{status:n.value,value:c.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(c=>c.status==="aborted"?A:(c.status==="dirty"&&n.dirty(),o(c.value).then(()=>({status:n.value,value:c.value}))))}if(r.type==="transform")if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!it(o))return o;const c=r.transform(o.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:c}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>it(o)?Promise.resolve(r.transform(o.value,i)).then(c=>({status:n.value,value:c})):o);B.assertNever(r)}}ke.create=(e,t,n)=>new ke({schema:e,typeName:C.ZodEffects,effect:t,...D(n)});ke.createWithPreprocess=(e,t,n)=>new ke({schema:t,effect:{type:"preprocess",transform:e},typeName:C.ZodEffects,...D(n)});class Ae extends N{_parse(t){return this._getType(t)===b.undefined?pe(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:C.ZodOptional,...D(t)});class Ve extends N{_parse(t){return this._getType(t)===b.null?pe(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Ve.create=(e,t)=>new Ve({innerType:e,typeName:C.ZodNullable,...D(t)});class Vt extends N{_parse(t){const{ctx:n}=this._processInputParams(t);let s=n.data;return n.parsedType===b.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Vt.create=(e,t)=>new Vt({innerType:e,typeName:C.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...D(t)});class Kt extends N{_parse(t){const{ctx:n}=this._processInputParams(t),s={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Mt(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ye(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new ye(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Kt.create=(e,t)=>new Kt({innerType:e,typeName:C.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...D(t)});class _n extends N{_parse(t){if(this._getType(t)!==b.nan){const s=this._getOrReturnCtx(t);return y(s,{code:m.invalid_type,expected:b.nan,received:s.parsedType}),A}return{status:"valid",value:t.data}}}_n.create=e=>new _n({typeName:C.ZodNaN,...D(e)});const va=Symbol("zod_brand");class Os extends N{_parse(t){const{ctx:n}=this._processInputParams(t),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class Yt extends N{_parse(t){const{status:n,ctx:s}=this._processInputParams(t);if(s.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?A:i.status==="dirty"?(n.dirty(),yt(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{const r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?A:r.status==="dirty"?(n.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(t,n){return new Yt({in:t,out:n,typeName:C.ZodPipeline})}}class Wt extends N{_parse(t){const n=this._def.innerType._parse(t),s=r=>(it(r)&&(r.value=Object.freeze(r.value)),r);return Mt(n)?n.then(r=>s(r)):s(n)}unwrap(){return this._def.innerType}}Wt.create=(e,t)=>new Wt({innerType:e,typeName:C.ZodReadonly,...D(t)});function Qs(e,t){const n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function ki(e,t={},n){return e?wt.create().superRefine((s,r)=>{var i,o;const c=e(s);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){const f=Qs(t,s),p=(u=(d=f.fatal)!==null&&d!==void 0?d:n)!==null&&u!==void 0?u:!0;r.addIssue({code:"custom",...f,fatal:p})}});if(!c){const l=Qs(t,s),d=(o=(i=l.fatal)!==null&&i!==void 0?i:n)!==null&&o!==void 0?o:!0;r.addIssue({code:"custom",...l,fatal:d})}}):wt.create()}const _a={object:Q.lazycreate};var C;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(C||(C={}));const ba=(e,t={message:`Input not instance of ${e.name}`})=>ki(n=>n instanceof e,t),Ti=we.create,Ei=Ge.create,wa=_n.create,Sa=He.create,xi=jt.create,ka=ot.create,Ta=gn.create,Ea=$t.create,xa=Ut.create,Ia=wt.create,Ca=st.create,Ra=$e.create,Aa=yn.create,Oa=Se.create,Pa=Q.create,Da=Q.strictCreate,La=Ft.create,Na=En.create,Ma=Bt.create,ja=Pe.create,$a=Zt.create,Ua=vn.create,Fa=at.create,Ba=_t.create,Za=Gt.create,Ga=Ht.create,Ha=ze.create,za=zt.create,Va=St.create,Xs=ke.create,Ka=Ae.create,Wa=Ve.create,Ya=ke.createWithPreprocess,Qa=Yt.create,Xa=()=>Ti().optional(),Ja=()=>Ei().optional(),qa=()=>xi().optional(),ec={string:e=>we.create({...e,coerce:!0}),number:e=>Ge.create({...e,coerce:!0}),boolean:e=>jt.create({...e,coerce:!0}),bigint:e=>He.create({...e,coerce:!0}),date:e=>ot.create({...e,coerce:!0})},tc=A;var a=Object.freeze({__proto__:null,defaultErrorMap:bt,setErrorMap:Yo,getErrorMap:pn,makeIssue:hn,EMPTY_PATH:Qo,addIssueToContext:y,ParseStatus:ue,INVALID:A,DIRTY:yt,OK:pe,isAborted:ns,isDirty:ss,isValid:it,isAsync:Mt,get util(){return B},get objectUtil(){return ts},ZodParsedType:b,getParsedType:Me,ZodType:N,datetimeRegex:wi,ZodString:we,ZodNumber:Ge,ZodBigInt:He,ZodBoolean:jt,ZodDate:ot,ZodSymbol:gn,ZodUndefined:$t,ZodNull:Ut,ZodAny:wt,ZodUnknown:st,ZodNever:$e,ZodVoid:yn,ZodArray:Se,ZodObject:Q,ZodUnion:Ft,ZodDiscriminatedUnion:En,ZodIntersection:Bt,ZodTuple:Pe,ZodRecord:Zt,ZodMap:vn,ZodSet:at,ZodFunction:_t,ZodLazy:Gt,ZodLiteral:Ht,ZodEnum:ze,ZodNativeEnum:zt,ZodPromise:St,ZodEffects:ke,ZodTransformer:ke,ZodOptional:Ae,ZodNullable:Ve,ZodDefault:Vt,ZodCatch:Kt,ZodNaN:_n,BRAND:va,ZodBranded:Os,ZodPipeline:Yt,ZodReadonly:Wt,custom:ki,Schema:N,ZodSchema:N,late:_a,get ZodFirstPartyTypeKind(){return C},coerce:ec,any:Ia,array:Oa,bigint:Sa,boolean:xi,date:ka,discriminatedUnion:Na,effect:Xs,enum:Ha,function:Ba,instanceof:ba,intersection:Ma,lazy:Za,literal:Ga,map:Ua,nan:wa,nativeEnum:za,never:Ra,null:xa,nullable:Wa,number:Ei,object:Pa,oboolean:qa,onumber:Ja,optional:Ka,ostring:Xa,pipeline:Qa,preprocess:Ya,promise:Va,record:$a,set:Fa,strictObject:Da,string:Ti,symbol:Ta,transformer:Xs,tuple:ja,undefined:Ea,union:La,unknown:Ca,void:Aa,NEVER:tc,ZodIssueCode:m,quotelessJson:Wo,ZodError:ye});const O=a.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/),qt=a.string().min(1).max(256).regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/),en=a.string().min(1).max(32768),R=a.string().regex(/^[a-f0-9]{12}$/),$n=a.string().regex(/^[A-Za-z0-9_.:-]{1,100}$/),tn=a.string().regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/),Js=a.string().regex(/^[a-f0-9]{32}$/),Un=a.string().min(1).max(4096).regex(/^(\/|[A-Za-z]:[\\/])/),qs=/^[a-f0-9]{32}$/,Y=a.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/),Et=a.string().regex(/^[A-Za-z0-9_-]{1,128}$/),er=a.object({data_b64:a.string().min(1).max(1e6),mime_type:a.enum(["image/png","image/jpeg","image/gif","image/webp"])}).strict(),tr=2e5,nc=256,sc=100,nr=16,rc=256,ic=100,oc=200,ac=1e6,je=a.string().min(1).max(128).refine(e=>e!=="."&&e!==".."&&!e.includes("/")&&!e.includes("\\")&&[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127)),nn=a.object({kind:a.enum(["agent","team"]),name:je}).strict(),Fn=a.object({provider:a.string().min(1).max(128),model_id:a.string().min(1).max(512),reasoning_effort:a.string().min(1).max(64).nullable()}).strict(),sr=a.object({kind:a.enum(["role","specialist"]).optional(),description:a.string().max(8e3).optional(),instructions:a.string().max(8e3).optional(),tools:a.array(a.string().min(1).max(128)).max(256).optional(),effort:a.string().max(64).optional(),delegate:a.boolean().optional()}).strict(),rr=a.object({name:a.string().min(1).max(64).optional(),description:a.string().max(8e3).optional(),manager:je.optional(),members:a.array(a.object({role:je,count:a.number().int().min(1).max(16),kind:a.enum(["agent","team"])}).strict()).max(128).optional(),instructions:a.string().max(8e3).optional(),project:a.string().max(8e3).optional()}).strict(),cc=a.record(a.array(a.string().max(1024)).max(100)),ir=a.enum(["minutes","hours","days"]);function lc(e){return!/^\.+$/.test(e)}const uh=e=>cn.safeParse(e).success,cn=a.string().min(1).max(128).refine(e=>[...e].every(t=>t.charCodeAt(0)>=32&&t.charCodeAt(0)!==127&&t!=="/"&&t!=="\\")).refine(lc),or=a.enum(["str","int","float","bool","list","dict"]),ar=a.string().max(16384),dc=2e3,cr=a.string().min(1).max(dc),lr=a.string().min(1).max(64),dr=a.object({is_active:a.boolean().nullish(),one_time:a.boolean().nullish(),start_time_utc:a.string().max(64).nullish(),end_time_utc:a.string().max(64).nullish()}).strict(),uc=a.object({conversation_length:a.number().int().optional(),detail_length:a.number().int().optional(),max_learnings_history:a.number().int().optional(),hosting:a.string().max(256).optional(),model_name:a.string().max(1024).optional(),auto_save_conversation:a.boolean().optional()}).strict(),is=128,ur=2e3,fr=8e3,pr=64,hr=64,xn=e=>[...e].length,os=e=>e>=9&&e<=13||e>=28&&e<=32||e===133||e===160||e===5760||e>=8192&&e<=8202||e===8232||e===8233||e===8239||e===8287||e===12288,fc=e=>e===9||e===10||e===11||e===12||e===13||e===133,pc=e=>e<=31||e>=127&&e<=159,hc=e=>new RegExp("\\p{Cf}","u").test(String.fromCodePoint(e)),mc=e=>e>=8234&&e<=8238||e>=8294&&e<=8297,sn=(e,t)=>{for(const n of e)if(t(n.codePointAt(0)??0))return!0;return!1},Ii=e=>{const t=[...e];let n=0,s=t.length;for(;n<s&&os(t[n].codePointAt(0)??0);)n++;for(;s>n&&os(t[s-1].codePointAt(0)??0);)s--;return t.slice(n,s).join("")},gc=e=>{let t="",n=!1;for(const s of e){if(os(s.codePointAt(0)??0)){n=t.length>0;continue}n&&(t+=" ",n=!1),t+=s}return t};function yc(e){const t=Ii(e);if(!t)return"must not be empty";if(xn(t)>is)return`must be at most ${is} characters`;if(/[/\\:]/.test(t))return'must not contain "/", "\\" or ":"';if(sn(t,mc))return"must not contain Unicode bidirectional override characters";if(sn(t,fc))return"must not contain whitespace";if(sn(t,pc))return"must not contain control characters";if(sn(t,hc))return"must not contain invisible Unicode formatting characters";const n=[...t];return"-.".includes(n[0])||"-.".includes(n[n.length-1])?'must not begin or end with "-" or "."':null}function fh(e){return gc(Ii(e).normalize("NFKC").toLowerCase())}function vc(e){return e.trim()?xn(e)>ur?`must be at most ${ur} characters`:null:"must not be empty"}function _c(e){return e.trim()?xn(e)>fr?`must be at most ${fr} characters`:null:"must not be empty"}function bc(e){if(e.length>hr)return`must hold at most ${hr} items`;for(const t of e)if(!t.trim()||xn(t)>pr)return`must hold items of 1 to ${pr} characters`;return null}const wc=e=>yc(e)===null,Sc=a.string().refine(wc,{message:"That is not a name the hub can publish."}),kc=a.string().refine(e=>_c(e)===null,{message:"That instruction body cannot be published."}),Tc=a.string().refine(e=>vc(e)===null,{message:"That description cannot be published."}),Ec=a.array(a.string()).refine(e=>bc(e)===null,{message:"That tool list cannot be published."}),mr=a.object({name:Sc,description:Tc,instructions:kc,kind:a.enum(["role","specialist"]),when_to_use:a.string(),tools:Ec,effort:a.string(),delegate:a.boolean(),version:a.string(),categories:a.array(a.string()),tags:a.array(a.string())}).partial().strict(),xc=a.enum(["team","agent"]),Ic=a.string().min(1).max(64),Cc=a.string().min(1).max(256),Ci=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Bn=a.string().regex(Ci,{message:"Letters, digits, dot, underscore and dash; no spaces."}),Rc=["planning","active","qa","validation","done","paused","archived"],gr=a.enum(Rc),rn=a.string().regex(/^$|^\d{4}-\d{2}-\d{2}$/,"Dates are YYYY-MM-DD, or empty to clear."),yr=a.array(a.string().min(1).max(24)).max(8),qe=a.string().min(1).max(64),Ac=1e3,vr=240,_r=80,Oc=/^[a-z0-9][a-z0-9_-]{0,23}$/;function ph(e){return e?Ci.test(e)?null:"Names start with a letter or digit and may use letters, digits, dot, underscore or dash.":"Give the project a name."}function hh(e){return Oc.test(e)?null:"Tags are 1-24 characters of lowercase letters, digits, underscore or dash."}const Pc=a.discriminatedUnion("op",[a.object({op:a.literal("capabilities")}).strict(),a.object({op:a.literal("profiles.list")}).strict(),a.object({op:a.literal("profiles.get"),name:je}).strict(),a.object({op:a.literal("profiles.install"),name:je,requestId:Y}).strict(),a.object({op:a.literal("profiles.create"),name:je,requestId:Y,fields:sr.extend({description:a.string().max(8e3),instructions:a.string().min(1).max(8e3)})}).strict(),a.object({op:a.literal("profiles.update"),name:je,requestId:Y,fields:sr}).strict(),a.object({op:a.literal("teams.list")}).strict(),a.object({op:a.literal("teams.get"),name:je}).strict(),a.object({op:a.literal("teams.create"),requestId:Y,fields:rr.extend({name:a.string().min(1).max(64)})}).strict(),a.object({op:a.literal("teams.update"),name:je,requestId:Y,fields:rr}).strict(),a.object({op:a.literal("sessions.list"),limit:a.number().int().min(1).max(500).optional(),include_archived:a.boolean().optional(),include_peers:a.boolean().optional(),scope_kind:xc.optional(),scope_name:Ic.optional(),cursor:Cc.optional(),with_counts:a.boolean().optional()}).strict(),a.object({op:a.literal("sessions.search"),q:a.string().min(1).max(nc),limit:a.number().int().min(1).max(500).optional(),include_archived:a.boolean().optional()}).strict(),a.object({op:a.literal("sessions.archive"),sessionId:R,archived:a.boolean()}).strict(),a.object({op:a.literal("sessions.delete"),sessionId:R,confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("sessions.create"),requestId:Y,cwd:a.string().min(1).max(4096),target:nn.optional(),model:Fn.optional(),draftId:R.optional()}).strict(),a.object({op:a.literal("sessions.preview"),requestId:Y,cwd:a.string().min(1).max(4096),target:nn.optional(),model:Fn.optional()}).strict(),a.object({op:a.literal("sessions.draft"),requestId:Y,cwd:a.string().min(1).max(4096),target:nn.optional(),model:Fn.optional()}).strict(),a.object({op:a.literal("sessions.get"),sessionId:R}).strict(),a.object({op:a.literal("sessions.history"),sessionId:R,beforeId:O.optional(),limit:a.number().int().min(1).max(500).optional()}).strict(),a.object({op:a.literal("sessions.checkpoints"),sessionId:R}).strict(),a.object({op:a.literal("sessions.checkpoints.warm"),sessionId:R,ids:a.array(O).max(nr).optional(),limit:a.number().int().min(1).max(nr).optional()}).strict(),a.object({op:a.literal("sessions.find"),sessionId:R,q:a.string().min(1).max(rc),limit:a.number().int().min(1).max(oc).optional()}).strict(),a.object({op:a.literal("subagents.transcript"),sessionId:R,childId:R,beforeId:O.optional(),limit:a.number().int().min(1).max(500).optional()}).strict(),a.object({op:a.literal("sessions.message"),sessionId:R,requestId:Y,text:a.string().max(tr),images:a.array(er).max(8).optional(),mode:a.enum(["prompt","steer"]).optional(),inputMode:a.enum(["typed","dictated","mixed"]).optional(),inputPath:a.string().max(1024).optional()}).strict(),a.object({op:a.literal("sessions.command"),sessionId:R,requestId:Y,command:a.string().regex(/^\/?[A-Za-z]+$/).max(64),args:a.string().max(tr).optional(),images:a.array(er).max(8).optional()}).strict(),a.object({op:a.literal("sessions.move"),sessionId:R,requestId:Y,cwd:a.string().min(1).max(4096)}).strict(),a.object({op:a.literal("sessions.answer"),sessionId:R,epoch:O,requestId:O,value:a.string().max(32768).optional(),approved:a.boolean().optional(),questionIndex:a.number().int().min(0).optional()}).strict(),a.object({op:a.literal("sessions.seen"),sessionId:R,completionToken:a.string().uuid()}).strict(),a.object({op:a.literal("attention.seen"),items:a.array(a.object({sessionId:R,completionToken:a.string().uuid()}).strict()).min(1).max(500)}).strict(),a.object({op:a.literal("sessions.notified"),sessionId:R,completionToken:a.string().uuid()}).strict(),a.object({op:a.literal("sessions.pin"),sessionId:R,pinned:a.boolean()}).strict(),a.object({op:a.literal("sessions.watch"),sessionId:R,subscriptionId:a.string().regex(qs),visible:a.boolean(),canNotify:a.boolean()}).strict(),a.object({op:a.literal("sessions.warm"),sessionId:R}).strict(),a.object({op:a.literal("sessions.interrupt"),sessionId:R,requestId:Y}).strict(),a.object({op:a.literal("sessions.variables.list"),sessionId:R}).strict(),a.object({op:a.literal("sessions.variables.create"),sessionId:R,key:cn,value:ar,type:or}).strict(),a.object({op:a.literal("sessions.variables.update"),sessionId:R,key:cn,value:ar,type:or}).strict(),a.object({op:a.literal("sessions.variables.delete"),sessionId:R,key:cn}).strict(),a.object({op:a.literal("sessions.presence"),subscriptionId:a.string().regex(/^[a-f0-9]{1,64}$/),canNotify:a.boolean(),canNotifyKinds:a.array(a.enum(["complete","error"])).max(4),sessionId:a.string().regex(/^([a-f0-9]{12})?$/),window:a.object({exists:a.boolean(),focused:a.boolean(),visible:a.boolean(),minimized:a.boolean()}).strict()}).strict(),a.object({op:a.literal("legacy.models"),provider:a.string().max(128).optional(),sort:a.enum(["id","name","provider","recommended"]).optional(),direction:a.enum(["ascending","descending"]).optional()}).strict(),a.object({op:a.literal("legacy.models.providers")}).strict(),a.object({op:a.literal("auth.probe"),provider:O}).strict(),a.object({op:a.literal("legacy.agent.upload"),agentId:O}).strict(),a.object({op:a.literal("agent.publish"),agentId:O,document:mr.optional(),visibility:a.literal("org").optional(),tenantId:O.optional()}).strict(),a.object({op:a.literal("agent.republish"),agentId:O,hubAgentId:O,document:mr.optional(),visibility:a.literal("org").optional(),tenantId:O.optional()}).strict(),a.object({op:a.literal("team.pull"),teamId:O,tenantId:O.optional()}).strict(),a.object({op:a.literal("agent.nameAvailability"),name:a.string().min(1).max(is)}).strict(),a.object({op:a.literal("legacy.agents.list"),page:a.number().int().min(1).optional(),perPage:a.number().int().min(1).max(500).optional(),name:a.string().max(256).optional(),sort:a.string().max(64).optional(),direction:a.enum(["asc","desc"]).optional()}).strict(),a.object({op:a.literal("legacy.agent.get"),agentId:O}).strict(),a.object({op:a.literal("legacy.agent.history"),agentId:O,page:a.number().int().min(1).optional(),perPage:a.number().int().min(1).max(500).optional()}).strict(),a.object({op:a.literal("legacy.jobs.list"),agentId:O.optional(),status:a.string().max(64).optional()}).strict(),a.object({op:a.literal("legacy.job.get"),jobId:O}).strict(),a.object({op:a.literal("legacy.schedules.list"),page:a.number().int().min(1).optional(),perPage:a.number().int().min(1).max(100).optional()}).strict(),a.object({op:a.literal("legacy.agent.schedules.list"),agentId:O,page:a.number().int().min(1).optional(),perPage:a.number().int().min(1).max(100).optional()}).strict(),a.object({op:a.literal("legacy.agent.schedule.create"),agentId:O,schedule:dr.extend({prompt:a.string().max(64e3),interval:a.number().int().min(1),unit:ir})}).strict(),a.object({op:a.literal("legacy.schedule.get"),scheduleId:O}).strict(),a.object({op:a.literal("legacy.schedule.edit"),scheduleId:O,schedule:dr.extend({prompt:a.string().max(64e3).nullish(),interval:a.number().int().min(1).nullish(),unit:ir.nullish()})}).strict(),a.object({op:a.literal("legacy.schedule.remove"),scheduleId:O}).strict(),a.object({op:a.literal("legacy.agent.create"),agent:a.record(a.unknown())}).strict(),a.object({op:a.literal("legacy.agent.update"),agentId:O,update:a.record(a.unknown())}).strict(),a.object({op:a.literal("legacy.agent.delete"),agentId:O}).strict(),a.object({op:a.literal("legacy.agent.conversation.clear"),agentId:O}).strict(),a.object({op:a.literal("legacy.agent.systemPrompt.get"),agentId:O}).strict(),a.object({op:a.literal("legacy.agent.systemPrompt.update"),agentId:O,systemPrompt:a.string().max(ac)}).strict(),a.object({op:a.literal("legacy.agent.download"),agentId:O}).strict(),a.object({op:a.literal("legacy.job.cancel"),jobId:O}).strict(),a.object({op:a.literal("commands.list")}).strict(),a.object({op:a.literal("commands.entities"),sessionId:R,command:O,name:a.string().max(128).optional()}).strict(),a.object({op:a.literal("models.catalogue"),live:a.boolean().optional()}).strict(),a.object({op:a.literal("usage.get"),provider:O.optional(),live:a.boolean().optional(),refresh:a.boolean().optional()}).strict(),a.object({op:a.literal("analytics.get"),sessionId:R.optional(),sinceMs:a.number().int().nonnegative().optional(),untilMs:a.number().int().nonnegative().optional(),days:a.number().int().min(1).max(366).optional()}).strict(),a.object({op:a.literal("analytics.models"),sessionId:R.optional(),sinceMs:a.number().int().nonnegative().optional(),untilMs:a.number().int().nonnegative().optional(),days:a.number().int().min(1).max(366).optional()}).strict(),a.object({op:a.literal("info.get")}).strict(),a.object({op:a.literal("sessions.report"),sessionId:R,recentLimit:a.number().int().min(0).max(50).optional()}).strict(),a.object({op:a.literal("skills.list"),sessionId:R,name:O.optional()}).strict(),a.object({op:a.literal("sessions.failovers"),sessionId:R}).strict(),a.object({op:a.literal("sessions.credential"),sessionId:R,action:a.enum(["list","store","forget"]),key:qt.optional(),value:en.optional(),confirmed:a.boolean().optional()}).strict(),a.object({op:a.literal("sessions.fork"),sessionId:R,requestId:Y,message:a.string().max(2e5).optional(),boundary:a.literal("next_safe").optional()}).strict(),a.object({op:a.literal("sessions.stop"),requestId:Y,targets:a.array(R).min(1).max(100),confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("sessions.aside"),sessionId:R,requestId:Y,text:a.string().min(1).max(32768),asideId:Y.optional(),subscriptionId:a.string().regex(qs).optional()}).strict(),a.object({op:a.literal("sessions.adopt"),sessionId:R,requestId:Y,asideId:Y,confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("sessions.aside.get"),sessionId:R,asideId:Y}).strict(),a.object({op:a.literal("sessions.aside.close"),sessionId:R,asideId:Y}).strict(),a.object({op:a.literal("wakes.list"),limit:a.number().int().min(1).max(500).optional(),includeDormant:a.boolean().optional()}).strict(),a.object({op:a.literal("wakes.create"),requestId:Y,sessionId:R.optional(),cwd:a.string().min(1).max(4096).optional(),target:nn.optional(),message:cr,in:a.string().min(1).max(64).optional(),at:a.string().min(1).max(64).optional(),every:a.string().min(1).max(64).optional(),until:a.string().min(1).max(64).optional(),limit:a.number().int().min(1).optional(),title:a.string().min(1).max(200).optional()}).strict(),a.object({op:a.literal("wakes.edit"),sessionId:R,wakeId:lr,message:cr.optional(),in:a.string().min(1).max(64).optional(),at:a.string().min(1).max(64).optional(),every:a.string().min(1).max(64).optional(),until:a.string().min(1).max(64).optional(),limit:a.number().int().min(1).optional()}).strict(),a.object({op:a.literal("wakes.remove"),sessionId:R,wakeId:lr}).strict(),a.object({op:a.literal("mcp.list"),sessionId:R}).strict(),a.object({op:a.literal("mcp.credentials.store"),sessionId:R,name:a.string().min(1).max(256),values:a.record(a.string().min(1).max(128),a.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:a.array(a.string().min(1).max(128)).max(32)}).strict(),a.object({op:a.literal("mcp.control"),sessionId:R,control:a.object({action:a.enum(["list","add","remove","reload","connect","probe","disconnect","login","logout","reauth","status","cancel"]),name:$n.optional(),scope:a.enum(["global","project"]).optional(),command:a.string().min(1).max(4096).optional(),args:a.array(a.string().max(8192)).max(128).optional(),env:a.record(tn).optional(),url:a.string().max(4096).optional(),headers:a.record(tn).optional(),oauth:a.boolean().optional(),confirmed:a.boolean().optional(),operation_id:Js.optional()}).strict()}).strict(),a.object({op:a.literal("mcp.catalog"),cwd:Un.optional(),sessionId:R.optional()}).strict(),a.object({op:a.literal("mcp.catalog.control"),cwd:Un.optional(),control:a.object({action:a.enum(["add","remove","test","login","reauth","logout","status","cancel"]),name:$n.optional(),scope:a.enum(["global","project"]).optional(),command:a.string().min(1).max(4096).optional(),args:a.array(a.string().max(8192)).max(128).optional(),env:a.record(tn).optional(),url:a.string().max(4096).optional(),headers:a.record(tn).optional(),confirmed:a.boolean().optional(),operation_id:Js.optional()}).strict()}).strict(),a.object({op:a.literal("mcp.catalog.credentials"),header:a.string().min(1).max(128).optional(),cwd:Un.optional(),name:$n,values:a.record(a.string().min(1).max(128),a.string().min(1).max(32768)).refine(e=>Object.keys(e).length<=32&&Object.values(e).reduce((t,n)=>t+n.length,0)<=65536,{message:"Too many secret values, or too much secret text, for one MCP credential write."}),confirmedReplace:a.array(a.string().min(1).max(128)).max(32)}).strict(),a.object({op:a.literal("radient.request"),control:a.object({operation:a.enum(["account","prices","credits","usage","provision","application.create","agents.list","agents.get","agents.create","agents.update","agents.delete","agents.like","agents.unlike","agents.liked","agents.like_count","agents.favourite","agents.unfavourite","agents.favourited","agents.favourite_count","agents.download_count","agents.statuses","comments.list","comments.create","comments.update","comments.delete","account.agents","memberships.list","org_agents.list","org_team.get","org_teams.list"]),request_id:Y.optional(),tenant_id:O.optional(),account_id:O.optional(),agent_id:O.optional(),comment_id:O.optional(),team_id:O.optional(),query:a.record(a.union([a.string().max(1024),a.number().int()])).optional(),payload:a.record(a.unknown()).optional(),confirmed:a.boolean().optional()}).strict()}).strict(),a.object({op:a.literal("providers.list")}).strict(),a.object({op:a.literal("accounts.list")}).strict(),a.object({op:a.literal("accounts.remove"),accountId:a.number().int().positive(),confirmed:a.literal(!0)}).strict(),a.object({op:a.literal("auth.start"),provider:O}).strict(),a.object({op:a.literal("auth.status"),id:O}).strict(),a.object({op:a.literal("auth.input"),id:O,promptId:O,value:en}).strict(),a.object({op:a.literal("auth.cancel"),id:O}).strict(),a.object({op:a.literal("auth.key"),provider:O,value:en}).strict(),a.object({op:a.literal("auth.logout"),provider:O}).strict(),a.object({op:a.literal("settings.list")}).strict(),a.object({op:a.literal("settings.edit"),key:qt,value:a.unknown().refine(e=>e!==void 0,"A setting value is required."),base:cc.optional()}).strict(),a.object({op:a.literal("settings.reset"),key:qt}).strict(),a.object({op:a.literal("config.get")}).strict(),a.object({op:a.literal("config.update"),value:uc}).strict(),a.object({op:a.literal("instructions.get")}).strict(),a.object({op:a.literal("instructions.update"),content:a.string().max(64e3)}).strict(),a.object({op:a.literal("credentials.list")}).strict(),a.object({op:a.literal("credentials.update"),key:qt,value:en}).strict(),a.object({op:a.literal("peers.list")}).strict(),a.object({op:a.literal("networks.list")}).strict(),a.object({op:a.literal("networks.invite"),networkId:Et,role:a.enum(["read","drive","admin"]),deviceId:Et.optional()}).strict(),a.object({op:a.literal("networks.member.remove"),networkId:Et,deviceId:Et,confirm:a.string().min(1).max(256)}).strict(),a.object({op:a.literal("sessions.transfer"),sessionId:R,to:a.union([a.literal("local"),Et]),keep:a.boolean().optional(),waitS:a.number().min(0).max(300).optional(),requestId:Y.optional()}).strict(),a.object({op:a.literal("projects.list")}).strict(),a.object({op:a.literal("projects.get"),key:qe}).strict(),a.object({op:a.literal("projects.create"),name:Bn,description:a.string().max(vr).optional(),status:gr.optional(),tags:yr.optional()}).strict(),a.object({op:a.literal("projects.update"),key:qe,fields:a.object({name:Bn.optional(),title:a.string().max(80).optional(),owner:a.string().max(80).optional(),team:a.string().max(80).optional(),description:a.string().max(vr).optional(),status:gr.optional(),progress:a.string().max(Ac).optional(),tags:yr.optional(),start_date:rn.optional(),target_date:rn.optional(),completed_at:rn.optional(),estimate:a.number().positive().max(1e3).optional(),estimate_unit:a.enum(["points","days"]).optional()}).strict()}).strict(),a.object({op:a.literal("projects.delete"),key:qe,confirmed_name:Bn}).strict(),a.object({op:a.literal("projects.link"),key:qe,sessionId:R}).strict(),a.object({op:a.literal("projects.unlink"),key:qe,sessionId:R}).strict(),a.object({op:a.literal("projects.milestone"),key:qe,name:a.string().min(1).max(_r),targetDate:rn.optional(),completed:a.boolean().optional()}).strict(),a.object({op:a.literal("projects.milestone.remove"),key:qe,name:a.string().min(1).max(_r)}).strict(),a.object({op:a.literal("aida.status")}).strict(),a.object({op:a.literal("aida.control"),action:a.enum(["open","pause","resume","greet","status"])}).strict()]);Pc.superRefine((e,t)=>{e.op!=="agent.publish"&&e.op!=="agent.republish"||e.visibility==="org"!=!!e.tenantId&&t.addIssue({code:a.ZodIssueCode.custom,message:'A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.'})});const _e={noCredential:"pairing.no-credential",refused:"pairing.refused",planeClosed:"pairing.plane-closed",transportFailed:"transport.failed"},Dc={runtimeUnreachable:"runtime_unreachable"},Ps="runtime_busy",Ri="runtime_retiring",Ds={[_e.noCredential]:"This app is not paired with the running Local Operator server, so this control is unavailable.",[_e.refused]:"This app's credential for the running Local Operator server was refused, so this control is unavailable.",[_e.planeClosed]:"The running Local Operator server does not accept this app's desktop controls.",[_e.transportFailed]:"The Local Operator server did not answer this request."},as={noCredential:"Restart with a desktop-managed backend to use these controls.",transportFailed:"The backend could not complete this request. Check its connection and try again."};function Ls(e){return e!==void 0&&Object.values(_e).includes(e)}function Lc(e,t){if(e.startsWith("/v1/desktop/")){if(t===401||t===403)return _e.refused;if(t===503)return _e.planeClosed}}const Nc=88e4,Mc=11e5,jc=2e4,$c=9e4,Uc=new Set(["analytics.get","analytics.models","sessions.report"]),Fc=new Set(["usage.get"]),Bc=new Set(["networks.list","peers.list"]),Zc=new Set([...Uc,...Fc,...Bc]),Gc=90,Hc=30,zc=300,Vc=10,Kc=15,Wc=1e4;function Yc(e){const n=e.to==="local"||e.keep?zc:Hc,s=Math.max(0,e.waitS??0);return(Gc+n+Vc+Kc)*1e3+s*1e3}function Qc(e){if(typeof e!="string"&&e.op==="sessions.transfer")return Yc(e)+Wc;const t=typeof e=="string"?e:e.op;return Zc.has(t)?$c:jc}const Xc=5e3;function Ai(e){return Qc(e)+Xc}const Ns="deadline_exceeded",Oi="foreground_required",Pi="View these completions in the foreground before marking them read.",Jc=new Set(["capabilities","accounts.list","analytics.get","analytics.models","commands.entities","commands.list","config.get","credentials.list","info.get","instructions.get","legacy.agent.get","legacy.agent.history","legacy.agent.schedules.list","legacy.agents.list","legacy.job.get","legacy.jobs.list","legacy.models","legacy.models.providers","legacy.schedule.get","legacy.schedules.list","mcp.catalog","mcp.list","models.catalogue","networks.list","peers.list","profiles.get","profiles.list","providers.list","sessions.aside.get","sessions.checkpoints","sessions.failovers","sessions.find","sessions.get","sessions.history","sessions.list","sessions.preview","sessions.report","sessions.search","sessions.variables.list","skills.list","subagents.transcript","teams.get","teams.list","usage.get"]),qc=new Set(["analytics.get","analytics.models","networks.list","peers.list","usage.get","sessions.report","info.get","sessions.failovers"]);function el(e,t){const n=Math.round(t/1e3),s=Ns;return e==="sessions.transfer"?{code:s,message:`The app waits up to ${n} seconds for a move, and it was still running when the app stopped waiting. The move was asked for, so its outcome is unknown from here: read the session again before moving it anywhere else.`}:Jc.has(e)?{code:s,message:qc.has(e)?`The app waits up to ${n} seconds for this panel's data, and the read was still running when the app stopped waiting. Nothing was read; reopen the panel to ask again.`:`The app waits up to ${n} seconds for this read, and it was still running when the app stopped waiting. Nothing was read; ask again.`}:{code:s,message:`The app waits up to ${n} seconds for this request, and it was still running when the app stopped waiting. It may or may not have reached the server; check the result before repeating it.`}}const mh=Nc,gh=Mc;function tl(e){return e.sessionId?{session_id:e.sessionId}:{...e.cwd?{cwd:e.cwd}:{},...e.target?{target:e.target}:{}}}function br(e){return{...e.in!==void 0?{in:e.in}:{},...e.at!==void 0?{at:e.at}:{},...e.every!==void 0?{every:e.every}:{},...e.until!==void 0?{until:e.until}:{},...e.limit!==void 0?{limit:e.limit}:{}}}function wr(e){if(e.visibility==="org"!=!!e.tenantId)throw new Error('A publication target needs both `visibility: "org"` and `tenantId`, or neither: one half would publish to the public hub.')}function nl(e){switch(e.op){case"capabilities":return{path:"/v1/capabilities",method:"GET"};case"peers.list":return{path:"/v1/desktop/peers",method:"GET"};case"networks.list":return{path:"/v1/desktop/networks",method:"GET"};case"networks.invite":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/invite`,method:"POST",body:{role:e.role,device:e.deviceId??null}};case"networks.member.remove":return{path:`/v1/desktop/networks/${encodeURIComponent(e.networkId)}/members/${encodeURIComponent(e.deviceId)}`,method:"DELETE",body:{confirm:e.confirm}};case"sessions.transfer":return{path:`/v1/desktop/sessions/${encodeURIComponent(e.sessionId)}/transfer`,method:"POST",body:{to:e.to,keep:e.keep??!1,wait_s:e.waitS??0,...e.requestId?{request_id:e.requestId}:{}}};case"profiles.list":return{path:"/v1/desktop/profiles",method:"GET"};case"profiles.get":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"GET"};case"profiles.install":return{path:"/v1/desktop/profiles/install",method:"POST",body:{request_id:e.requestId,name:e.name}};case"profiles.create":return{path:"/v1/desktop/profiles",method:"POST",body:{request_id:e.requestId,name:e.name,...e.fields}};case"profiles.update":return{path:`/v1/desktop/profiles/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields}};case"teams.list":return{path:"/v1/desktop/teams",method:"GET"};case"teams.get":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"GET"};case"teams.create":return{path:"/v1/desktop/teams",method:"POST",body:{request_id:e.requestId,...e.fields}};case"teams.update":return{path:`/v1/desktop/teams/${encodeURIComponent(e.name)}`,method:"PATCH",body:{request_id:e.requestId,...e.fields}};case"sessions.list":{const t=new URLSearchParams;return t.set("limit",String(e.limit??100)),e.include_archived&&t.set("include_archived","true"),e.scope_kind&&t.set("scope_kind",e.scope_kind),e.scope_name&&t.set("scope_name",e.scope_name),e.cursor&&t.set("cursor",e.cursor),e.with_counts&&t.set("with_counts","true"),e.include_peers&&t.set("include_peers","true"),{path:`/v1/desktop/sessions?${t}`,method:"GET"}}case"sessions.search":{const t=new URLSearchParams({q:e.q,limit:String(e.limit??sc)});return e.include_archived&&t.set("include_archived","true"),{path:`/v1/desktop/sessions/search?${t}`,method:"GET"}}case"sessions.archive":return{path:`/v1/desktop/sessions/${e.sessionId}/archive`,method:"POST",body:{archived:e.archived}};case"sessions.delete":return{path:`/v1/desktop/sessions/${e.sessionId}`,method:"DELETE",body:{confirmed:!0}};case"sessions.create":return{path:"/v1/desktop/sessions",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{},...e.draftId?{draft_id:e.draftId}:{}}};case"sessions.preview":return{path:"/v1/desktop/sessions/preview",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}}};case"sessions.draft":return{path:"/v1/desktop/sessions/draft",method:"POST",body:{request_id:e.requestId,cwd:e.cwd,...e.target?{target:e.target}:{},...e.model?{model:e.model}:{}}};case"sessions.get":return{path:`/v1/desktop/sessions/${e.sessionId}`,method:"GET"};case"sessions.history":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),{path:`/v1/desktop/sessions/${e.sessionId}/history?${t}`,method:"GET"}}case"sessions.checkpoints":return{path:`/v1/desktop/sessions/${e.sessionId}/checkpoints`,method:"GET"};case"sessions.checkpoints.warm":return{path:`/v1/desktop/sessions/${e.sessionId}/checkpoints/warm`,method:"POST",body:{...e.ids?{ids:e.ids}:{},...e.limit!==void 0?{limit:e.limit}:{}}};case"sessions.find":{const t=new URLSearchParams({q:e.q,limit:String(e.limit??ic)});return{path:`/v1/desktop/sessions/${e.sessionId}/find?${t}`,method:"GET"}}case"subagents.transcript":{const t=new URLSearchParams({limit:String(e.limit??100)});return e.beforeId&&t.set("before_id",e.beforeId),{path:`/v1/desktop/sessions/${e.sessionId}/children/${e.childId}/transcript?${t}`,method:"GET"}}case"sessions.message":return{path:`/v1/desktop/sessions/${e.sessionId}/messages`,method:"POST",body:{request_id:e.requestId,text:e.text,images:e.images??[],mode:e.mode??"prompt",...e.inputMode?{input_mode:e.inputMode}:{},...e.inputPath?{input_path:e.inputPath}:{}}};case"sessions.command":return{path:`/v1/desktop/sessions/${e.sessionId}/commands`,method:"POST",body:{request_id:e.requestId,command:e.command,args:e.args??"",images:e.images??[]}};case"sessions.answer":return{path:`/v1/desktop/sessions/${e.sessionId}/answers`,method:"POST",body:{epoch:e.epoch,request_id:e.requestId,value:e.value,approved:e.approved,question_index:e.questionIndex}};case"sessions.seen":return{path:`/v1/desktop/sessions/${e.sessionId}/seen`,method:"POST",body:{completion_token:e.completionToken}};case"attention.seen":return{path:"/v1/desktop/attention/seen",method:"POST",body:{items:e.items.map(t=>({session_id:t.sessionId,completion_token:t.completionToken}))}};case"sessions.notified":return{path:`/v1/desktop/sessions/${e.sessionId}/notified`,method:"POST",body:{completion_token:e.completionToken}};case"sessions.pin":return{path:`/v1/desktop/sessions/${e.sessionId}/pin`,method:"POST",body:{pinned:e.pinned}};case"sessions.watch":return{path:`/v1/desktop/sessions/${e.sessionId}/watch`,method:"POST",body:{subscription_id:e.subscriptionId,visible:e.visible,can_notify:e.canNotify}};case"sessions.presence":return{path:"/v1/desktop/presence",method:"POST",body:{subscription_id:e.subscriptionId,can_notify_kinds:e.canNotifyKinds,session_id:e.sessionId,window:e.window,can_notify:e.canNotify}};case"sessions.move":return{path:`/v1/desktop/sessions/${e.sessionId}/working-directory`,method:"POST",body:{request_id:e.requestId,cwd:e.cwd}};case"sessions.warm":return{path:`/v1/desktop/sessions/${e.sessionId}/warm`,method:"POST",body:{}};case"sessions.interrupt":return{path:`/v1/desktop/sessions/${e.sessionId}/interrupt`,method:"POST",body:{request_id:e.requestId}};case"sessions.variables.list":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"GET"};case"sessions.variables.create":return{path:`/v1/desktop/sessions/${e.sessionId}/variables`,method:"POST",body:{key:e.key,value:e.value,type:e.type}};case"sessions.variables.update":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"PATCH",body:{value:e.value,type:e.type}};case"sessions.variables.delete":return{path:`/v1/desktop/sessions/${e.sessionId}/variables/${encodeURIComponent(e.key)}`,method:"DELETE"};case"legacy.models":{const t=new URLSearchParams;return e.provider&&t.set("provider",e.provider),e.sort&&t.set("sort",e.sort),e.direction&&t.set("direction",e.direction),{path:t.size>0?`/v1/models?${t}`:"/v1/models",method:"GET"}}case"legacy.models.providers":return{path:"/v1/models/providers",method:"GET"};case"auth.probe":return{path:`/v1/auth/providers/${e.provider}/probe`,method:"POST"};case"legacy.agent.upload":return{path:`/v1/agents/${e.agentId}/upload`,method:"POST"};case"agent.publish":{wr(e);const t=new URLSearchParams;e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId));const n=t.toString();return{path:`/v1/agents/${e.agentId}/publish${n?`?${n}`:""}`,method:"POST",body:{document:e.document??{}}}}case"agent.republish":{wr(e);const t=new URLSearchParams;e.visibility==="org"&&e.tenantId&&(t.set("visibility","org"),t.set("tenant_id",e.tenantId));const n=t.toString();return{path:`/v1/agents/${e.agentId}/publish${n?`?${n}`:""}`,method:"PUT",body:{hub_agent_id:e.hubAgentId,document:e.document??{}}}}case"team.pull":{const t=new URLSearchParams;e.tenantId&&t.set("tenant_id",e.tenantId);const n=t.toString();return{path:`/v1/teams/pull/${e.teamId}${n?`?${n}`:""}`,method:"GET"}}case"agent.nameAvailability":return{path:`/v1/agent-name-availability?${new URLSearchParams({name:e.name})}`,method:"GET"};case"legacy.agents.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return e.name&&t.set("name",e.name),e.sort&&t.set("sort",e.sort),e.direction&&t.set("direction",e.direction),{path:`/v1/agents?${t}`,method:"GET"}}case"legacy.agent.get":return{path:`/v1/agents/${e.agentId}`,method:"GET"};case"legacy.agent.history":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/history?${t}`,method:"GET"}}case"wakes.list":{const t=new URLSearchParams;return e.limit!==void 0&&t.set("limit",String(e.limit)),e.includeDormant!==void 0&&t.set("include_dormant",String(e.includeDormant)),{path:t.size>0?`/v1/desktop/wakes?${t}`:"/v1/desktop/wakes",method:"GET"}}case"wakes.create":return{path:"/v1/desktop/wakes",method:"POST",body:{request_id:e.requestId,...tl(e),message:e.message,...br(e)}};case"wakes.edit":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"PATCH",body:{...e.message!==void 0?{message:e.message}:{},...br(e)}};case"wakes.remove":return{path:`/v1/desktop/wakes/${e.sessionId}/${e.wakeId}`,method:"DELETE"};case"legacy.jobs.list":{const t=new URLSearchParams;return e.agentId&&t.set("agent_id",e.agentId),e.status&&t.set("status",e.status),{path:t.size>0?`/v1/jobs?${t}`:"/v1/jobs",method:"GET"}}case"legacy.job.get":return{path:`/v1/jobs/${e.jobId}`,method:"GET"};case"legacy.schedules.list":return{path:`/v1/schedules?${new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)})}`,method:"GET"};case"legacy.agent.schedules.list":{const t=new URLSearchParams({page:String(e.page??1),per_page:String(e.perPage??10)});return{path:`/v1/agents/${e.agentId}/schedules?${t}`,method:"GET"}}case"legacy.agent.schedule.create":return{path:`/v1/agents/${e.agentId}/schedules`,method:"POST",body:e.schedule};case"legacy.schedule.get":return{path:`/v1/schedules/${e.scheduleId}`,method:"GET"};case"legacy.schedule.edit":return{path:`/v1/schedules/${e.scheduleId}`,method:"PATCH",body:e.schedule};case"legacy.schedule.remove":return{path:`/v1/schedules/${e.scheduleId}`,method:"DELETE"};case"legacy.agent.create":return{path:"/v1/agents",method:"POST",body:e.agent};case"legacy.agent.update":return{path:`/v1/agents/${e.agentId}`,method:"PATCH",body:e.update};case"legacy.agent.delete":return{path:`/v1/agents/${e.agentId}`,method:"DELETE"};case"legacy.agent.conversation.clear":return{path:`/v1/agents/${e.agentId}/conversation`,method:"DELETE"};case"legacy.agent.systemPrompt.get":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"GET"};case"legacy.agent.systemPrompt.update":return{path:`/v1/agents/${e.agentId}/system-prompt`,method:"PUT",body:{system_prompt:e.systemPrompt}};case"legacy.agent.download":return{path:`/v1/agents/${e.agentId}/download`,method:"GET"};case"legacy.job.cancel":return{path:`/v1/jobs/${e.jobId}`,method:"DELETE"};case"commands.list":return{path:"/v1/desktop/commands",method:"GET"};case"commands.entities":return{path:`/v1/desktop/sessions/${e.sessionId}/command-entities?command=${encodeURIComponent(e.command)}${e.name?`&name=${encodeURIComponent(e.name)}`:""}`,method:"GET"};case"models.catalogue":return{path:`/v1/desktop/models?live=${e.live??!1}`,method:"GET"};case"usage.get":{const t=new URLSearchParams({live:String(e.live??!1),refresh:String(e.refresh??!1)});return e.provider&&t.set("provider",e.provider),{path:`/v1/desktop/usage?${t}`,method:"GET"}}case"analytics.get":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics?${t}`,method:"GET"}}case"analytics.models":{const t=new URLSearchParams({days:String(e.days??30)});return e.sessionId&&t.set("session_id",e.sessionId),e.sinceMs!==void 0&&t.set("since_ms",String(e.sinceMs)),e.untilMs!==void 0&&t.set("until_ms",String(e.untilMs)),{path:`/v1/desktop/analytics/models?${t}`,method:"GET"}}case"info.get":return{path:"/v1/desktop/info",method:"GET"};case"sessions.report":{const t=new URLSearchParams({recent_limit:String(e.recentLimit??12)});return{path:`/v1/desktop/sessions/${e.sessionId}/report?${t}`,method:"GET"}}case"skills.list":return{path:`/v1/desktop/skills?session_id=${e.sessionId}${e.name?`&name=${encodeURIComponent(e.name)}`:""}`,method:"GET"};case"sessions.failovers":return{path:`/v1/desktop/sessions/${e.sessionId}/failovers`,method:"GET"};case"sessions.credential":return{path:`/v1/desktop/sessions/${e.sessionId}/credentials`,method:"POST",body:{action:e.action,key:e.key,value:e.value,confirmed:e.confirmed}};case"sessions.fork":return{path:`/v1/desktop/sessions/${e.sessionId}/fork`,method:"POST",body:{request_id:e.requestId,message:e.message,boundary:e.boundary}};case"sessions.stop":return{path:"/v1/desktop/stop",method:"POST",body:{request_id:e.requestId,targets:e.targets,confirmed:e.confirmed}};case"sessions.aside":return{path:`/v1/desktop/sessions/${e.sessionId}/asides`,method:"POST",body:{request_id:e.requestId,text:e.text,aside_id:e.asideId,subscription_id:e.subscriptionId}};case"sessions.adopt":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}/adopt`,method:"POST",body:{request_id:e.requestId,confirmed:e.confirmed}};case"sessions.aside.get":case"sessions.aside.close":return{path:`/v1/desktop/sessions/${e.sessionId}/asides/${e.asideId}`,method:e.op==="sessions.aside.get"?"GET":"DELETE"};case"mcp.list":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"GET"};case"mcp.credentials.store":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp/credentials`,method:"POST",body:{name:e.name,values:e.values,confirmed_replace:e.confirmedReplace}};case"mcp.control":return{path:`/v1/desktop/sessions/${e.sessionId}/mcp`,method:"POST",body:e.control};case"mcp.catalog":{const t=new URLSearchParams;e.cwd&&t.set("cwd",e.cwd),e.sessionId&&t.set("session_id",e.sessionId);const n=t.toString();return{path:n?`/v1/desktop/mcp?${n}`:"/v1/desktop/mcp",method:"GET"}}case"mcp.catalog.control":return{path:"/v1/desktop/mcp",method:"POST",body:{...e.control,...e.cwd?{cwd:e.cwd}:{}}};case"mcp.catalog.credentials":return{path:"/v1/desktop/mcp/credentials",method:"POST",body:{name:e.name,values:e.values,...e.header?{header:e.header}:{},confirmed_replace:e.confirmedReplace,...e.cwd?{cwd:e.cwd}:{}}};case"radient.request":return{path:"/v1/desktop/radient",method:"POST",body:e.control};case"providers.list":return{path:"/v1/auth/providers",method:"GET"};case"accounts.list":return{path:"/v1/auth/status",method:"GET"};case"accounts.remove":return{path:`/v1/auth/accounts/${e.accountId}`,method:"DELETE"};case"auth.start":return{path:"/v1/auth/login",method:"POST",body:{provider:e.provider}};case"auth.status":return{path:`/v1/auth/operations/${e.id}`,method:"GET"};case"auth.input":return{path:`/v1/auth/operations/${e.id}/input`,method:"POST",body:{prompt_id:e.promptId,value:e.value}};case"auth.cancel":return{path:`/v1/auth/operations/${e.id}`,method:"DELETE"};case"auth.key":return{path:`/v1/auth/providers/${e.provider}/key`,method:"PUT",body:{value:e.value}};case"auth.logout":return{path:`/v1/auth/providers/${e.provider}/credentials`,method:"DELETE"};case"settings.list":return{path:"/v1/settings",method:"GET"};case"settings.edit":return{path:`/v1/settings/${e.key}`,method:"PATCH",body:{value:e.value,base:e.base}};case"settings.reset":return{path:`/v1/settings/${e.key}/reset`,method:"POST"};case"config.get":return{path:"/v1/config",method:"GET"};case"config.update":return{path:"/v1/config",method:"PATCH",body:e.value};case"instructions.get":return{path:"/v1/config/system-prompt",method:"GET"};case"instructions.update":return{path:"/v1/config/system-prompt",method:"PATCH",body:{content:e.content}};case"credentials.list":return{path:"/v1/credentials",method:"GET"};case"credentials.update":return{path:"/v1/credentials",method:"PATCH",body:{key:e.key,value:e.value}};case"projects.list":return{path:"/v1/desktop/projects",method:"GET"};case"projects.get":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"GET"};case"projects.create":return{path:"/v1/desktop/projects",method:"POST",body:{name:e.name,...e.description!==void 0?{description:e.description}:{},...e.status!==void 0?{status:e.status}:{},...e.tags!==void 0?{tags:e.tags}:{}}};case"projects.update":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"PATCH",body:{...e.fields}};case"projects.delete":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}`,method:"DELETE",body:{confirm:e.confirmed_name}};case"projects.link":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links`,method:"POST",body:{session_id:e.sessionId}};case"projects.unlink":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/links/${encodeURIComponent(e.sessionId)}`,method:"DELETE"};case"projects.milestone":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones`,method:"POST",body:{name:e.name,...e.targetDate!==void 0?{target_date:e.targetDate}:{},...e.completed!==void 0?{completed:e.completed}:{}}};case"projects.milestone.remove":return{path:`/v1/desktop/projects/${encodeURIComponent(e.key)}/milestones/${encodeURIComponent(e.name)}`,method:"DELETE"};case"aida.status":return{path:"/v1/desktop/aida",method:"GET"};case"aida.control":return{path:"/v1/desktop/aida",method:"POST",body:{op:e.action}}}}const yh=64,vh=64*1024*1024,Pt={notPaired:"This backend was not started with desktop controls.",serverDown:"The Local Operator server is not answering.",frameBudget:"The event stream exceeded its frame budget.",ended:"The event stream ended."},Sr={statement:"Lost the connection to this conversation — reconnect to keep reading.",action:"reconnect"},sl={statement:"The Local Operator server is not running — reconnect once it is back, or restart the app if it stays down.",action:"reconnect"},rl={statement:"This app is not paired with the Local Operator server, so this conversation cannot be read yet.",action:null},il={statement:"Could not load this conversation's history — reconnect to try again.",action:"reconnect"},ol={statement:"This conversation's updates were too large to display — reconnect to try again.",action:"reconnect"};function kr(e){return e?e===Pt.notPaired?rl:e===Pt.serverDown?sl:e===Pt.frameBudget?ol:Sr:Sr}async function Di(e){if(window.api?.desktop)try{return await al(window.api.desktop.request(e),e)}catch(n){throw n instanceof X?n:dl(n)?new Ke(Pi,Oi):new X(null,"Desktop controls could not reach the backend process.",n)}let t;try{t=await fetch("/__desktop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(n){throw new X(null,"Desktop controls could not reach the backend process.",n)}if(!t.ok)throw new X(t.status,"Desktop controls need a compatible backend connection.");return t.json()}function al(e,t){const n=Ai(t);let s;return Promise.race([e,new Promise((r,i)=>{s=setTimeout(()=>{const o=el(t.op,n);i(new X(null,o.message,void 0,o.code))},n)})]).finally(()=>clearTimeout(s))}class X extends Error{status;cause;code;retryAfterMs;constructor(t,n,s,r,i){super(n),this.name="DesktopControlError",this.status=t,this.cause=s,this.code=r,this.retryAfterMs=i}}class Ke extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function In(e,t){return e instanceof X||e instanceof Ke?Ls(e.code)?Ds[e.code]:e.message:t}function cl(e,t,n,s){return typeof s=="string"?s:n===as.noCredential?_e.noCredential:n===as.transportFailed?_e.transportFailed:Lc(nl(e).path,t)}async function ce(e){const t=await Di(e),n=t.body;if(t.status<200||t.status>=300){const s=typeof n?.detail=="string"?n.detail:typeof n?.detail?.message=="string"?n.detail.message:null;throw new X(t.status,s??"This server did not answer the request for its desktop controls.",void 0,cl(e,t.status,s,typeof n?.detail=="object"?n.detail?.code:void 0),typeof n?.detail=="object"&&typeof n.detail?.retry_after_ms=="number"&&Number.isFinite(n.detail.retry_after_ms)?n.detail.retry_after_ms:void 0)}return n?.result}function ll(e){return e instanceof X&&e.code===Ns}function _h(e){return e instanceof X?e.status===null||e.status===503:!1}function bh(e){return e instanceof Ke&&e.code===Oi}function dl(e){return e instanceof Error&&e.message.includes(Pi)}async function wh(e){const t=await Di(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function Sh(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await ce({op:"auth.status",id:e});if(!n.auth_url)throw new Error("This sign-in is no longer waiting for a browser.");const s=new URL(n.auth_url);if(s.username||s.password||s.protocol!=="https:"&&!(s.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(s.hostname)))throw new Error("The provider returned an invalid sign-in address.");window.open(s.href,"_blank","noopener,noreferrer")}function ul(e,t){const n=window.api?.desktop?.stream;if(n){const i=n.subscribe(e,t);return()=>i.dispose()}const s=new URLSearchParams({session:e.sessionId});e.epoch&&s.set("epoch",e.epoch),e.afterSeq!==void 0&&s.set("after_seq",String(e.afterSeq)),s.set("frontend_replace","1");const r=new EventSource(`/__desktop/stream?${s}`);return r.onmessage=i=>{t({kind:"data",data:i.data})},r.onerror=()=>{r.readyState===EventSource.CLOSED&&(t({kind:"error",detail:Pt.ended}),r.close())},()=>{r.close(),t({kind:"end"})}}async function fl(e,t){const n=window.api?.desktop?.media;if(n)return n(e,t);const s=await fetch("/__desktop/media",{method:"POST",headers:{"x-desktop-media":JSON.stringify(e),"Content-Type":"application/octet-stream"},body:t?new Blob([t]):void 0}),r=s.headers.get("content-type")??"";if(!s.ok){let i="The media request failed.";if(r.includes("application/json"))try{const o=await s.json();typeof o.detail=="string"&&(i=o.detail)}catch{}return{status:s.status,kind:"error",detail:i,code:i===as.noCredential?_e.noCredential:void 0}}return r.includes("application/json")?{status:s.status,kind:"json",body:await s.json()}:{status:s.status,kind:"bytes",mimeType:r||"application/octet-stream",data:new Uint8Array(await s.arrayBuffer())}}function pl(e){return e.kind==="error"?Ls(e.code)?new Ke(Ds[e.code],e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}const kh="superseded_completion_token",Th="store_busy";function Eh(e,t,n){if(!e||typeof e!="object")return!1;const s=e;return s.unseen===!1&&s.conversation_id===`session/${t}`&&s.completion_token===n}function vt(e,t,n){return!t||t.conversation_id!==`session/${n}`||!Array.isArray(t.revision)||t.revision.length!==2||!t.revision.every(s=>Number.isSafeInteger(s)&&s>=0)||e?.conversation_id===t.conversation_id&&(t.revision[0]<e.revision[0]||t.revision[1]<e.revision[1])?e:t.supported===void 0&&e?.supported!==void 0?{...t,supported:e.supported}:t}function hl(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const xh=e=>typeof e?.goal_status=="string",Ih=e=>(e?.goal??"").trim().length>0;function ml(e,t,n){return n.session_id!==t||n.payload.frontend.snapshot.session_id!==t||!e?!1:e.epoch===n.epoch&&n.seq>e.seq}const Li=/\s+/,gl=/[\\/]+$/,yl=/[\\/]/,Ni=`
|
|
2
2
|
|
|
3
|
-
`,
|
|
4
|
-
`)){const n=cs(t);if(n)return n}return""}function
|
|
5
|
-
`)){const s=n.trim();if(s&&!
|
|
6
|
-
`):null;if(!Array.isArray(t))return null;const n=t.filter(s=>typeof s=="string");return n.length?n:null}function
|
|
3
|
+
`,vl=" — cancel with wake(",_l=120,bl=/(?:\u001b[\]PX^_]|[\u009d\u0090\u0098\u009e\u009f])(?:(?!\u0007|\u001b\\|\u009c)[\s\S])*(?:\u0007|\u001b\\|\u009c|$)|(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]|(?:\u001b\[|\u009b)[0-?]*[ -/]*$|\u001b[ -/]+[0-~]|\u001b[@-Z\\-_]|\u001b$|[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g,wl=new RegExp("\\p{Cf}","gu"),Sl=4096;function cs(e){return e==null?"":(typeof e=="string"?e:String(e)).replace(bl,"").replace(wl,"").split(Li).filter(Boolean).join(" ").slice(0,_l)}function Mi(e){if(e.conversationName)return{name:e.conversationName,quoted:!0};const t=e.cwd.replace(gl,"");if(t){const n=t.split(yl).pop()??"";if(n)return{name:`${n}/`,quoted:!1}}return e.sessionId?{name:e.sessionId.slice(0,8),quoted:!1}:{name:"",quoted:!1}}function ji(e){const{name:t,quoted:n}=Mi(e);return t?n?`"${t}"`:t:e.pid?`pid ${e.pid}`:"another session"}function kl(e){const{name:t,quoted:n}=Mi(e),s=[];return e.pid&&s.push(`pid ${e.pid}`),e.modelLabel&&s.push(e.modelLabel),t?[n?`"${t}"`:t,...s].join(" · "):s.length>0?s.join(" · "):"another session"}function Ch(e,t){return t.trim()?!0:kl(e)!==ji(e)}function Tl(e){for(const t of e.slice(0,Sl).split(`
|
|
4
|
+
`)){const n=cs(t);if(n)return n}return""}function Rh(e,t){const n=ji(e),s=Tl(t);return s?`${n} · ${s}`:n}function El(e,t){return e.pid===t.pid&&e.conversationName===t.conversationName&&e.cwd===t.cwd&&e.sessionId===t.sessionId&&e.modelLabel===t.modelLabel}const xl=/^<peer-session-message\s+((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/peer-session-message>\s*$/,Il=/<\/?peer-session-message(?:[^>"']|"[^"]*"|'[^']*')*>/g,Cl=/^<peer-session-message[^>]*>/,Rl=/([a-zA-Z_]+)\s*=\s*(?:'([^']*)'|"([^"]*)"|([^\s>]+))/g;function Al(e){const t=String(e.text??e.detail??""),n=xl.exec(t.trim()),s={};if(n)for(const d of n[1].matchAll(Rl))s[d[1]]=d[2]??d[3]??d[4]??"";const r=n?n[2]:"",o=(String(e.body??"").trim()||r||(n?"":t.trim().replace(Cl,""))).replace(Il,"").trim(),c=e.sender??{},l=(d,u)=>cs(d)||cs(u);return{body:o,sender:{pid:l(c.pid,s.from_pid),conversationName:l(c.conversation_name,s.conversation),cwd:l(c.cwd,void 0),sessionId:l(c.session_id,void 0),modelLabel:l(c.model_label,s.model)}}}function Ol(e){return!!e.wake_catchup}function Ah(e){let t=e.split(Ni)[0]??"";t=t.split(Li).filter(Boolean).join(" "),t=t.split(vl)[0];const n="(alarm) ";for(;t.startsWith(n);)t=t.slice(n.length);const s="Scheduled wake ";return t.startsWith(s)&&(t=t.slice(s.length)),t.trim()}function Oh(e){const t=e.indexOf(Ni);return t===-1?"":e.slice(t+2).trim()}const Pl=new Set(["command","path","file_path","url","pattern","query","name","target","message","milestone"]),Dl=new Set(["true","yes","y","t","on","1"]),Ll={hub:{steps:e=>{const t=Tr(e);return t!==null&&Number.isInteger(t)&&t>=0?`${t} ${t===1?"step":"steps"}`:""}},wait:{wait_ms:e=>{const t=Tr(e);return t!==null&&t>0?`· ${Ui(t/1e3)}`:""}}};function Tr(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="string"&&e!==""){const t=Number(e);return Number.isFinite(t)?t:null}return null}const Er="mcp__",Nl=/^\/(?:Users|home)\/[^/]+\//,Ml=/\s+/;function jl(e){return!e.startsWith("/")||e.includes(" ")?e:e.replace(Nl,"~/")}function bn(e){return typeof e=="string"?jl(e.trim()).replace(/\n/g," ").trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function $l(e){return e.now?"now":e.wake===!1?"quiet":"wake"}function Ul(e){const t=e.pid;if(typeof t=="number"&&Number.isFinite(t))return`pid ${t}`;const n=String(e.session??"").trim();return n?`session ${n}`:String(e.target??"").split(Ml).filter(Boolean).join(" ")||"?"}function Fl(e){return[$l(e),bn(Ul(e))||"?",bn(e.message)].filter(Boolean).join(" · ")}function Ph(e,t){const n=e.trim();if(!t)return n;if(n==="send")return Fl(t)||n;const s=Hl(n)?Object.entries(t).filter(([i])=>!Fi.has(i)):Object.entries(t);let r=s.filter(([i])=>Pl.has(i)).map(([,i])=>bn(i)).filter(Boolean);if(r.length===0){const i=Ll[n.toLowerCase()];r=s.map(([o,c])=>i?.[o]?.(c)||bn(c)).filter(Boolean)}return r.slice(0,2).join(" ")||n}function $i(e){const t=e.trim();if(!t.toLowerCase().startsWith(Er))return t;const n=t.slice(Er.length),s=n.indexOf("_");return s<=0?n||t:n.slice(s+1)||n}function Bl(e,t){return e===t||e===$i(t)}const Zl=/^(?:exit code:?\s*-?\d*|\(empty\)|--- (?:stdout|stderr) ---)$/,Gl="… ";function Dh(e,t=!1){if(!e||t)return null;for(const n of e.split(`
|
|
5
|
+
`)){const s=n.trim();if(s&&!Zl.test(s))return`${Gl}${s.slice(0,160)}`}return null}function Ui(e){const t=Math.max(0,Math.floor(e));if(t<60)return`${t}s`;if(t<3600){const r=Math.floor(t/60),i=t%60;return i===0?`${r}m`:`${r}m${i}s`}if(t<86400){const r=Math.floor(t/3600),i=Math.floor(t%3600/60);return i===0?`${r}h`:`${r}h${i}m`}const n=Math.floor(t/86400);if(n>99)return"100d+";const s=Math.floor(t%86400/3600);return s===0?`${n}d`:`${n}d${s}h`}function Lh(e){if(e===null)return"";const t=Math.max(0,e);return t<.05?"<0.1s":t<10?`${t.toFixed(1)}s`:t<60?`${Math.round(t)}s`:Ui(t)}function xr(e){const t=e*10,n=Math.floor(t),s=t-n;return((s>.5?n+1:s<.5||n%2===0?n:n+1)/10).toFixed(1)}function Nh(e){return e<1024?`${e} B`:e<1024*1024?`${xr(e/1024)} KB`:`${xr(e/(1024*1024))} MB`}function Ir(e){return typeof e!="number"||!Number.isInteger(e)||e<=0?0:e}const Cr={read:"read",glob:"read",grep:"read",web_fetch:"read",web_read:"read",web_search:"read",browser:"read",lsp:"read",list_variables:"read",read_variable:"read",write:"mutate",edit:"mutate",bash:"exec",eval:"exec",console:"exec",task:"meta",agent:"meta",team:"meta",hub:"meta",todo:"meta",send:"meta",wake:"meta",ask:"meta",wait:"meta",jobs:"meta",secret:"meta",network:"meta",project:"meta",team_delete:"meta",project_delete:"meta"};function Mh(e){const t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Cr,t)?Cr[t]:"plain"}function jh(e){if(!e)return"";for(const t of Fi){const n=e[t];if(typeof n=="string"&&n.trim()){const s=n.trim().toLowerCase(),r=e.remove,i=r===!0||r===1||typeof r=="string"&&Dl.has(r.toLowerCase());return s==="milestone"&&i?"milestone-remove":s}}return""}const Fi=new Set(["op","action","method"]),Hl=e=>Object.prototype.hasOwnProperty.call(Bi,e.trim().toLowerCase()),zl={bash:{settled:"Ran",running:"Running"},eval:{settled:"Ran Python",running:"Running Python"},read:{settled:"Read",running:"Reading"},write:{settled:"Wrote",running:"Writing"},edit:{settled:"Edited",running:"Editing"},glob:{settled:"Listed",running:"Listing"},grep:{settled:"Searched",running:"Searching"},web_search:{settled:"Searched the web",running:"Searching the web"},web_fetch:{settled:"Fetched",running:"Fetching"},web_read:{settled:"Read",running:"Reading"},browser:{settled:"Browsed",running:"Browsing"},list_variables:{settled:"Listed variables",running:"Listing variables"},read_variable:{settled:"Read variable",running:"Reading variable"},ask:{settled:"Asked",running:"Asking"},send:{settled:"Sent",running:"Sending"},wait:{settled:"Waited for jobs",running:"Waiting for jobs"},team_delete:{settled:"Deleted team",running:"Deleting team"},project_delete:{settled:"Deleted project",running:"Deleting project"},peer:{settled:"Received",running:"Receiving"},task:{settled:"Delegated",running:"Delegating"}},Bi={agent:{list:{settled:"Listed agents",running:"Listing agents"},show:{settled:"Viewed agent",running:"Viewing agent"},search:{settled:"Searched agents",running:"Searching agents"},install:{settled:"Installed agent",running:"Installing agent"},reset:{settled:"Reset agent",running:"Resetting agent"},create:{settled:"Created agent",running:"Creating agent"},update:{settled:"Updated agent",running:"Updating agent"},sync:{settled:"Synced agents",running:"Syncing agents"}},team:{list:{settled:"Listed teams",running:"Listing teams"},show:{settled:"Viewed team",running:"Viewing team"},create:{settled:"Created team",running:"Creating team"},update:{settled:"Updated team",running:"Updating team"}},hub:{list:{settled:"Listed subagents",running:"Listing subagents"},peek:{settled:"Peeked at",running:"Peeking at"},send:{settled:"Messaged",running:"Messaging"},ask:{settled:"Asked",running:"Asking"},steer:{settled:"Steered",running:"Steering"},pause:{settled:"Paused",running:"Pausing"},cancel:{settled:"Cancelled",running:"Cancelling"},resume:{settled:"Resumed",running:"Resuming"}},secret:{store:{settled:"Stored secret",running:"Storing secret"},retrieve:{settled:"Retrieved secret",running:"Retrieving secret"},list:{settled:"Listed secrets",running:"Listing secrets"},describe:{settled:"Described secret",running:"Describing secret"},update:{settled:"Updated secret",running:"Updating secret"},delete:{settled:"Deleted secret",running:"Deleting secret"}},project:{list:{settled:"Listed projects",running:"Listing projects"},show:{settled:"Viewed project",running:"Viewing project"},create:{settled:"Created project",running:"Creating project"},update:{settled:"Updated project",running:"Updating project"},link:{settled:"Linked session to",running:"Linking session to"},unlink:{settled:"Unlinked session from",running:"Unlinking session from"},milestone:{settled:"Updated milestone",running:"Updating milestone"},"milestone-remove":{settled:"Removed milestone",running:"Removing milestone"}},todo:{view:{settled:"Read todos",running:"Reading todos"},init:{settled:"Updated todos",running:"Updating todos"},add:{settled:"Updated todos",running:"Updating todos"},done:{settled:"Updated todos",running:"Updating todos"},block:{settled:"Updated todos",running:"Updating todos"},drop:{settled:"Updated todos",running:"Updating todos"}},wake:{create:{settled:"Scheduled",running:"Scheduling"},list:{settled:"Listed wakes",running:"Listing wakes"},cancel:{settled:"Cancelled wake",running:"Cancelling wake"}},jobs:{list:{settled:"Listed jobs",running:"Listing jobs"},peek:{settled:"Peeked at",running:"Peeking at"},cancel:{settled:"Cancelled job",running:"Cancelling job"}},network:{status:{settled:"Checked network status",running:"Checking network status"},ls:{settled:"Listed networks",running:"Listing networks"},show:{settled:"Viewed network",running:"Viewing network"},peers:{settled:"Listed network peers",running:"Listing network peers"},log:{settled:"Read network log",running:"Reading network log"},doctor:{settled:"Diagnosed network",running:"Diagnosing network"},init:{settled:"Created network",running:"Creating network"},invite:{settled:"Invited device",running:"Inviting device"},join:{settled:"Joined network",running:"Joining network"},member_rm:{settled:"Removed device",running:"Removing device"},disconnect:{settled:"Left network",running:"Leaving network"},panic:{settled:"Raised panic",running:"Raising panic"}},console:{list:{settled:"Listed consoles",running:"Listing consoles"},create:{settled:"Opened console",running:"Opening console"},status:{settled:"Checked console",running:"Checking console"},read:{settled:"Read console",running:"Reading console"},screenshot:{settled:"Captured console",running:"Capturing console"},input:{settled:"Typed in console",running:"Typing in console"},keys:{settled:"Sent keys",running:"Sending keys"},resize:{settled:"Resized console",running:"Resizing console"},secure:{settled:"Updated secure input",running:"Updating secure input"},close:{settled:"Closed console",running:"Closing console"}},lsp:{definitions:{settled:"Found definition",running:"Finding definition"},references:{settled:"Found references",running:"Finding references"},symbols:{settled:"Listed symbols",running:"Listing symbols"},rename_preview:{settled:"Previewed rename",running:"Previewing rename"}}};function Vl(e,t){const n=e.trim().toLowerCase(),s=(t??"").trim().toLowerCase(),r=s?Bi[n]?.[s]:void 0;if(r)return{...r,named:!0};const i=zl[n];return i?{...i,named:!0}:{settled:"Called",running:"Calling",named:!1}}function $h(e,t,n,s,r=""){const i=Vl(e,r),o=Bl(t,e)?n??"":t;return{verb:s?i.running:i.settled,object:i.named?o:[$i(e),o].filter(Boolean).join(" ")}}const Kl=new Set(["write","edit"]);function Wl(e){return Kl.has(e.trim().toLowerCase())}function Uh(e){return Wl(e.toolName)&&e.diff!==null&&!e.isError}function Zi(e){if(!e||typeof e!="object")return null;const t=e.diff;if(typeof t=="string")return t?t.split(`
|
|
6
|
+
`):null;if(!Array.isArray(t))return null;const n=t.filter(s=>typeof s=="string");return n.length?n:null}function Yl(e,t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Gi(e,t){return e===null||Yl(e,t)?t:e}function Hi(e,t){if(!e||typeof e!="object")return{added:t?.added??0,removed:t?.removed??0};const n=e;return{added:Ir(n.added),removed:Ir(n.removed)}}function Ql(e){return e.length>=2&&ls(e[0])==="---"&&ls(e[1])==="+++"?e.slice(2):e.slice()}const Xl=/\s+$/;function ls(e){return e.replace(Xl,"")}function Jl(e){const t=e.slice(0,1);return t==="@"?"hunk":t==="+"?"added":t==="-"?"removed":"context"}const ql=40;function Fh(e){const t=Ql(e),n=t.slice(0,ql);return{lines:n.map(s=>{const r=ls(s);return{text:r,marker:r.slice(0,1),kind:Jl(r)}}),hidden:t.length-n.length}}function Bh(e){return`… ${e} more diff line${e===1?"":"s"}`}const Be={records:[],index:new Map,generation:0,compacting:!1,compactingSince:0,viewEpoch:0,oldestId:null,hasMore:!1,argsByCall:new Map};function zi(e){return e==="skipped"||e==="aborted"}function Rr(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Ar(e,t,n,s){return Rr(n.args)??(s?.kind==="tool"?s.args:null)??Rr(e.argsByCall.get(t)?.arguments)}function Vi(e){return e?e.type==="image"||typeof e.attachment=="string"&&e.attachment?!0:typeof e.data=="string"&&e.data.length>0:!1}function nt(e){const t=e?.content;return Array.isArray(t)?t.filter(n=>n&&!Vi(n)).filter(n=>(n.type??"text")==="text").map(n=>n.text??"").join(""):""}function wn(e,t,n){const s=e?.content;if(!Array.isArray(s))return n?.length?n:Dt;const r=[];for(const i of s)Vi(i)&&r.push({id:`${t}:${r.length}`,data:typeof i.data=="string"&&i.data?i.data:null,attachment:typeof i.attachment=="string"&&i.attachment?i.attachment:null,mimeType:typeof i.mime_type=="string"&&i.mime_type?i.mime_type:"image/png"});return r.length===0?Dt:n&&Ki(n,r)?n:r}const Dt=[];function ed(e,t){return e.length===0&&t.length>0?t:e}function Ki(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n].id!==t[n].id||e[n].data!==t[n].data||e[n].attachment!==t[n].attachment||e[n].mimeType!==t[n].mimeType)return!1;return!0}function kt(e){const t=new Map;return e.forEach((n,s)=>t.set(n.id,s)),t}function td(e,t){return t&&(!e||t.epoch!==e.epoch||t.seq>=e.seq)?t:e}const nd=new Set;function Wi(e,t=nd){const n=o=>o.kind==="user"&&o.provisional===!0,s=e.map((o,c)=>({record:o,position:c})),r=s.reduce((o,c)=>n(c.record)&&c.position<o?c.position:o,Number.POSITIVE_INFINITY),i=o=>n(o.record)||o.position>r&&!t.has(o.record.id);return s.sort((o,c)=>{const l=i(o),d=i(c);return l!==d?l?1:-1:l?o.position-c.position:o.record.ts!==c.record.ts?o.record.ts-c.record.ts:o.position-c.position}).map(o=>o.record)}function ds(e,t){const n=e,s=t,r=Object.keys(n);if(r.length!==Object.keys(s).length)return!1;for(const i of r)if(n[i]!==s[i]){if(i==="images"){const o=n[i],c=s[i];if(Array.isArray(o)&&Array.isArray(c)&&Ki(o,c))continue}if(i==="frame"){const o=n[i],c=s[i];if(o!==void 0&&c!==void 0&&o.epoch===c.epoch&&o.seq===c.seq)continue}return!1}return!0}function ne(e,t){const n=e.index.get(t.id);if(n!==void 0){const i=e.records[n];if(ds(i,t))return e;const o=e.records.slice();return o[n]=t,{...e,records:o}}const s=[...e.records,t],r=new Map(e.index);return r.set(t.id,s.length-1),{...e,records:s,index:r}}function Ms(e,t){if(!e.records.some(t))return e;const n=e.records.filter(s=>!t(s));return{...e,records:n,index:kt(n)}}function Or(e,t){const n=`tool:${t}`,s=e.index.get(n);if(s===void 0)return e;const r=e.records[s];return r.kind==="tool"&&(r.phase==="composing"||r.phase==="queued")?Ms(e,i=>i.id===n):e}function sd(e,t,n){const s=e.index.get(`tool:${t}`);if(s===void 0)return e;const r=e.records[s];if(!(r.kind==="tool"&&(r.phase==="composing"||r.phase==="queued")))return e;const i=e.records.slice();return i[s]=n,{...e,records:i,index:kt(i)}}const rd=new Set(["frontend_state_checkpoint_v1","session_state","hub_communication","wake_schedule","prune"]);function Yi(e){const t=e.trim()||"compaction did not run";return{text:`Compaction did not run${t.includes(":")?" — ":": "}${t}`,level:t.startsWith("compaction failed")?"error":"warning"}}function id(e,t){const n=Ur(e),s=Ur(t);return n===s?`Context compacted to ${s} tokens`:`Context compacted, ${n} to ${s} tokens`}const Qi="Context compacted",od=12e4;function Xi(e){const t=[],n=[];for(const d of e)d.kind==="compaction"&&(d.id.startsWith("compaction:")?t.push(d):n.push(d));if(t.length===0||n.length===0)return e;const s=new Set,r=new Set,i=new Map,o=(d,u)=>{s.add(u.id),r.add(d.id),i.set(u.id,d.text)},c=[...t].sort((d,u)=>d.ts-u.ts);for(const d of c){if(d.before===void 0)continue;const u=n.find(f=>!s.has(f.id)&&f.before===d.before);u&&o(d,u)}const l=[];for(const d of c)if(!r.has(d.id))for(const u of n){if(u.before!==void 0)continue;const f=Math.abs(u.ts-d.ts);f>od||l.push({live:d,durable:u,distance:f})}l.sort((d,u)=>d.distance-u.distance);for(const{live:d,durable:u}of l)r.has(d.id)||s.has(u.id)||o(d,u);return r.size===0?e:e.filter(d=>!r.has(d.id)).map(d=>{const u=i.get(d.id);return u===void 0||d.kind!=="compaction"&&d.kind!=="notice"||u===d.text?d:{...d,text:u}})}function ad(e){const t=Xi(e.records);return t===e.records?e:{...e,records:t,index:kt(t)}}const cd="peer_message",ld="wake_prompt",dd="session_mcp_unavailable",ud=new Set(["session_mcp_recovery","session_model_switch","session_credential"]),fd=/^\[session incident(?:\s*\(([^)]*)\))?\]\s*([^:\n]{1,40}):\s*/,Pr=/^<\/?[a-z][a-z0-9-]*(\s[^>]*)?>$/i,pd=new Set(["this changes your instructions. apply it from now on, and drop work it makes pointless.","answer it now with the `hub` tool — a short, direct reply — then carry on with what you were doing. do not restructure your work around the question.","this is a note, not a question. no reply is needed unless it changes what you should do."]),Ji=/^\[[^\]]{1,32}\]\s*/,Sn="Reason:",hd=/[\n;,(]| [—–] /,md=/^\d+\.$/,gd=/[A-Z]/,yd=/\s/,Lt=160;function vd(e,t,n){if(e==="session_incident")return{level:"error",...kd(t,n)};let s;return e===dd?s=_d(t):ud.has(e)?s=wd(t.trim().replace(Ji,"")):s=Td(t),{level:"info",category:null,provider:null,...s}}function _d(e){const t=e.trim().replace(Ji,"").split(`
|
|
7
7
|
`).map(c=>c.trim()),n=t[0]??"",s=t[1]?.startsWith(Sn)?t[1]:null,r=t.slice(s?2:1).filter(Boolean).join(`
|
|
8
|
-
`),i=(s?`${n} ${s}`:n).trim();if(i.length<=Lt)return{headline:i,detail:r||null};const o=s===null?null:
|
|
9
|
-
`)||null,d=`${n} ${c(o.leading,o.clause)}`;if(d.length<=Lt)return{headline:d,detail:l(o.rest)};const u=`${n} ${c("",o.clause)}`;if(u.length<=Lt)return{headline:u,detail:l([o.leading,o.rest].filter(Boolean).join(" "))}}return{headline:
|
|
10
|
-
`)||null}}function
|
|
11
|
-
`),s=n[0].match(
|
|
12
|
-
`).trim();return{provider:(s?.[1]??"").trim()||null,category:(s?.[2]??"").trim()||null,headline:i,detail:o||null}}function
|
|
13
|
-
`).map(s=>s.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function
|
|
14
|
-
`).map(c=>c.trim()).filter(Boolean),n=c=>!Pr.test(c)&&!kd(c),s=t.find(n),r=t.find(c=>Pr.test(c)&&!c.startsWith("</"));let i=s??r??e.trim();const o=t.indexOf(i);if(o>=0&&i.endsWith(":")){const c=t.slice(o+1).find(n);c&&(i=`${i} ${c}`)}return Ji(i)}function kd(e){return dd.has(e.replace(/\s+/g," ").trim().toLowerCase())}function Ji(e){const t=e.trim();if(t.length<=Lt)return t;const n=t.slice(0,Lt),s=n.lastIndexOf(" ");return`${(s>0?n.slice(0,s):n).trimEnd()}…`}const Td="harness_injected",qi=e=>!e||typeof e!="object"?!1:e[Td]===!0;function Ed(e,t){const n=e.payload??{},s=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const o=t?.kind==="compaction"?t.text:Yi,c=n.tokens_before;return{kind:"compaction",id:e.id,ts:s,text:o,...typeof c=="number"?{before:c}:{}}}if(e.type==="message"&&n.custom_type==="compaction_refused"){const o=n.details??{},c=Wi(String(o.detail??""));return{kind:"notice",id:e.id,ts:s,text:c.text,level:c.level}}if(e.type==="custom"&&n.custom_type==="completion_attention"){const o=n.details??{};if(typeof o.anchor=="string"&&(o.kind==="error"||o.kind==="interrupted"))return{kind:"notice",id:o.anchor,ts:s,complete:!0,text:o.kind==="error"?"Stopped with an error":"Interrupted",level:o.kind==="error"?"error":"warning"}}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const o=String(n.custom_type??"");if(td.has(o))return null;const c=n.details??{};if(o===id){const{body:d,sender:u}=Il(c);return{kind:"peer",id:e.id,ts:s,body:d,sender:t?.kind==="peer"&&Sl(t.sender,u)?t.sender:u}}if(o===od){if(Cl(c))return null;const d=String(c.text??"");return d.trim()?{kind:"wake",id:e.id,ts:s,text:d}:null}const l=String(c.text??c.detail??"");return l.trim()?{kind:"custom",id:e.id,ts:s,customType:o,text:l,attribution:n.attribution??"system",...md(o,l,c)}:null}const i=String(n.role??"");if(i==="user"){if(qi(n.provider_payload))return null;const o=tt(n);return o.startsWith("Harness recovery notice:")?{kind:"notice",id:e.id,ts:s,text:o,level:"warning"}:{kind:"user",id:e.id,ts:s,text:o,images:wn(n,e.id,t?.kind==="user"?t.images:void 0)}}if(i==="assistant"){const o=Array.isArray(n.tool_calls)?n.tool_calls:[],c=tt(n);return!c&&o.length>0?{kind:"assistant",id:e.id,ts:s,text:"",streaming:!1,stopReason:String(n.stop_reason??"toolUse"),error:!1}:{kind:"assistant",id:e.id,ts:s,text:c,complete:!0,streaming:!1,stopReason:n.stop_reason??null,error:!!n.is_error}}if(i==="tool"){const o=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{},d=Hi(l.__fault);return{kind:"tool",id:`tool:${o}`,ts:s,toolCallId:o,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:tt(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:wn(n,`tool:${o}`,t?.kind==="tool"?t.images:void 0),...Gi(c.details,t?.kind==="tool"?t:null),diff:Zi(Bi(c.details),t?.kind==="tool"?t.diff:null),stopped:d}}return null}function xd(e,t){if(!e.cursor_missing||e.entries.length===0)return null;const n=e.entries[0]?.id;return typeof n!="string"||n===t?null:n}function Dr(e,t,n){if(!e.cursor_missing)return{cursor:null,failed:!1};const s=xd(e,t);return!n&&s!==null?{cursor:s,failed:!1}:{cursor:null,failed:!0}}function Rt(e,t,n={}){const s=n.keepPaging===!0&&e.viewEpoch>0,r=[];for(const h of t.entries){if(s&&!Bd(h,e.clearedAt))continue;const _=e.records[e.index.get(h.id)??-1]??e.records[e.index.get(`tool:${String(h.payload?.tool_call_id??"")}`)??-1],x=Ed(h,_);x&&r.push(x)}let i=e.argsByCall,o=!1;for(const h of t.entries){const _=h.payload?.tool_calls;if(!Array.isArray(_))continue;const x=Math.round((h.ts??0)*1e3);for(const I of _)!I||typeof I.id!="string"||i.has(I.id)||(o||(i=new Map(i),o=!0),i.set(I.id,{...I,anchoredAt:x}))}for(let h=0;h<r.length;h++){const _=r[h];if(_.kind!=="tool")continue;const x=i.get(_.toolCallId);if(!x)continue;const I=x.arguments??null;r[h]={..._,args:I,intent:typeof I?.i=="string"?I.i:null}}const c=o?e.records.map(h=>{if(h.kind!=="tool"||h.args)return h;const x=i.get(h.toolCallId)?.arguments??null;return x?{...h,args:x,intent:h.intent??(typeof x.i=="string"?x.i:null)}:h}):e.records,l=n.replace?Be:{...e,records:c},d=new Map(l.records.map(h=>[h.id,h]));let u=n.replace||!n.replace&&c!==e.records;for(const h of r){const _=d.get(h.id);if(!_){u=!0,d.set(h.id,h);continue}if(_.kind==="tool"&&h.kind==="tool"){const x={...h,args:h.args??_.args,intent:h.intent??_.intent,images:_.images.length?_.images:h.images};ds(_,x)||(u=!0,d.set(h.id,x));continue}ds(_,h)||(u=!0,d.set(h.id,h))}const f=e.compacting&&t.entries.some(h=>e.index.has(h.id)||Math.round((h.ts??0)*1e3)<e.compactingSince?!1:h.type==="compaction"||h.type==="message"&&h.payload?.custom_type==="compaction_refused");if(!u&&e.hasMore===t.has_more&&!f)return e;const p=Qi(Ki([...d.values()],new Set(r.map(h=>h.id)))),w=t.entries[0];let E=l.oldestId;if(n.keepPaging)return{...e,records:p,index:kt(p),argsByCall:i};if(w){const h=Math.round((w.ts??0)*1e3),_=E?l.records[l.index.get(E)??-1]:void 0;(!_||h<=_.ts)&&(E=w.id)}return{...e,records:p,index:kt(p),oldestId:E,hasMore:t.has_more,argsByCall:i,compacting:f?!1:e.compacting,compactingSince:f?0:e.compactingSince}}const Zn={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0};function us(e,t,n=Date.now(),s={}){const r=t.message,i=s.frame;switch(t.type){case"agent_start":{const o=Number(t.generation??e.generation+1);return o===e.generation?e:{...e,generation:o,compacting:!1,compactingSince:0}}case"compaction_start":return e.compacting?e:{...e,compacting:!0,compactingSince:n};case"agent_end":{if(Number(t.generation??e.generation)<e.generation)return e;let c=e;for(const l of e.records)if(l.kind==="assistant"&&l.streaming&&(c=ne(c,{...l,streaming:!1,settledAt:n,stopReason:t.aborted?"aborted":l.stopReason})),l.kind==="tool"&&l.phase!=="done"){const d=l.phase==="composing"||l.phase==="queued";c=ne(c,{...l,phase:"done",startedAt:null,stopped:!!t.aborted||d,neverSent:l.neverSent||d})}return c}case"message_start":{if(!r||typeof r.id!="string")return e;const o=e.records[e.index.get(r.id)??-1];if(r.role==="user"){if(qi(r.provider_payload))return e;const c=o?.kind==="user"&&o.provisional===!0;return ne(e,{kind:"user",id:r.id,ts:c?Us(e,n):n,text:tt(r),images:wn(r,r.id,o?.kind==="user"?o.images:void 0),...c?{provisional:!0}:{}})}return r.role!=="assistant"||o?e:ne(e,{kind:"assistant",id:r.id,ts:n,text:"",streaming:!0,...i?{frame:i}:{},stopReason:null,error:!1})}case"message_update":{if(!r||typeof r.id!="string")return e;const o=e.index.get(r.id),c=String(t.delta??""),l=tt(r);if(o===void 0)return!l&&!c?e:ne(e,{kind:"assistant",id:r.id,ts:n,text:l?l+c:c,streaming:!0,truncated:l===""?"prefix":void 0,...i?{frame:i}:{},stopReason:null,error:!1});const d=e.records[o];if(d.kind!=="assistant")return e;if(!d.streaming)return Zn.settledAssistantUpdate+=1,e;if(s.seed!==!0&&i&&d.frame&&i.epoch===d.frame.epoch&&i.seq<=d.frame.seq)return Zn.staleUpdateFrameDropped+=1,e;const u=Jl(d.frame,i);if(s.seed===!0&&!l)return!d.text&&!c?e:(Zn.seededDeltaWithheld+=d.text?1:0,ne(e,{...d,text:d.text||c,...u?{frame:u}:{},truncated:d.text?"interrupted":"prefix"}));let f;if(l){if(f=l+c,f.length<=d.text.length)return e}else{if(!c)return e;f=d.text+c}return ne(e,{...d,text:f,...u?{frame:u}:{},truncated:l?void 0:d.truncated})}case"message_end":{if(!r||typeof r.id!="string"||r.role!=="assistant")return e;const o=e.index.get(r.id),c=tt(r),l=o===void 0?void 0:e.records[o],d={kind:"assistant",id:r.id,ts:o===void 0?n:e.records[o].ts,text:c,streaming:!1,settledAt:l?.kind==="assistant"&&l.settledAt!==void 0?l.settledAt:n,stopReason:r.stop_reason??null,error:!!r.is_error};return ne(e,d)}case"history_delta":{const c={entries:(Array.isArray(t.messages)?t.messages:[]).map(l=>({id:String(l.id??""),ts:n/1e3,type:"message",payload:{kind:l.custom_type?"custom":"message",...l}})),has_more:e.hasMore};return Rt(e,c,{replace:t.reset===!0})}case"tool_call_compose":{const o=String(t.tool_call_id??"");if(!o)return e;const c=String(t.supersedes_tool_call_id??""),l=`tool:${o}`,d=e.records[e.index.get(l)??-1],u=c?e.records[e.index.get(`tool:${c}`)??-1]:void 0,f=d?.kind==="tool"?d:u?.kind==="tool"?u:void 0;if(f&&f.phase!=="composing"&&f.phase!=="queued")return c&&d?.kind==="tool"?Or(e,c):e;const w=String(t.not_run_reason??"").trim()||null,E=String(t.not_run_kind??"").trim()||null,h=Number(t.argument_bytes??0),_={kind:"tool",id:l,ts:f?.ts??n,toolCallId:o,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:w?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:h>0?h:f?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:Dt,added:0,removed:0,diff:null,stopped:!1,notRunReason:w,notRunKind:w?E:null,neverSent:w!==null};return c&&u?.kind==="tool"&&d?.kind!=="tool"?ed(e,c,_):ne(c&&d?.kind==="tool"?Or(e,c):e,_)}case"tool_execution_start":{const o=String(t.tool_call_id??"");if(!o)return e;const c=`tool:${o}`,l=e.records[e.index.get(c)??-1];if(l&&l.kind==="tool"&&l.phase==="done"&&!l.notRunReason)return e;const d=Ar(e,o,t,l),u=d&&!e.argsByCall.has(o)?new Map(e.argsByCall).set(o,{arguments:d,anchoredAt:Nt(t)??n}):e.argsByCall,f=u===e.argsByCall?e:{...e,argsByCall:u};return ne(f,{kind:"tool",id:c,ts:l?.ts??n,toolCallId:o,toolName:String(t.tool_name??""),intent:t.intent??(typeof d?.i=="string"?d.i:null),args:d,phase:"running",notRunReason:null,notRunKind:null,neverSent:!1,argumentBytes:0,output:null,isError:!1,durationS:null,startedAt:Nt(t)??(l?.kind==="tool"&&l.startedAt!==null?l.startedAt:n),endedAt:null,images:l?.kind==="tool"?l.images:Dt,added:0,removed:0,diff:l?.kind==="tool"?l.diff:null,stopped:!1})}case"tool_execution_end":{const o=String(t.tool_call_id??"");if(!o)return e;const c=`tool:${o}`,l=e.records[e.index.get(c)??-1],d=t.result??{},u=Ar(e,o,t,l),f=l&&l.kind==="tool"?l:{kind:"tool",id:c,ts:n,toolCallId:o,toolName:String(t.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:Dt,added:0,removed:0,diff:null,stopped:!1},p=u&&!e.argsByCall.has(o)?new Map(e.argsByCall).set(o,{arguments:u,anchoredAt:Nt(t)??n}):e.argsByCall,w=p===e.argsByCall?e:{...e,argsByCall:p},E=s.userStoppedAt??null,h=!!(t.is_error??d.is_error),_=Hi(d.details?.__fault),x=E!==null&&(typeof f.startedAt=="number"?f.startedAt<=E:h);return ne(w,{...f,args:u,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:tt(d)||null,isError:x||_?!1:h,durationS:typeof t.duration_s=="number"?t.duration_s:null,endedAt:typeof t.duration_s=="number"&&typeof f.startedAt=="number"?f.startedAt+t.duration_s*1e3:null,startedAt:null,images:Xl(wn(d,c,f.images),f.images),...Gi(d.details,f),diff:Zi(Bi(d.details),f.diff),stopped:f.stopped||x||_})}case"notice":{const o=String(t.text??"");if(!o)return e;const c=`notice:${e.generation}:${o}`;return e.index.has(c)?e:ne(e,{kind:"notice",id:c,ts:n,text:o,level:t.kind??"info"})}case"compaction_end":{const o=Number(t.tokens_before??0),c=Number(t.tokens_after??0),d=!!t.success?null:Wi(String(t.detail??"")),u=d?d.text:o&&c?nd(o,c):Yi,f=`compaction:${e.generation}:${o}:${c}`,p=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return p.index.has(f)?p:d?ne(p,{kind:"notice",id:f,ts:n,text:u,level:d.level}):rd(ne(p,{kind:"compaction",id:f,ts:n,text:u,before:o}))}case"retry_start":{const o=`Retrying after an error (attempt ${String(t.attempt??"?")})${t.fallback_model?`, falling back to ${String(t.fallback_model)}`:""}`,c=`retry:${e.generation}:${String(t.attempt??"")}`;return e.index.has(c)?e:ne(e,{kind:"notice",id:c,ts:n,text:o,level:"warning"})}case"subagent_end":{const o=`subagent:${String(t.job_id??"")}`,c=String(t.status??""),l=`${String(t.label??"Subagent")} ${c||"finished"}`,d=e.records[e.index.get(o)??-1];return d&&d.kind==="notice"&&d.text===l?e:ne(e,{kind:"notice",id:o,ts:d?.ts??n,text:l,level:c==="failed"?"error":"info"})}default:return e}}function Nt(e){return ul(e.started_at_epoch)}function eo(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function Id(e){const t=eo(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function Cd(e,t){const n=Nt(e);if(n!==null)return n;const s=eo(e);if(!s)return null;const r=t.argsByCall.get(s)?.anchoredAt;return typeof r=="number"&&Number.isFinite(r)&&r>0?r:null}function js(e){return e.type!=="tool_call_compose"?!1:typeof e.not_run_reason=="string"&&e.not_run_reason.trim().length>0?!0:e.dictation_complete===!0}function Cn(e){return e.type==="tool_execution_end"}function Rd(e,t,n=Date.now(),s=null){let r=e;t.streaming&&t.generation>r.generation&&(r={...r,generation:t.generation}),r.compacting&&(r={...r,compacting:!1,compactingSince:0});const i=t.streaming===!0;let o=!1;const c=new Set;for(const d of t.live_events??[]){const u=d;let f=n;const p=Id(u);if(p!==null&&!r.index.has(p)){const w=Cd(u,r);if(w!==null)f=w,o=!0,c.add(p);else if(Cn(u)||js(u)||!i)continue}r=us(r,u,f,{seed:!0,...s?{frame:s}:{}})}if(!o)return r;const l=Ki(r.records,c);return{...r,records:l,index:kt(l)}}function Lr(e){const t=new Map;for(const n of e??[]){if(!n)continue;const s=n;if(!Cn(s)&&!js(s))continue;const r=String(s.tool_call_id??"");if(!r)continue;const i=Nt(s);i!==null&&t.set(r,i)}return t}function Ad(e){const t=new Set;for(const n of e??[]){if(!n)continue;const s=n;if(s.type!=="tool_call_compose")continue;const r=s.not_run_reason;if(typeof r=="string"&&r.trim().length>0)continue;const i=String(s.tool_call_id??"");i&&t.add(i)}return t}const Od=5e3;function Pd(e,t){const n=new Set(t),s=new Map;if(n.size===0)return s;for(const r of e){if(r.payload?.role!=="tool")continue;const i=r.payload.tool_call_id;if(typeof i!="string"||!n.has(i))continue;const o=r.ts;typeof o!="number"||!Number.isFinite(o)||s.set(i,Math.round(o*1e3))}return s}function Dd(e,t,n,s=new Map,r=new Set){const i=e[0]?.ts;if(typeof i!="number"||!Number.isFinite(i))return!1;let o=null;for(const l of t){const d=n.get(l);if(d===void 0){if(r.has(l))continue;return!1}(o===null||d<o)&&(o=d)}for(const l of s.values())(o===null||l<o)&&(o=l);return o===null?!1:Math.round(i*1e3)<=o-Od}function Nr(e,t){const n=[];for(const s of e??[]){if(!s)continue;const r=s;if(!Cn(r)&&!js(r))continue;const i=String(r.tool_call_id??"");!i||n.includes(i)||t.has(i)||n.push(i)}return n}function Mr(e,t,n,s){const r=[],i=new Set;for(const o of t)i.has(o)||(i.add(o),!n.has(o)&&((e.get(o)??0)>=s||r.push(o)));return r}const Ld=3.25,fs=100,$s=500;function jr(e){return e<=0?fs:Math.min($s,fs+Math.ceil(Ld*e))}function Gn(e,t){const n=[];if(t.size===0)return n;for(const s of e){const r=s.payload?.tool_calls;if(Array.isArray(r))for(const i of r)i&&typeof i.id=="string"&&t.has(i.id)&&n.push(i.id)}return n}function Nd(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function Md(e,t){const n=new Set(t);for(const i of e){const o=i.payload?.tool_calls;if(Array.isArray(o))for(const c of o)c&&typeof c.id=="string"&&n.add(c.id)}const s=[],r=new Set;for(const i of e){if(i.payload?.role!=="tool")continue;const o=i.payload.tool_call_id;typeof o!="string"||n.has(o)||r.has(o)||(r.add(o),s.push(o))}return s}function jd(e,t){return e&&t===0}function $d(e){const t=new Set;for(const n of e??[]){if(!n)continue;const s=n,r=s.not_run_reason,i=s.type==="tool_call_compose"&&typeof r=="string"&&r.trim().length>0;if(s.type!=="tool_execution_start"&&!Cn(s)&&!i)continue;const o=String(s.tool_call_id??"");o&&t.add(o)}return t}function to(e,t,n){const s=new Set(e),r=[];for(const i of t)!s.has(i)&&!n.has(i)&&r.push(i);for(const i of e){if(n.has(i))return r;t.has(i)&&r.push(i)}return r}function Ud(e,t,n){return to(e,t,n).length}function $r(e){let t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;for(const n of e.records)n.kind!=="assistant"||!n.streaming||n.truncated||(t=ne(t,{...n,truncated:"interrupted"}));return t}function Fd(e,t=Date.now()){return e.records.length===0?e:{...Be,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function Bd(e,t){return e.type==="compaction"||e.type==="message"&&e.payload?.custom_type==="compaction_refused"?t===void 0?!0:Math.round((e.ts??0)*1e3)>=t:!1}function Ur(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function Zd(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return Ms(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function Us(e,t){let n=t;for(const s of e.records)s.ts>n&&(n=s.ts);return n}function no(e,t,n,s,r=Date.now()){return e.index.has(t)?e:ne(e,{kind:"user",id:t,ts:Us(e,r),text:n,images:s,local:!0,provisional:!0})}function Gd(e,t){return Ms(e,n=>n.id===t)}let Fr=0;function Hd(e,t,n,s=Date.now()){return Fr+=1,ne(e,{kind:"notice",id:`local:${s}:${Fr}`,ts:Us(e,s),text:t,level:n})}function $h(e,t,n,s){const r=t?.anchor_id,i=t?.kind;return!r||i!=="error"&&i!=="interrupted"||n||e.index.has(r)||!t?.unseen&&!s?.has(r)?e:(s?.add(r),ne(e,{kind:"notice",id:r,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:i==="error"?"Stopped with an error":"Interrupted",level:i==="error"?"error":"warning"}))}const Vd="compacting context…";function Uh(e){return typeof e=="string"&&e.trim()===Vd}const zd=[1500,5e3];async function Fh(e,t=n=>new Promise(s=>setTimeout(s,n))){for(const n of zd){await t(n);try{if(await e())return}catch{}}}function Kd(e,t){return e.some(n=>Math.round((n.ts??0)*1e3)<t?!1:n.type==="compaction"||n.type==="message"&&n.payload?.custom_type==="compaction_refused")}const Br=new Set(["openrouter","radient","radient-key"]),Wd=new Set(["auto","openrouter/auto"]),Yd="Auto";function so(e){return e.slice(e.lastIndexOf("/")+1)||e}function Qd(e,t){return e===t||e===so(t)}function Hn(e){if(!e)return null;const t=typeof e.provider=="string"?e.provider:"";if(!t)return null;const n=typeof e.model_id=="string"?e.model_id:"";return n?`${t}/${n}`:null}function Bh(e){if(!e||typeof e.model_id!="string"||!e.model_id)return null;const t=typeof e.provider=="string"?e.provider:"",n=t?`${t}/${e.model_id}`:e.model_id,s=typeof e.display_name=="string"?e.display_name.trim():"",r=Br.has(t)||!s||Qd(s,e.model_id)||s.toLowerCase()==="unknown";return{name:Br.has(t)&&Wd.has(e.model_id)?Yd:r?so(n):s,selector:n}}function Zh(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function Gh(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function Hh(e){if(!e)return null;for(const t of[e.reasoning_effort,e.reasoning_default_effort])if(typeof t=="string"&&t.trim())return t.trim().toLowerCase();return null}function Vh(e){const t=e.trim();return t&&({auto:"Auto",none:"None",minimal:"Minimal",low:"Low",medium:"Medium",high:"High",xhigh:"xHigh",max:"Max"}[t.toLowerCase()]??t)}function ro(e){if(!e)return!1;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim():"",n=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim():"";return typeof e.model_id=="string"&&e.model_id!==""&&!t&&!n&&!e.reasoning&&Array.isArray(e.reasoning_efforts)&&e.reasoning_efforts.length===0&&typeof e.display_name=="string"&&e.display_name.trim()===""}function zh(e,t){const n=(e??t)?.effective_model;return ro(n)?null:n?.model_id??null}function Kh(e){if(!e)return null;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim().toLowerCase():"",n=Array.isArray(e.reasoning_efforts)?e.reasoning_efforts.filter(i=>typeof i=="string"):null,s=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",r=ro(e);return t?{label:t,adjustable:n===null||n.length>0,knownLadder:!!(n&&n.length>0),levelKnown:!0,detail:n&&n.length>0?`Reasoning effort. This model offers ${n.join(", ")}.`:"Reasoning effort for this session."}:n&&n.length>0?{label:"auto",adjustable:!0,knownLadder:!0,levelKnown:!0,detail:`No level is set, so this model runs at its own default${s?` (${s})`:""}. It offers ${n.join(", ")}.`}:r?{label:"unknown",adjustable:!0,knownLadder:!1,levelKnown:!1,detail:"This session has not reported its reasoning effort yet. It appears after the next turn, or run /effort <level> to set one now."}:n&&e.reasoning?{label:"reasoning",adjustable:!1,knownLadder:!0,levelKnown:!0,detail:"This model reasons, but exposes no effort levels to choose between."}:n===null&&s?{label:s,adjustable:!1,knownLadder:!1,levelKnown:!0,detail:"The level this model runs at by default. This backend does not report which other levels it accepts."}:null}function Wh(e,t){if(!e)return null;if(!t||t.length===0||e.knownLadder)return e;const n=t.map(s=>typeof s=="object"&&s!==null&&"value"in s?String(s.value):"").filter(Boolean);return n.length===0?e:{...e,adjustable:!0,detail:`Reasoning effort. This model offers ${n.join(", ")}.`}}function Xd(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function Jd(e,t){return!!e.streams[t]}function io(e,t){return e.attached[t]?.turns.at(-1)}function Yh(e,t){const n=io(e,t);return n?e.streams[n.asideId]:void 0}function Qh(e,t){const n=e.attached[t]?.turns??[];for(let s=n.length-1;s>=0;s-=1){const r=n[s];if(r&&e.streams[r.asideId]?.settled)return r.asideId}}function qd(){return{text:"",streaming:!0,settled:!1,error:null}}function eu(e){return{text:e,streaming:!1,settled:!0,error:null}}function tu(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const nu=As(e=>({streams:{},attached:{},attachAside:t=>e(n=>{const s=n.attached[t];return s&&s.notice===null?n:{attached:{...n.attached,[t]:s?{...s,notice:null}:{turns:[],notice:null}}}}),beginAsk:(t,n,s)=>e(r=>({streams:{...r.streams,[n]:qd()},attached:{...r.attached,[t]:{turns:[...r.attached[t]?.turns??[],{asideId:n,question:s}],notice:null}}})),applyAsideDelta:(t,n)=>e(s=>{const r=Xd(s.streams[t],n);return r?{streams:{...s.streams,[t]:r}}:s}),settleAside:(t,n)=>e(s=>s.streams[t]?{streams:{...s.streams,[t]:eu(n)}}:s),failAside:(t,n)=>e(s=>Jd(s,t)?{streams:{...s.streams,[t]:tu(s.streams[t],n)}}:s),setAsideNotice:(t,n)=>e(s=>{const r=s.attached[t];return r?{attached:{...s.attached,[t]:{...r,notice:n}}}:s}),detachAside:t=>e(n=>{const s=n.attached[t],r={...n.attached};if(delete r[t],!s)return{attached:r};const i={...n.streams};for(const o of s.turns)delete i[o.asideId];return{streams:i,attached:r}})}));function Xh(e,t){return io(e,t)?.asideId}const su=4*1024*1024,ru=1024*1024,Re=new Map;function Zr(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function iu(e){const t=e.slice(-200);let n=0,s=Zr(t);for(;n<t.length&&s>ru;)n+=1,s=Zr(t.slice(n));return{records:t.slice(n),bytes:s}}function ou(e,t){const{records:n,bytes:s}=iu(Zd(t.transcript).records);if(n.length===0){Re.delete(e);return}const i={transcript:{...t.transcript,records:n,index:new Map(n.map((o,c)=>[o.id,c])),oldestId:null,hasMore:!1,argsByCall:new Map},savedAt:Date.now(),bytes:s,owedLabels:Gr(n,t.owedLabels),markLabels:Gr(n,t.markLabels)};Re.delete(e),Re.set(e,i),cu()}function Gr(e,t){if(!t||t.size===0)return Hr;const n=new Set;for(const s of e)s.kind!=="tool"||s.args||s.toolCallId&&t.has(s.toolCallId)&&n.add(s.toolCallId);return n.size>0?n:Hr}const Hr=new Set;function oo(e){const t=Re.get(e);if(!t)return null;const{bytes:n,...s}=t;return s}function au(e){Re.delete(e)}function cu(){let e=0;for(const t of Re.values())e+=t.bytes;for(;e>su&&Re.size>0;){const t=Re.keys().next().value;if(t===void 0)break;const n=Re.get(t);Re.delete(t),e-=n?.bytes??0}}const lu=8,du=128,ao=new Set,uu="",Ne=new Map,Fs=e=>e??uu;function Jh(e){return Ne.get(Fs(e))??ao}function qh(e,t,n){const s=Fs(e),r=Ne.get(s)??new Set,i=new Set(r);if(n)for(i.delete(t),i.add(t);i.size>du;){const o=i.values().next().value;if(o===void 0)break;i.delete(o)}else i.delete(t);for(Ne.delete(s),i.size>0&&Ne.set(s,i);Ne.size>lu;){const o=Ne.keys().next().value;if(o===void 0)break;Ne.delete(o)}return Ne.get(s)??ao}function fu(e){Ne.delete(Fs(e))}const pu=new Set(["subagent_start","subagent_progress","subagent_end"]),hu=(e,t)=>({...e,[t]:(e[t]??0)+1}),mu=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const s=co(n);s&&(t[s]=(t[s]??0)+1)}return t},co=e=>{if(!e||typeof e!="object")return null;const t=e;return pu.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},gu=(e,t)=>{const n=co(t);return n?hu(e,n):e};function yu(e){for(const t of e)t.type==="aside_delta"&&nu.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function vu(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const et=new Set,At=new Set;function _u(e,t){let n=null;for(const s of t)e.has(s)&&(n=n??new Set(e),n.delete(s));return n??e}const bu=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),wu=15e3,ps=[500,1e3,2e3,4e3,8e3,8e3],Su=ps.length,ku=2e4,Tu=1e4;function Vr(e){const t=Math.max(1,Math.min(e,ps.length));return ps[t-1]??8e3}const Eu=3,xu=250,zr=512,Kr=new Set(["turn_end","agent_end"]),Wr=2,Iu=500,Yr=$s,Cu=6,Vn=Ai("sessions.history"),Ru=2e3,Qr={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},st=new Map,ln=new Map,Au=8,Ou=2048,Xr=1024,Pu=1024,Du="",qe=new Map;function Jr(e){const t=e??Du,n=qe.get(t);if(n)return qe.delete(t),qe.set(t,n),n;const s={attempts:new Map,painted:new Set,inFlight:new Set,refused:!1,depth:0,order:[],starts:new Map,waiting:new Set,settled:new Set,settleRows:0};for(qe.set(t,s);qe.size>Au;){const r=qe.keys().next().value;if(r===void 0||r===t)break;qe.delete(r)}return s}function zn(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function Kn(e,t,n,s){return t.has(n)?!1:e.inFlight.has(n)?!0:s}function Lu(e,t){return ln.set(e,t),()=>{ln.get(e)===t&&ln.delete(e)}}function em(e){const t=ln.get(e);return t?(t(),!0):!1}const se=new Map,Nu=4,Mu=16;function lo(e,t){e(n=>no(n,t.id,t.text,t.images)),t.painted||(t.painted=!0,t.onPainted?.())}function ju(e,t,n){const s=e.index.get(t),r=s===void 0?void 0:e.records[s];if(s===void 0||!r||r.kind!=="user"||!r.local||r.text===n)return e;const i=e.records.slice();return i[s]={...r,text:n},{...e,records:i}}function hs(e,t){let n=se.get(e);if(!n){if(se.size>=Mu){const i=se.keys().next();i.done||se.delete(i.value)}n=new Map,se.set(e,n)}const s={identity:e,id:t.id,text:t.text,images:t.images,onPainted:t.onPainted,settled:t.settled,submittedAt:t.submittedAt};for(n.set(s.id,s);n.size>Nu;){const i=n.keys().next();if(i.done)break;n.delete(i.value)}const r=st.get(e);r&&lo(r,s)}function tm(e){if(!e)return null;const t=se.get(e);if(!t)return null;for(const n of t.values())if(!n.settled)return n;return null}function ms(e,t){const n=se.get(e);n&&(n.delete(t),n.size===0&&se.delete(e))}function gs(e,t){const n=se.get(e)?.get(t);n&&(n.settled=!0)}function qr(e,t){return e?se.get(e)?.has(t)===!0:!1}function nm(e){return e?(se.get(e)?.size??0)>0:!1}function $u(e,t,n){const s=se.get(e)?.get(t);if(!s)return;s.text=n;const r=st.get(e);r&&r(i=>ju(i,t,n))}function Uu(e,t){if(e===t)return;const n=se.get(e);if(!n)return;se.delete(e);const s=se.get(t)??new Map;for(const[r,i]of n)i.identity=t,s.set(r,i);se.set(t,s)}function on(e){se.delete(e)}function Fu(e,t){const n=se.get(e);if(n)for(const s of[...n.keys()]){const r=t.index.get(s),i=r===void 0?void 0:t.records[r];i?.kind==="user"&&i.local!==!0&&ms(e,s)}}function Bu(e,t){st.set(e,t);const n=se.get(e);if(n)for(const s of n.values())lo(t,s);return()=>{st.get(e)===t&&st.delete(e)}}function Zu(e,t){const n=se.get(e);if(!n)return t;let s=t;for(const r of n.values())s=no(s,r.id,r.text,r.images);return s}function Gu(e,t,n){return e===t?!0:!n}function sm(e,t){const n=st.get(e);if(!n)return ms(e,t),"queued";let s="queued";return n(r=>{const i=r.records[r.index.get(t)??-1];return!i||i.kind!=="user"?r:i.local?(s="retracted",Gd(r,t)):(s="owner",r)}),ms(e,t),s}function Hu(e,t){const n=st.get(e);if(!n)return"unseen";let s="unseen";return n(r=>{const i=r.records[r.index.get(t)??-1];return!i||i.kind!=="user"||(s=i.local?"local":"owner"),r}),s}function Vu(e){const t=oo(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:Be,stale:!1,owedLabels:et,markLabels:At}}function zu(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function rm(e,t,n=!0,s=e){const[r,i]=T.useState(()=>{const k=t&&e?Vu(e):null;return{status:"connecting",frontend:null,heldFrontend:null,pendingModel:null,history:null,cold:!1,subscriptionId:null,ownerEpoch:null,receipt:null,terminal:null,turnsCompleted:0,failure:null,transcript:s?Zu(s,k?.transcript??Be):Be,stale:k?.stale??!1,missing:!1,loadingOlder:!1,subagentPulses:{},labelPending:k?.owedLabels??et,labelMarked:k?.markLabels??At,labelHoldLate:!1,hydrated:!1}}),o=T.useRef(r),c=T.useCallback(k=>{const P=k(o.current);return P===o.current||(o.current=P,i(P)),P},[]),l=T.useRef(e),d=T.useRef([]),u=T.useRef(Be.index),f=T.useRef(Jr(e)),p=T.useRef(new Set),w=T.useRef(null),E=T.useRef({}),h=T.useRef(null),_=T.useRef(0);T.useEffect(()=>{if(!e||!t)return;const k=++_.current;let P=null,U=!1,te=0,W=0,me=0,ie=0,Ke=0,Tt=0,We=0,Pn=!1;const Xt=()=>{Tt&&(window.clearTimeout(Tt),Tt=0)},Bo=j=>{for(const F of j)f.current.attempts.set(F,(f.current.attempts.get(F)??0)+1)},Dn=j=>{c(F=>{const Z=new Set;for(const J of F.labelPending)F.labelPending.has(J)&&(Kn(f.current,F.transcript.argsByCall,J,zn(F))||Z.add(J));let G=null;for(const J of F.labelMarked)Kn(f.current,F.transcript.argsByCall,J,zn(F))||(G=G??new Set(F.labelMarked),G.delete(J));if(Z.size===0&&!G)return F;const oe=new Set(F.labelPending);for(const J of Z)oe.delete(J);return{...F,labelPending:oe.size?oe:et,labelMarked:G&&G.size===0?At:G??F.labelMarked}})},Zo=j=>{c(F=>{let Z=null,G=null;for(const oe of j)F.labelPending.has(oe)&&(Z=Z??new Set(F.labelPending),Z.delete(oe),G=G??new Set(F.labelMarked),G.add(oe));return!Z||!G?F:{...F,labelPending:Z.size?Z:et,labelMarked:G}})},Ln=async(j,F,Z=Qr,G=1,oe)=>{for(const ve of Z.targets)f.current.inFlight.add(ve),p.current.add(ve);let J=!1;try{J=await Go(j,F,Z,G,oe)}finally{if(!J){for(const ve of Z.targets)f.current.inFlight.delete(ve);f.current.refused&&Zo(Z.targets),Dn()}}},Go=async(j,F,Z,G,oe)=>{const J=new Set;let ve,lt=0,dt=0,Ye=!1,ut=!1;const xe=new Set(Z.found),Qe=()=>Ud(Z.order,Z.targets,xe),ft=()=>to(Z.order,Z.targets,xe),Xe=()=>{const K=new Map;for(const L of v){if(xe.has(L))continue;const de=g.get(L);de!==void 0&&K.set(L,de)}return K},Ue=new Set(Z.every);for(const K of xe)Ue.add(K);const v=new Set,g=new Map;let q=1;const fe=Z.targets.size>0;let pt=Math.max(jr(Qe()),fe?f.current.depth:0),$=0;for(;lt<Yr&&dt<Cu;){dt+=1;let K;try{K=await ce({op:"sessions.history",sessionId:e,...ve?{beforeId:ve}:{},limit:Math.min(pt,Yr-lt)})}catch{if(o.current.transcript.records.length>0){if($++>0)return f.current.refused=!0,!1;continue}return G<Eu?(Ke=window.setTimeout(()=>{if(Ke=0,_.current!==j){Dn();return}Ln(j,F,Z,G+1,oe)},Vr(G)),!0):(c(ee=>({...ee,status:"unavailable",failure:nl,heldFrontend:null})),!1)}finally{Dn()}if(_.current!==j)return!1;f.current.refused=!1;const L=K.entries[0];lt+=K.entries.length,oe?.(K.entries.length),c(ee=>{const Ie=Rt(ee.transcript,K),ht=Gn(K.entries,Ue),Mn=new Set(ee.labelPending);for(const zo of ht)Mn.delete(zo);return{...ee,hydrated:!0,labelPending:Mn.size?Mn:et,labelMarked:_u(ee.labelMarked,ht),transcript:Ie}}),e&&ve===void 0&&Ze.getState().resolveHeldFromServer(e,K.entries.map(ee=>ee.id),!K.cursor_missing);const de=Qe();for(const ee of Gn(K.entries,Ue))xe.add(ee),Ue.add(ee);if(Nd(K.entries)&&(ut=!0),fe){const ee=Md(K.entries,Ue);for(const Ie of ee)v.add(Ie),Ue.add(Ie);for(const[Ie,ht]of Pd(K.entries,ee))g.set(Ie,ht);for(const Ie of[...v])xe.has(Ie)&&v.delete(Ie);v.size>0&&q--<=0&&v.clear()}Ye=Ye||F.size===0||K.entries.some(ee=>F.has(ee.id)||J.has(ee.id));for(const ee of K.entries)J.add(ee.id);const Fe=Qe()+v.size;if(fe&&Qe()<de&&(f.current.depth=Math.min($s,Math.max(f.current.depth,lt))),fe){const ee=ft();if(Dd(K.entries,ee,Z.starts,Xe(),new Set(ee.filter(ht=>Z.waiting.has(ht))))||ut)return!1}if(jd(Ye,Fe)||!L||!K.has_more)return!1;ve=L.id,pt=Fe>0?jr(Fe):fs}return!1},Ks=()=>{if(te&&cancelAnimationFrame(te),W&&clearTimeout(W),te=0,W=0,_.current!==k)return;const j=d.current;if(d.current=[],j.length===0)return;yu(j);const F=v=>{const q=v.payload.history.entries.at(-1);return q?zu(v.payload)?!0:q.id===v.payload.frontend.snapshot.history_cursor?!1:u.current.has(q.id):!1},Z=v=>v!=null&&u.current.has(v),G=j.some(v=>v.type==="attention"?!Z(v.payload.anchor_id):v.type==="snapshot"&&!F(v)),oe=new Set(o.current.transcript.argsByCall.keys()),J=[],ve=new Set;for(const v of j)if(v.type==="snapshot"){for(const g of v.payload.history.entries){ve.add(g.id);const q=g.payload?.tool_calls;if(Array.isArray(q))for(const fe of q)fe&&typeof fe.id=="string"&&oe.add(fe.id)}for(const g of v.payload.frontend.snapshot.live_events??[]){const q=g.message;typeof q?.id=="string"&&ve.add(q.id)}J.push(...v.payload.frontend.snapshot.live_events??[])}const lt=j.some(v=>v.type==="event"&&Kr.has(String(v.payload.type??""))),dt=Mr(f.current.attempts,Nr(J,oe),oe,Wr),Ye=lt?Mr(f.current.attempts,[...f.current.attempts.keys(),...f.current.settled],oe,Wr):[],ut=[];for(const v of j){if(v.type!=="event")continue;const g=v.payload;String(g.type??"")==="tool_execution_end"&&String(g.tool_call_id??"")&&ut.push(g)}const xe=[];for(const v of ut){const g=String(v.tool_call_id??"");oe.has(g)||f.current.settled.has(g)||xe.push(g)}for(const v of xe)f.current.settled.add(v);for(;f.current.settled.size>zr;){const v=f.current.settled.values().next().value;if(v===void 0)break;f.current.settled.delete(v)}for(const[v,g]of Lr(ut))f.current.starts.set(v,g);for(;f.current.starts.size>Xr;){const v=f.current.starts.keys().next().value;if(v===void 0)break;f.current.starts.delete(v)}const Qe=f.current.settleRows<Iu?xe:[],ft=[...new Set([...dt,...Ye,...Qe])],Xe=ft.filter(v=>!f.current.painted.has(v));if(J.length>0){f.current.order=Nr(J,new Set);for(const[v,g]of Lr(J))f.current.starts.set(v,g);for(;f.current.starts.size>Xr;){const v=f.current.starts.keys().next().value;if(v===void 0)break;f.current.starts.delete(v)}for(const v of Ad(J))f.current.waiting.add(v);for(const v of $d(J))f.current.waiting.delete(v);for(;f.current.waiting.size>Pu;){const v=f.current.waiting.values().next().value;if(v===void 0)break;f.current.waiting.delete(v)}}for(const v of[...f.current.attempts.keys()])oe.has(v)&&f.current.attempts.delete(v);for(Bo([...dt,...Ye]);f.current.attempts.size>zr;){const v=f.current.attempts.keys().next().value;if(v===void 0)break;f.current.attempts.delete(v)}if(performance.mark("lop:transcript:flush:start"),c(v=>{let g={...v},q=g.frontend!==null,fe=null;const pt=Date.now();for(const $ of j){if($.type==="heartbeat")continue;if($.type==="gap"){g={...g,frontend:null,heldFrontend:g.frontend??g.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:$r(g.transcript)},q=!1;continue}const K=w.current;if(($.type==="open"||"seq"in $)&&(w.current={epoch:$.epoch,seq:$.seq},g={...g,receipt:w.current}),$.type==="open"){if(g={...g,subscriptionId:$.payload.subscription_id},$.payload.gap){const L=g.frontend??g.heldFrontend;g={...g,frontend:null,heldFrontend:L,history:null,transcript:$r(g.transcript)},L&&g.status==="live"&&(g={...g,status:"reconnecting"}),q=!1}continue}if(!q){if($.type==="event"&&(fe=us(fe??g.transcript,$.payload,pt,{frame:{epoch:$.epoch,seq:$.seq}})),$.type==="snapshot"){const L=$.payload;let de=fe??g.transcript;L.history.cursor_missing||(de=Rt(de,L.history)),e&&Ze.getState().resolveHeldFromServer(e,L.history.entries.map(Fe=>Fe.id),!L.history.cursor_missing),de=Rd(de,L.frontend.snapshot,pt,{epoch:$.epoch,seq:$.seq}),g={...g,subagentPulses:mu(L.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...L.frontend.snapshot,attention:vt(g.frontend?.attention,L.frontend.snapshot.attention,e)},history:L.history,cold:L.cold,ownerEpoch:L.frontend.epoch,failure:null,hydrated:g.hydrated||!L.history.cursor_missing&&L.history.entries.length>0,transcript:de},q=!0,fe=null}continue}if($.type==="attention"){g.frontend&&(g={...g,frontend:{...g.frontend,attention:vt(g.frontend.attention,$.payload,e)}});continue}if($.type==="frontend.update"){const L=$.payload;if(!g.frontend)continue;const de=L.epoch!==g.ownerEpoch&&L.changes.epoch===L.epoch;(de||L.epoch===g.ownerEpoch&&g.frontend.sequence<L.sequence)&&(g={...g,ownerEpoch:de?L.epoch:g.ownerEpoch,frontend:{...g.frontend,...L.changes,attention:vt(g.frontend.attention,L.changes.attention,e),sequence:L.sequence}});continue}if($.type==="frontend.replace"){if(g.frontend&&fl(K,e,$)){const L=$.payload.frontend;g={...g,frontend:{...L.snapshot,attention:vt(g.frontend.attention,L.snapshot.attention,e)},ownerEpoch:L.epoch,cold:$.payload.cold}}continue}if($.type==="event"){const L=String($.payload.type??"");bu.has(L)&&(g={...g,terminal:L}),Kr.has(L)&&(g={...g,turnsCompleted:g.turnsCompleted+1});const de=us(g.transcript,$.payload,pt,{frame:{epoch:$.epoch,seq:$.seq},userStoppedAt:e?Ze.getState().stoppedTurns[e]??null:null});de!==g.transcript&&(g={...g,transcript:de});const Fe=gu(g.subagentPulses,$.payload);Fe!==g.subagentPulses&&(g={...g,subagentPulses:Fe})}}if(!q&&fe&&(g={...g,transcript:fe}),performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),u.current=g.transcript.index,!vu(j))return v;if(Xe.length>0){const $=new Set(g.labelPending);for(const K of Xe)$.add(K);g={...g,labelPending:$}}return g.frontend!==null&&g.frontend!==g.heldFrontend&&(g={...g,heldFrontend:g.frontend}),g}),Xe.length>0){for(const v of Xe)f.current.painted.add(v);for(;f.current.painted.size>Ou;){const v=f.current.painted.values().next().value;if(v===void 0)break;f.current.painted.delete(v)}}const Ue=Qe.length>0&&dt.length===0&&Ye.length===0&&!G;if(G||ft.length>0){const v=new Set(ft),g=f.current.order;Ln(k,ve,ft.length>0?{targets:v,order:g,starts:f.current.starts,waiting:f.current.waiting,every:new Set([...g,...v]),found:new Set(Gn(j.flatMap(q=>q.type==="snapshot"?q.payload.history.entries:[]),new Set(g))),pending:Xe}:Qr,1,Ue?q=>{f.current.settleRows+=q}:void 0)}},Nn=()=>{const j=P;if(P=null,!!j){U=!0;try{j()}finally{U=!1}}},Jt=()=>{Xt(),Tt=window.setTimeout(()=>{Tt=0,_.current===k&&(Nn(),c(j=>({...j,subscriptionId:null,status:"unavailable",failure:kr(Pt.ended),heldFrontend:null})),!Pn&&(Pn=!0,We=window.setTimeout(()=>{We=0,_.current===k&&Ws()},Tu)))},ku),P=cl({sessionId:e,epoch:E.current.epoch,afterSeq:E.current.afterSeq},j=>{if(_.current===k){if(j.kind==="error"||j.kind==="end"){if(U)return;if(Xt(),Nn(),j.kind==="error"&&j.status===404){e&&(au(e),fu(e)),c(G=>({...G,subscriptionId:null,status:"unavailable",missing:!0,failure:null,heldFrontend:null}));return}const F=j.kind==="error"?j.detail??"The event stream failed.":"The event stream closed unexpectedly.";if(c(G=>({...G,subscriptionId:null})),me>=Su){c(G=>({...G,status:"unavailable",failure:kr(F),heldFrontend:null}));return}me+=1;const Z=w.current;Z&&(E.current={epoch:Z.epoch,afterSeq:Z.seq}),c(G=>G.status==="unavailable"&&me>1?G:{...G,status:"reconnecting",failure:null}),ie=window.setTimeout(()=>{ie=0,_.current===k&&Jt()},Vr(me));return}if(j.data!==void 0)try{const F=JSON.parse(j.data);F.type==="snapshot"&&(me=0,Xt(),Pn=!1),d.current.push(F),te||(te=requestAnimationFrame(Ks)),W||(W=window.setTimeout(Ks,xu))}catch{}}})},Ho=()=>{ie!==0&&(window.clearTimeout(ie),ie=0),E.current={},w.current=null,Nn(),Jt()},Ws=()=>{me=0,We&&(window.clearTimeout(We),We=0),ie&&(window.clearTimeout(ie),ie=0),Ke&&(window.clearTimeout(Ke),Ke=0),c(j=>({...j,failure:null,status:j.status==="unavailable"?"connecting":j.status})),o.current.hydrated||Ln(k,new Set(o.current.transcript.index.keys())),!P&&Jt()};Jt(),h.current=Ws;const Vo=Lu(e,Ho);return()=>{_.current+=1,h.current=null,Vo(),P?.(),te&&cancelAnimationFrame(te),W&&clearTimeout(W),ie&&clearTimeout(ie),Ke&&clearTimeout(Ke),x.current&&(window.clearTimeout(x.current),x.current=0),I.current&&(window.clearTimeout(I.current),I.current=0),We&&window.clearTimeout(We),Xt(),d.current=[]}},[c,e,t]),T.useEffect(()=>{E.current={},w.current=null,u.current=Be.index;const k=Gu(l.current,e,n);l.current=e;const P=e?oo(e):null;c(U=>({...U,frontend:null,heldFrontend:k?U.heldFrontend:null,pendingModel:null,history:null,terminal:null,turnsCompleted:k?U.turnsCompleted:0,transcript:k?U.transcript:P?.transcript??Be,stale:k?U.stale:P!==null,missing:k?U.missing:!1,status:"connecting",subagentPulses:{},labelPending:P?.owedLabels??et,labelMarked:P?.markLabels??At,labelHoldLate:!1,hydrated:!1,loadingOlder:!1})),f.current=Jr(e)},[e,n]),T.useEffect(()=>{if(e)return()=>{const k=o.current.transcript;k.records.length>0&&ou(e,{transcript:k,owedLabels:new Set([...o.current.labelPending].filter(P=>Kn(f.current,o.current.transcript.argsByCall,P,zn(o.current)))),markLabels:new Set(o.current.labelMarked)});for(const P of p.current)f.current.inFlight.delete(P);p.current.clear()}},[e]);const x=T.useRef(0);T.useEffect(()=>{if(r.labelPending.size===0&&r.labelMarked.size===0){x.current&&(window.clearTimeout(x.current),x.current=0);return}if(x.current)return;const k=()=>{x.current=0;const P=o.current.labelPending,U=o.current.labelMarked;if(P.size===0&&U.size===0)return;const te=f.current;for(const W of P)if(te.inFlight.has(W)){x.current=window.setTimeout(k,Vn);return}for(const W of U)if(te.inFlight.has(W)){x.current=window.setTimeout(k,Vn);return}c(W=>W.labelPending.size===0&&W.labelMarked.size===0?W:{...W,labelPending:et,labelMarked:At})};x.current=window.setTimeout(k,Vn)},[c,r.labelPending,r.labelMarked]);const I=T.useRef(0);T.useEffect(()=>{if(r.labelPending.size===0){I.current&&(window.clearTimeout(I.current),I.current=0),c(k=>k.labelHoldLate?{...k,labelHoldLate:!1}:k);return}r.labelHoldLate||I.current||(I.current=window.setTimeout(()=>{I.current=0,c(k=>k.labelPending.size===0||k.labelHoldLate?k:{...k,labelHoldLate:!0})},Ru))},[c,r.labelPending,r.labelHoldLate]);const re=T.useRef(e);re.current=e;const H=T.useRef(!1),ae=T.useRef({session:null,cursor:null});ae.current.session!==e&&(ae.current={session:e??null,cursor:null});const Te=T.useCallback(async()=>{if(!e||H.current)return!1;const{transcript:k}=o.current;if(!k.hasMore||!k.oldestId)return!1;const P=e;H.current=!0,c(U=>({...U,loadingOlder:!0}));try{const U=ie=>ce({op:"sessions.history",sessionId:P,beforeId:ie,limit:100}),te=ae.current.cursor??k.oldestId;let W=await U(te),me=Dr(W,te,!1);return me.cursor!==null&&(ae.current={session:P,cursor:me.cursor},W=await U(me.cursor),me=Dr(W,me.cursor,!0)),ae.current={session:P,cursor:me.cursor},me.failed?(c(ie=>({...ie,loadingOlder:!1})),!1):re.current!==P?(c(ie=>({...ie,loadingOlder:!1})),!1):(c(ie=>({...ie,loadingOlder:!1,transcript:Rt(ie.transcript,W)})),!0)}catch{return c(U=>({...U,loadingOlder:!1})),!1}finally{H.current=!1}},[c,e]),M=T.useRef(!1),V=T.useCallback(async(k,P)=>{if(!e||M.current)return!1;const U=e;M.current=!0;try{const te=await ce({op:"sessions.history",sessionId:U,limit:100});return re.current!==U||o.current.transcript.viewEpoch!==P?!1:(c(W=>({...W,transcript:Rt(W.transcript,te,{keepPaging:!0})})),Kd(te.entries,k))}catch{return!1}finally{M.current=!1}},[c,e]);T.useEffect(()=>s?Bu(s,P=>{c(U=>{const te=P(U.transcript);return te===U.transcript?U:{...U,transcript:te}})}):void 0,[c,s]),T.useEffect(()=>{s&&Fu(s,r.transcript)},[s,r.transcript]);const z=T.useCallback(()=>{c(k=>({...k,transcript:Fd(k.transcript),heldFrontend:null}))},[c]),le=T.useCallback(()=>{h.current?.()},[]),he=T.useCallback((k,P="info")=>{c(U=>({...U,transcript:Hd(U.transcript,k,P)}))},[c]),Ee=T.useCallback(k=>{c(P=>({...P,pendingModel:k}))},[c]),Qt=T.useCallback(()=>{c(k=>k.pendingModel===null?k:{...k,pendingModel:null})},[c]);return T.useEffect(()=>{const k=r.pendingModel;if(!k)return;const P=Hn(k);if(!P)return;const U=r.frontend;(Hn(U?.selected_model)===P||Hn(U?.effective_model)===P)&&c(te=>({...te,pendingModel:null}))},[c,r.frontend,r.pendingModel]),T.useEffect(()=>{if(!r.pendingModel)return;const k=window.setTimeout(()=>c(P=>({...P,pendingModel:null})),wu);return()=>window.clearTimeout(k)},[c,r.pendingModel]),T.useMemo(()=>({...r,awaitingHydration:t&&!!e&&n&&!r.hydrated,loadOlder:Te,refreshTail:V,clearView:z,addNote:he,paintPendingModel:Ee,clearPendingModel:Qt,retry:le}),[r,t,e,n,Te,V,z,he,Ee,Qt,le])}function Rn(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
|
|
8
|
+
`),i=(s?`${n} ${s}`:n).trim();if(i.length<=Lt)return{headline:i,detail:r||null};const o=s===null?null:bd(s);if(o!==null){const c=(f,p)=>`${Sn} ${[f,p].filter(Boolean).join(" ")}`,l=f=>[f,r].filter(Boolean).join(`
|
|
9
|
+
`)||null,d=`${n} ${c(o.leading,o.clause)}`;if(d.length<=Lt)return{headline:d,detail:l(o.rest)};const u=`${n} ${c("",o.clause)}`;if(u.length<=Lt)return{headline:u,detail:l([o.leading,o.rest].filter(Boolean).join(" "))}}return{headline:qi(i),detail:[s,r].filter(Boolean).join(`
|
|
10
|
+
`)||null}}function bd(e){const t=e.startsWith(Sn)?e.slice(Sn.length):e,n=t.indexOf("/mcp");if(n<0)return null;const s=t.slice(n),r=s.search(hd),i=(r<0?s:s.slice(0,r)).trim();return i?{leading:t.slice(0,n).trim(),clause:i,rest:(r<0?"":s.slice(r)).trim()}:null}function wd(e){const t=e.trim(),n=Sd(t);if(n<0)return{headline:t,detail:null};const s=t.slice(n).trim();return{headline:t.slice(0,n).trim(),detail:s||null}}function Sd(e){for(let t=0;t<e.length-1;t++)if(".!?…".includes(e[t])&&yd.test(e[t+1])&&!md.test(e.slice(0,t+1))&&gd.test(e.slice(t+1).trimStart()[0]??""))return t+1;return-1}function kd(e,t){const n=e.split(`
|
|
11
|
+
`),s=n[0].match(fd),i=(typeof t.raw=="string"?t.raw.trim():"")||(s?n[0].slice(s[0].length):n[0]).trim()||e.trim(),o=n.slice(1).join(`
|
|
12
|
+
`).trim();return{provider:(s?.[1]??"").trim()||null,category:(s?.[2]??"").trim()||null,headline:i,detail:o||null}}function Td(e){const t=Ed(e),n=e.split(`
|
|
13
|
+
`).map(s=>s.trim()).filter(Boolean).join(" ");return{headline:t,detail:n===t?null:e}}function Ed(e){const t=e.split(`
|
|
14
|
+
`).map(c=>c.trim()).filter(Boolean),n=c=>!Pr.test(c)&&!xd(c),s=t.find(n),r=t.find(c=>Pr.test(c)&&!c.startsWith("</"));let i=s??r??e.trim();const o=t.indexOf(i);if(o>=0&&i.endsWith(":")){const c=t.slice(o+1).find(n);c&&(i=`${i} ${c}`)}return qi(i)}function xd(e){return pd.has(e.replace(/\s+/g," ").trim().toLowerCase())}function qi(e){const t=e.trim();if(t.length<=Lt)return t;const n=t.slice(0,Lt),s=n.lastIndexOf(" ");return`${(s>0?n.slice(0,s):n).trimEnd()}…`}const Id="harness_injected",eo=e=>!e||typeof e!="object"?!1:e[Id]===!0;function Cd(e,t){const n=e.payload??{},s=Math.round((e.ts??0)*1e3);if(e.type==="compaction"){const o=t?.kind==="compaction"?t.text:Qi,c=n.tokens_before;return{kind:"compaction",id:e.id,ts:s,text:o,...typeof c=="number"?{before:c}:{}}}if(e.type==="message"&&n.custom_type==="compaction_refused"){const o=n.details??{},c=Yi(String(o.detail??""));return{kind:"notice",id:e.id,ts:s,text:c.text,level:c.level}}if(e.type==="custom"&&n.custom_type==="completion_attention"){const o=n.details??{};if(typeof o.anchor=="string"&&(o.kind==="error"||o.kind==="interrupted"))return{kind:"notice",id:o.anchor,ts:s,complete:!0,text:o.kind==="error"?"Stopped with an error":"Interrupted",level:o.kind==="error"?"error":"warning"}}if(e.type!=="message")return null;if(String(n.kind??"message")==="custom"){const o=String(n.custom_type??"");if(rd.has(o))return null;const c=n.details??{};if(o===cd){const{body:d,sender:u}=Al(c);return{kind:"peer",id:e.id,ts:s,body:d,sender:t?.kind==="peer"&&El(t.sender,u)?t.sender:u}}if(o===ld){if(Ol(c))return null;const d=String(c.text??"");return d.trim()?{kind:"wake",id:e.id,ts:s,text:d}:null}const l=String(c.text??c.detail??"");return l.trim()?{kind:"custom",id:e.id,ts:s,customType:o,text:l,attribution:n.attribution??"system",...vd(o,l,c)}:null}const i=String(n.role??"");if(i==="user"){if(eo(n.provider_payload))return null;const o=nt(n);return o.startsWith("Harness recovery notice:")?{kind:"notice",id:e.id,ts:s,text:o,level:"warning"}:{kind:"user",id:e.id,ts:s,text:o,images:wn(n,e.id,t?.kind==="user"?t.images:void 0)}}if(i==="assistant"){const o=Array.isArray(n.tool_calls)?n.tool_calls:[],c=nt(n);return!c&&o.length>0?{kind:"assistant",id:e.id,ts:s,text:"",streaming:!1,stopReason:String(n.stop_reason??"toolUse"),error:!1}:{kind:"assistant",id:e.id,ts:s,text:c,complete:!0,streaming:!1,stopReason:n.stop_reason??null,error:!!n.is_error}}if(i==="tool"){const o=String(n.tool_call_id??e.id),c=n.provider_payload??{},l=c.details??{},d=zi(l.__fault);return{kind:"tool",id:`tool:${o}`,ts:s,toolCallId:o,toolName:String(n.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:nt(n)||null,isError:d?!1:!!n.is_error,durationS:typeof c.duration_s=="number"?c.duration_s:null,startedAt:null,endedAt:null,images:wn(n,`tool:${o}`,t?.kind==="tool"?t.images:void 0),...Hi(c.details,t?.kind==="tool"?t:null),diff:Gi(Zi(c.details),t?.kind==="tool"?t.diff:null),stopped:d}}return null}function Rd(e,t){if(!e.cursor_missing||e.entries.length===0)return null;const n=e.entries[0]?.id;return typeof n!="string"||n===t?null:n}function Dr(e,t,n){if(!e.cursor_missing)return{cursor:null,failed:!1};const s=Rd(e,t);return!n&&s!==null?{cursor:s,failed:!1}:{cursor:null,failed:!0}}function Rt(e,t,n={}){const s=n.keepPaging===!0&&e.viewEpoch>0,r=[];for(const h of t.entries){if(s&&!Hd(h,e.clearedAt))continue;const _=e.records[e.index.get(h.id)??-1]??e.records[e.index.get(`tool:${String(h.payload?.tool_call_id??"")}`)??-1],x=Cd(h,_);x&&r.push(x)}let i=e.argsByCall,o=!1;for(const h of t.entries){const _=h.payload?.tool_calls;if(!Array.isArray(_))continue;const x=Math.round((h.ts??0)*1e3);for(const I of _)!I||typeof I.id!="string"||i.has(I.id)||(o||(i=new Map(i),o=!0),i.set(I.id,{...I,anchoredAt:x}))}for(let h=0;h<r.length;h++){const _=r[h];if(_.kind!=="tool")continue;const x=i.get(_.toolCallId);if(!x)continue;const I=x.arguments??null;r[h]={..._,args:I,intent:typeof I?.i=="string"?I.i:null}}const c=o?e.records.map(h=>{if(h.kind!=="tool"||h.args)return h;const x=i.get(h.toolCallId)?.arguments??null;return x?{...h,args:x,intent:h.intent??(typeof x.i=="string"?x.i:null)}:h}):e.records,l=n.replace?Be:{...e,records:c},d=new Map(l.records.map(h=>[h.id,h]));let u=n.replace||!n.replace&&c!==e.records;for(const h of r){const _=d.get(h.id);if(!_){u=!0,d.set(h.id,h);continue}if(_.kind==="tool"&&h.kind==="tool"){const x={...h,args:h.args??_.args,intent:h.intent??_.intent,images:_.images.length?_.images:h.images};ds(_,x)||(u=!0,d.set(h.id,x));continue}ds(_,h)||(u=!0,d.set(h.id,h))}const f=e.compacting&&t.entries.some(h=>e.index.has(h.id)||Math.round((h.ts??0)*1e3)<e.compactingSince?!1:h.type==="compaction"||h.type==="message"&&h.payload?.custom_type==="compaction_refused");if(!u&&e.hasMore===t.has_more&&!f)return e;const p=Xi(Wi([...d.values()],new Set(r.map(h=>h.id)))),w=t.entries[0];let E=l.oldestId;if(n.keepPaging)return{...e,records:p,index:kt(p),argsByCall:i};if(w){const h=Math.round((w.ts??0)*1e3),_=E?l.records[l.index.get(E)??-1]:void 0;(!_||h<=_.ts)&&(E=w.id)}return{...e,records:p,index:kt(p),oldestId:E,hasMore:t.has_more,argsByCall:i,compacting:f?!1:e.compacting,compactingSince:f?0:e.compactingSince}}const Zn={settledAssistantUpdate:0,seededDeltaWithheld:0,staleUpdateFrameDropped:0};function us(e,t,n=Date.now(),s={}){const r=t.message,i=s.frame;switch(t.type){case"agent_start":{const o=Number(t.generation??e.generation+1);return o===e.generation?e:{...e,generation:o,compacting:!1,compactingSince:0}}case"compaction_start":return e.compacting?e:{...e,compacting:!0,compactingSince:n};case"agent_end":{if(Number(t.generation??e.generation)<e.generation)return e;let c=e;for(const l of e.records)if(l.kind==="assistant"&&l.streaming&&(c=ne(c,{...l,streaming:!1,settledAt:n,stopReason:t.aborted?"aborted":l.stopReason})),l.kind==="tool"&&l.phase!=="done"){const d=l.phase==="composing"||l.phase==="queued";c=ne(c,{...l,phase:"done",startedAt:null,stopped:!!t.aborted||d,neverSent:l.neverSent||d})}return c}case"message_start":{if(!r||typeof r.id!="string")return e;const o=e.records[e.index.get(r.id)??-1];if(r.role==="user"){if(eo(r.provider_payload))return e;const c=o?.kind==="user"&&o.provisional===!0;return ne(e,{kind:"user",id:r.id,ts:c?Us(e,n):n,text:nt(r),images:wn(r,r.id,o?.kind==="user"?o.images:void 0),...c?{provisional:!0}:{}})}return r.role!=="assistant"||o?e:ne(e,{kind:"assistant",id:r.id,ts:n,text:"",streaming:!0,...i?{frame:i}:{},stopReason:null,error:!1})}case"message_update":{if(!r||typeof r.id!="string")return e;const o=e.index.get(r.id),c=String(t.delta??""),l=nt(r);if(o===void 0)return!l&&!c?e:ne(e,{kind:"assistant",id:r.id,ts:n,text:l?l+c:c,streaming:!0,truncated:l===""?"prefix":void 0,...i?{frame:i}:{},stopReason:null,error:!1});const d=e.records[o];if(d.kind!=="assistant")return e;if(!d.streaming)return Zn.settledAssistantUpdate+=1,e;if(s.seed!==!0&&i&&d.frame&&i.epoch===d.frame.epoch&&i.seq<=d.frame.seq)return Zn.staleUpdateFrameDropped+=1,e;const u=td(d.frame,i);if(s.seed===!0&&!l)return!d.text&&!c?e:(Zn.seededDeltaWithheld+=d.text?1:0,ne(e,{...d,text:d.text||c,...u?{frame:u}:{},truncated:d.text?"interrupted":"prefix"}));let f;if(l){if(f=l+c,f.length<=d.text.length)return e}else{if(!c)return e;f=d.text+c}return ne(e,{...d,text:f,...u?{frame:u}:{},truncated:l?void 0:d.truncated})}case"message_end":{if(!r||typeof r.id!="string"||r.role!=="assistant")return e;const o=e.index.get(r.id),c=nt(r),l=o===void 0?void 0:e.records[o],d=Array.isArray(r.tool_calls)?r.tool_calls:[],u={kind:"assistant",id:r.id,ts:o===void 0?n:e.records[o].ts,text:c,...c||d.length===0?{complete:!0}:{},streaming:!1,settledAt:l?.kind==="assistant"&&l.settledAt!==void 0?l.settledAt:n,stopReason:r.stop_reason??null,error:!!r.is_error};return ne(e,u)}case"history_delta":{const c={entries:(Array.isArray(t.messages)?t.messages:[]).map(l=>({id:String(l.id??""),ts:n/1e3,type:"message",payload:{kind:l.custom_type?"custom":"message",...l}})),has_more:e.hasMore};return Rt(e,c,{replace:t.reset===!0})}case"tool_call_compose":{const o=String(t.tool_call_id??"");if(!o)return e;const c=String(t.supersedes_tool_call_id??""),l=`tool:${o}`,d=e.records[e.index.get(l)??-1],u=c?e.records[e.index.get(`tool:${c}`)??-1]:void 0,f=d?.kind==="tool"?d:u?.kind==="tool"?u:void 0;if(f&&f.phase!=="composing"&&f.phase!=="queued")return c&&d?.kind==="tool"?Or(e,c):e;const w=String(t.not_run_reason??"").trim()||null,E=String(t.not_run_kind??"").trim()||null,h=Number(t.argument_bytes??0),_={kind:"tool",id:l,ts:f?.ts??n,toolCallId:o,toolName:String(t.tool_name??""),intent:t.intent??null,args:null,phase:w?"done":t.dictation_complete===!0?"queued":"composing",argumentBytes:h>0?h:f?.argumentBytes??0,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:Dt,added:0,removed:0,diff:null,stopped:!1,notRunReason:w,notRunKind:w?E:null,neverSent:w!==null};return c&&u?.kind==="tool"&&d?.kind!=="tool"?sd(e,c,_):ne(c&&d?.kind==="tool"?Or(e,c):e,_)}case"tool_execution_start":{const o=String(t.tool_call_id??"");if(!o)return e;const c=`tool:${o}`,l=e.records[e.index.get(c)??-1];if(l&&l.kind==="tool"&&l.phase==="done"&&!l.notRunReason)return e;const d=Ar(e,o,t,l),u=d&&!e.argsByCall.has(o)?new Map(e.argsByCall).set(o,{arguments:d,anchoredAt:Nt(t)??n}):e.argsByCall,f=u===e.argsByCall?e:{...e,argsByCall:u};return ne(f,{kind:"tool",id:c,ts:l?.ts??n,toolCallId:o,toolName:String(t.tool_name??""),intent:t.intent??(typeof d?.i=="string"?d.i:null),args:d,phase:"running",notRunReason:null,notRunKind:null,neverSent:!1,argumentBytes:0,output:null,isError:!1,durationS:null,startedAt:Nt(t)??(l?.kind==="tool"&&l.startedAt!==null?l.startedAt:n),endedAt:null,images:l?.kind==="tool"?l.images:Dt,added:0,removed:0,diff:l?.kind==="tool"?l.diff:null,stopped:!1})}case"tool_execution_end":{const o=String(t.tool_call_id??"");if(!o)return e;const c=`tool:${o}`,l=e.records[e.index.get(c)??-1],d=t.result??{},u=Ar(e,o,t,l),f=l&&l.kind==="tool"?l:{kind:"tool",id:c,ts:n,toolCallId:o,toolName:String(t.tool_name??""),intent:null,args:null,phase:"done",argumentBytes:0,notRunReason:null,notRunKind:null,neverSent:!1,output:null,isError:!1,durationS:null,startedAt:null,endedAt:null,images:Dt,added:0,removed:0,diff:null,stopped:!1},p=u&&!e.argsByCall.has(o)?new Map(e.argsByCall).set(o,{arguments:u,anchoredAt:Nt(t)??n}):e.argsByCall,w=p===e.argsByCall?e:{...e,argsByCall:p},E=s.userStoppedAt??null,h=!!(t.is_error??d.is_error),_=zi(d.details?.__fault),x=E!==null&&(typeof f.startedAt=="number"?f.startedAt<=E:h);return ne(w,{...f,args:u,phase:"done",notRunReason:null,notRunKind:null,neverSent:!1,output:nt(d)||null,isError:x||_?!1:h,durationS:typeof t.duration_s=="number"?t.duration_s:null,endedAt:typeof t.duration_s=="number"&&typeof f.startedAt=="number"?f.startedAt+t.duration_s*1e3:null,startedAt:null,images:ed(wn(d,c,f.images),f.images),...Hi(d.details,f),diff:Gi(Zi(d.details),f.diff),stopped:f.stopped||x||_})}case"notice":{const o=String(t.text??"");if(!o)return e;const c=`notice:${e.generation}:${o}`;return e.index.has(c)?e:ne(e,{kind:"notice",id:c,ts:n,text:o,level:t.kind??"info"})}case"compaction_end":{const o=Number(t.tokens_before??0),c=Number(t.tokens_after??0),d=!!t.success?null:Yi(String(t.detail??"")),u=d?d.text:o&&c?id(o,c):Qi,f=`compaction:${e.generation}:${o}:${c}`,p=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return p.index.has(f)?p:d?ne(p,{kind:"notice",id:f,ts:n,text:u,level:d.level}):ad(ne(p,{kind:"compaction",id:f,ts:n,text:u,before:o}))}case"retry_start":{const o=`Retrying after an error (attempt ${String(t.attempt??"?")})${t.fallback_model?`, falling back to ${String(t.fallback_model)}`:""}`,c=`retry:${e.generation}:${String(t.attempt??"")}`;return e.index.has(c)?e:ne(e,{kind:"notice",id:c,ts:n,text:o,level:"warning"})}case"subagent_end":{const o=`subagent:${String(t.job_id??"")}`,c=String(t.status??""),l=`${String(t.label??"Subagent")} ${c||"finished"}`,d=e.records[e.index.get(o)??-1];return d&&d.kind==="notice"&&d.text===l?e:ne(e,{kind:"notice",id:o,ts:d?.ts??n,text:l,level:c==="failed"?"error":"info"})}default:return e}}function Nt(e){return hl(e.started_at_epoch)}function to(e){if(!e.type.startsWith("tool_"))return null;const t=String(e.tool_call_id??"");return t||null}function Ad(e){const t=to(e);if(t)return`tool:${t}`;const n=e.message;return typeof n?.id=="string"&&n.id?n.id:null}function Od(e,t){const n=Nt(e);if(n!==null)return n;const s=to(e);if(!s)return null;const r=t.argsByCall.get(s)?.anchoredAt;return typeof r=="number"&&Number.isFinite(r)&&r>0?r:null}function js(e){return e.type!=="tool_call_compose"?!1:typeof e.not_run_reason=="string"&&e.not_run_reason.trim().length>0?!0:e.dictation_complete===!0}function Cn(e){return e.type==="tool_execution_end"}function Pd(e,t,n=Date.now(),s=null){let r=e;t.streaming&&t.generation>r.generation&&(r={...r,generation:t.generation}),r.compacting&&(r={...r,compacting:!1,compactingSince:0});const i=t.streaming===!0;let o=!1;const c=new Set;for(const d of t.live_events??[]){const u=d;let f=n;const p=Ad(u);if(p!==null&&!r.index.has(p)){const w=Od(u,r);if(w!==null)f=w,o=!0,c.add(p);else if(Cn(u)||js(u)||!i)continue}r=us(r,u,f,{seed:!0,...s?{frame:s}:{}})}if(!o)return r;const l=Wi(r.records,c);return{...r,records:l,index:kt(l)}}function Lr(e){const t=new Map;for(const n of e??[]){if(!n)continue;const s=n;if(!Cn(s)&&!js(s))continue;const r=String(s.tool_call_id??"");if(!r)continue;const i=Nt(s);i!==null&&t.set(r,i)}return t}function Dd(e){const t=new Set;for(const n of e??[]){if(!n)continue;const s=n;if(s.type!=="tool_call_compose")continue;const r=s.not_run_reason;if(typeof r=="string"&&r.trim().length>0)continue;const i=String(s.tool_call_id??"");i&&t.add(i)}return t}const Ld=5e3;function Nd(e,t){const n=new Set(t),s=new Map;if(n.size===0)return s;for(const r of e){if(r.payload?.role!=="tool")continue;const i=r.payload.tool_call_id;if(typeof i!="string"||!n.has(i))continue;const o=r.ts;typeof o!="number"||!Number.isFinite(o)||s.set(i,Math.round(o*1e3))}return s}function Md(e,t,n,s=new Map,r=new Set){const i=e[0]?.ts;if(typeof i!="number"||!Number.isFinite(i))return!1;let o=null;for(const l of t){const d=n.get(l);if(d===void 0){if(r.has(l))continue;return!1}(o===null||d<o)&&(o=d)}for(const l of s.values())(o===null||l<o)&&(o=l);return o===null?!1:Math.round(i*1e3)<=o-Ld}function Nr(e,t){const n=[];for(const s of e??[]){if(!s)continue;const r=s;if(!Cn(r)&&!js(r))continue;const i=String(r.tool_call_id??"");!i||n.includes(i)||t.has(i)||n.push(i)}return n}function Mr(e,t,n,s){const r=[],i=new Set;for(const o of t)i.has(o)||(i.add(o),!n.has(o)&&((e.get(o)??0)>=s||r.push(o)));return r}const jd=3.25,fs=100,$s=500;function jr(e){return e<=0?fs:Math.min($s,fs+Math.ceil(jd*e))}function Gn(e,t){const n=[];if(t.size===0)return n;for(const s of e){const r=s.payload?.tool_calls;if(Array.isArray(r))for(const i of r)i&&typeof i.id=="string"&&t.has(i.id)&&n.push(i.id)}return n}function $d(e){for(const t of e)if(t.payload?.role==="user")return!0;return!1}function Ud(e,t){const n=new Set(t);for(const i of e){const o=i.payload?.tool_calls;if(Array.isArray(o))for(const c of o)c&&typeof c.id=="string"&&n.add(c.id)}const s=[],r=new Set;for(const i of e){if(i.payload?.role!=="tool")continue;const o=i.payload.tool_call_id;typeof o!="string"||n.has(o)||r.has(o)||(r.add(o),s.push(o))}return s}function Fd(e,t){return e&&t===0}function Bd(e){const t=new Set;for(const n of e??[]){if(!n)continue;const s=n,r=s.not_run_reason,i=s.type==="tool_call_compose"&&typeof r=="string"&&r.trim().length>0;if(s.type!=="tool_execution_start"&&!Cn(s)&&!i)continue;const o=String(s.tool_call_id??"");o&&t.add(o)}return t}function no(e,t,n){const s=new Set(e),r=[];for(const i of t)!s.has(i)&&!n.has(i)&&r.push(i);for(const i of e){if(n.has(i))return r;t.has(i)&&r.push(i)}return r}function Zd(e,t,n){return no(e,t,n).length}function $r(e){let t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;for(const n of e.records)n.kind!=="assistant"||!n.streaming||n.truncated||(t=ne(t,{...n,truncated:"interrupted"}));return t}function Gd(e,t=Date.now()){return e.records.length===0?e:{...Be,generation:e.generation,compacting:e.compacting,compactingSince:e.compactingSince,viewEpoch:e.viewEpoch+1,clearedAt:t,argsByCall:e.argsByCall}}function Hd(e,t){return e.type==="compaction"||e.type==="message"&&e.payload?.custom_type==="compaction_refused"?t===void 0?!0:Math.round((e.ts??0)*1e3)>=t:!1}function Ur(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function zd(e){const t=e.compacting?{...e,compacting:!1,compactingSince:0}:e;return Ms(t,n=>n.kind==="assistant"&&n.streaming||n.kind==="tool"&&n.phase!=="done")}function Us(e,t){let n=t;for(const s of e.records)s.ts>n&&(n=s.ts);return n}function so(e,t,n,s,r=Date.now()){return e.index.has(t)?e:ne(e,{kind:"user",id:t,ts:Us(e,r),text:n,images:s,local:!0,provisional:!0})}function Vd(e,t){return Ms(e,n=>n.id===t)}let Fr=0;function Kd(e,t,n,s=Date.now()){return Fr+=1,ne(e,{kind:"notice",id:`local:${s}:${Fr}`,ts:Us(e,s),text:t,level:n})}function Zh(e,t,n,s){const r=t?.anchor_id,i=t?.kind;return!r||i!=="error"&&i!=="interrupted"||n||e.index.has(r)||!t?.unseen&&!s?.has(r)?e:(s?.add(r),ne(e,{kind:"notice",id:r,ts:e.records.at(-1)?.ts??Date.now(),complete:!0,text:i==="error"?"Stopped with an error":"Interrupted",level:i==="error"?"error":"warning"}))}const Wd="compacting context…";function Gh(e){return typeof e=="string"&&e.trim()===Wd}const Yd=[1500,5e3];async function Hh(e,t=n=>new Promise(s=>setTimeout(s,n))){for(const n of Yd){await t(n);try{if(await e())return}catch{}}}function Qd(e,t){return e.some(n=>Math.round((n.ts??0)*1e3)<t?!1:n.type==="compaction"||n.type==="message"&&n.payload?.custom_type==="compaction_refused")}const Br=new Set(["openrouter","radient","radient-key"]),Xd=new Set(["auto","openrouter/auto"]),Jd="Auto";function ro(e){return e.slice(e.lastIndexOf("/")+1)||e}function qd(e,t){return e===t||e===ro(t)}function Hn(e){if(!e)return null;const t=typeof e.provider=="string"?e.provider:"";if(!t)return null;const n=typeof e.model_id=="string"?e.model_id:"";return n?`${t}/${n}`:null}function zh(e){if(!e||typeof e.model_id!="string"||!e.model_id)return null;const t=typeof e.provider=="string"?e.provider:"",n=t?`${t}/${e.model_id}`:e.model_id,s=typeof e.display_name=="string"?e.display_name.trim():"",r=Br.has(t)||!s||qd(s,e.model_id)||s.toLowerCase()==="unknown";return{name:Br.has(t)&&Xd.has(e.model_id)?Jd:r?ro(n):s,selector:n}}function Vh(e,t){const n=e?.effective_model??e?.selected_model??null;return{identity:t??n,effort:n}}function Kh(e){return Array.isArray(e?.reasoning_efforts)?e.reasoning_efforts.filter(t=>typeof t=="string"&&t!==""):[]}function Wh(e){if(!e)return null;for(const t of[e.reasoning_effort,e.reasoning_default_effort])if(typeof t=="string"&&t.trim())return t.trim().toLowerCase();return null}function Yh(e){const t=e.trim();return t&&({auto:"Auto",none:"None",minimal:"Minimal",low:"Low",medium:"Medium",high:"High",xhigh:"xHigh",max:"Max"}[t.toLowerCase()]??t)}function io(e){if(!e)return!1;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim():"",n=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim():"";return typeof e.model_id=="string"&&e.model_id!==""&&!t&&!n&&!e.reasoning&&Array.isArray(e.reasoning_efforts)&&e.reasoning_efforts.length===0&&typeof e.display_name=="string"&&e.display_name.trim()===""}function Qh(e,t){const n=(e??t)?.effective_model;return io(n)?null:n?.model_id??null}function Xh(e){if(!e)return null;const t=typeof e.reasoning_effort=="string"?e.reasoning_effort.trim().toLowerCase():"",n=Array.isArray(e.reasoning_efforts)?e.reasoning_efforts.filter(i=>typeof i=="string"):null,s=typeof e.reasoning_default_effort=="string"?e.reasoning_default_effort.trim().toLowerCase():"",r=io(e);return t?{label:t,adjustable:n===null||n.length>0,knownLadder:!!(n&&n.length>0),levelKnown:!0,detail:n&&n.length>0?`Reasoning effort. This model offers ${n.join(", ")}.`:"Reasoning effort for this session."}:n&&n.length>0?{label:"auto",adjustable:!0,knownLadder:!0,levelKnown:!0,detail:`No level is set, so this model runs at its own default${s?` (${s})`:""}. It offers ${n.join(", ")}.`}:r?{label:"unknown",adjustable:!0,knownLadder:!1,levelKnown:!1,detail:"This session has not reported its reasoning effort yet. It appears after the next turn, or run /effort <level> to set one now."}:n&&e.reasoning?{label:"reasoning",adjustable:!1,knownLadder:!0,levelKnown:!0,detail:"This model reasons, but exposes no effort levels to choose between."}:n===null&&s?{label:s,adjustable:!1,knownLadder:!1,levelKnown:!0,detail:"The level this model runs at by default. This backend does not report which other levels it accepts."}:null}function Jh(e,t){if(!e)return null;if(!t||t.length===0||e.knownLadder)return e;const n=t.map(s=>typeof s=="object"&&s!==null&&"value"in s?String(s.value):"").filter(Boolean);return n.length===0?e:{...e,adjustable:!0,detail:`Reasoning effort. This model offers ${n.join(", ")}.`}}function eu(e,t){if(e&&!(e.settled||e.error!==null))return{...e,text:e.text+t,streaming:!0}}function tu(e,t){return!!e.streams[t]}function oo(e,t){return e.attached[t]?.turns.at(-1)}function qh(e,t){const n=oo(e,t);return n?e.streams[n.asideId]:void 0}function em(e,t){const n=e.attached[t]?.turns??[];for(let s=n.length-1;s>=0;s-=1){const r=n[s];if(r&&e.streams[r.asideId]?.settled)return r.asideId}}function nu(){return{text:"",streaming:!0,settled:!1,error:null}}function su(e){return{text:e,streaming:!1,settled:!0,error:null}}function ru(e,t){return{text:e?.text??"",streaming:!1,settled:!1,error:t}}const iu=As(e=>({streams:{},attached:{},attachAside:t=>e(n=>{const s=n.attached[t];return s&&s.notice===null?n:{attached:{...n.attached,[t]:s?{...s,notice:null}:{turns:[],notice:null}}}}),beginAsk:(t,n,s)=>e(r=>({streams:{...r.streams,[n]:nu()},attached:{...r.attached,[t]:{turns:[...r.attached[t]?.turns??[],{asideId:n,question:s}],notice:null}}})),applyAsideDelta:(t,n)=>e(s=>{const r=eu(s.streams[t],n);return r?{streams:{...s.streams,[t]:r}}:s}),settleAside:(t,n)=>e(s=>s.streams[t]?{streams:{...s.streams,[t]:su(n)}}:s),failAside:(t,n)=>e(s=>tu(s,t)?{streams:{...s.streams,[t]:ru(s.streams[t],n)}}:s),setAsideNotice:(t,n)=>e(s=>{const r=s.attached[t];return r?{attached:{...s.attached,[t]:{...r,notice:n}}}:s}),detachAside:t=>e(n=>{const s=n.attached[t],r={...n.attached};if(delete r[t],!s)return{attached:r};const i={...n.streams};for(const o of s.turns)delete i[o.asideId];return{streams:i,attached:r}})}));function tm(e,t){return oo(e,t)?.asideId}const ou=4*1024*1024,au=1024*1024,Re=new Map;function Zr(e){if(e.length===0)return 0;try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return Number.POSITIVE_INFINITY}}function cu(e){const t=e.slice(-200);let n=0,s=Zr(t);for(;n<t.length&&s>au;)n+=1,s=Zr(t.slice(n));return{records:t.slice(n),bytes:s}}function lu(e,t){const{records:n,bytes:s}=cu(zd(t.transcript).records);if(n.length===0){Re.delete(e);return}const i={transcript:{...t.transcript,records:n,index:new Map(n.map((o,c)=>[o.id,c])),oldestId:null,hasMore:!1,argsByCall:new Map},savedAt:Date.now(),bytes:s,owedLabels:Gr(n,t.owedLabels),markLabels:Gr(n,t.markLabels)};Re.delete(e),Re.set(e,i),uu()}function Gr(e,t){if(!t||t.size===0)return Hr;const n=new Set;for(const s of e)s.kind!=="tool"||s.args||s.toolCallId&&t.has(s.toolCallId)&&n.add(s.toolCallId);return n.size>0?n:Hr}const Hr=new Set;function ao(e){const t=Re.get(e);if(!t)return null;const{bytes:n,...s}=t;return s}function du(e){Re.delete(e)}function uu(){let e=0;for(const t of Re.values())e+=t.bytes;for(;e>ou&&Re.size>0;){const t=Re.keys().next().value;if(t===void 0)break;const n=Re.get(t);Re.delete(t),e-=n?.bytes??0}}const fu=8,pu=128,co=new Set,hu="",Ne=new Map,Fs=e=>e??hu;function nm(e){return Ne.get(Fs(e))??co}function sm(e,t,n){const s=Fs(e),r=Ne.get(s)??new Set,i=new Set(r);if(n)for(i.delete(t),i.add(t);i.size>pu;){const o=i.values().next().value;if(o===void 0)break;i.delete(o)}else i.delete(t);for(Ne.delete(s),i.size>0&&Ne.set(s,i);Ne.size>fu;){const o=Ne.keys().next().value;if(o===void 0)break;Ne.delete(o)}return Ne.get(s)??co}function mu(e){Ne.delete(Fs(e))}const gu=new Set(["subagent_start","subagent_progress","subagent_end"]),yu=(e,t)=>({...e,[t]:(e[t]??0)+1}),vu=e=>{const t={};if(!Array.isArray(e))return t;for(const n of e){const s=lo(n);s&&(t[s]=(t[s]??0)+1)}return t},lo=e=>{if(!e||typeof e!="object")return null;const t=e;return gu.has(String(t.type??""))&&typeof t.job_id=="string"&&t.job_id?t.job_id:null},_u=(e,t)=>{const n=lo(t);return n?yu(e,n):e};function bu(e){for(const t of e)t.type==="aside_delta"&&iu.getState().applyAsideDelta(t.payload.aside_id,t.payload.delta)}function wu(e){return e.some(t=>t.type!=="aside_delta"&&t.type!=="heartbeat")}const tt=new Set,At=new Set;function Su(e,t){let n=null;for(const s of t)e.has(s)&&(n=n??new Set(e),n.delete(s));return n??e}const ku=new Set(["agent_end","agent_start","provider_start","steering_delivered","turn_end","turn_start"]),Tu=15e3,ps=[500,1e3,2e3,4e3,8e3,8e3],Eu=ps.length,xu=2e4,Iu=1e4;function zr(e){const t=Math.max(1,Math.min(e,ps.length));return ps[t-1]??8e3}const Cu=3,Ru=250,Vr=512,Kr=new Set(["turn_end","agent_end"]),Wr=2,Au=500,Yr=$s,Ou=6,zn=Ai("sessions.history"),Pu=2e3,Qr={targets:new Set,order:[],every:new Set,found:new Set,pending:[],starts:new Map,waiting:new Set},rt=new Map,ln=new Map,Du=8,Lu=2048,Xr=1024,Nu=1024,Mu="",et=new Map;function Jr(e){const t=e??Mu,n=et.get(t);if(n)return et.delete(t),et.set(t,n),n;const s={attempts:new Map,painted:new Set,inFlight:new Set,refused:!1,depth:0,order:[],starts:new Map,waiting:new Set,settled:new Set,settleRows:0};for(et.set(t,s);et.size>Du;){const r=et.keys().next().value;if(r===void 0||r===t)break;et.delete(r)}return s}function Vn(e){return e.terminal||e.failure?!1:(e.frontend??e.heldFrontend)?.streaming===!0}function Kn(e,t,n,s){return t.has(n)?!1:e.inFlight.has(n)?!0:s}function ju(e,t){return ln.set(e,t),()=>{ln.get(e)===t&&ln.delete(e)}}function rm(e){const t=ln.get(e);return t?(t(),!0):!1}const se=new Map,$u=4,Uu=16;function uo(e,t){e(n=>so(n,t.id,t.text,t.images)),t.painted||(t.painted=!0,t.onPainted?.())}function Fu(e,t,n){const s=e.index.get(t),r=s===void 0?void 0:e.records[s];if(s===void 0||!r||r.kind!=="user"||!r.local||r.text===n)return e;const i=e.records.slice();return i[s]={...r,text:n},{...e,records:i}}function hs(e,t){let n=se.get(e);if(!n){if(se.size>=Uu){const i=se.keys().next();i.done||se.delete(i.value)}n=new Map,se.set(e,n)}const s={identity:e,id:t.id,text:t.text,images:t.images,onPainted:t.onPainted,settled:t.settled,submittedAt:t.submittedAt};for(n.set(s.id,s);n.size>$u;){const i=n.keys().next();if(i.done)break;n.delete(i.value)}const r=rt.get(e);r&&uo(r,s)}function im(e){if(!e)return null;const t=se.get(e);if(!t)return null;for(const n of t.values())if(!n.settled)return n;return null}function ms(e,t){const n=se.get(e);n&&(n.delete(t),n.size===0&&se.delete(e))}function gs(e,t){const n=se.get(e)?.get(t);n&&(n.settled=!0)}function qr(e,t){return e?se.get(e)?.has(t)===!0:!1}function om(e){return e?(se.get(e)?.size??0)>0:!1}function Bu(e,t,n){const s=se.get(e)?.get(t);if(!s)return;s.text=n;const r=rt.get(e);r&&r(i=>Fu(i,t,n))}function Zu(e,t){if(e===t)return;const n=se.get(e);if(!n)return;se.delete(e);const s=se.get(t)??new Map;for(const[r,i]of n)i.identity=t,s.set(r,i);se.set(t,s)}function on(e){se.delete(e)}function Gu(e,t){const n=se.get(e);if(n)for(const s of[...n.keys()]){const r=t.index.get(s),i=r===void 0?void 0:t.records[r];i?.kind==="user"&&i.local!==!0&&ms(e,s)}}function Hu(e,t){rt.set(e,t);const n=se.get(e);if(n)for(const s of n.values())uo(t,s);return()=>{rt.get(e)===t&&rt.delete(e)}}function zu(e,t){const n=se.get(e);if(!n)return t;let s=t;for(const r of n.values())s=so(s,r.id,r.text,r.images);return s}function Vu(e,t,n){return e===t?!0:!n}function am(e,t){const n=rt.get(e);if(!n)return ms(e,t),"queued";let s="queued";return n(r=>{const i=r.records[r.index.get(t)??-1];return!i||i.kind!=="user"?r:i.local?(s="retracted",Vd(r,t)):(s="owner",r)}),ms(e,t),s}function Ku(e,t){const n=rt.get(e);if(!n)return"unseen";let s="unseen";return n(r=>{const i=r.records[r.index.get(t)??-1];return!i||i.kind!=="user"||(s=i.local?"local":"owner"),r}),s}function Wu(e){const t=ao(e);return t?{transcript:t.transcript,stale:!0,owedLabels:t.owedLabels,markLabels:t.markLabels}:{transcript:Be,stale:!1,owedLabels:tt,markLabels:At}}function Yu(e){return"cold_reason"in e&&!e.history.cursor_missing&&e.history.entries.length>0}function cm(e,t,n=!0,s=e){const[r,i]=T.useState(()=>{const k=t&&e?Wu(e):null;return{status:"connecting",frontend:null,heldFrontend:null,pendingModel:null,history:null,cold:!1,subscriptionId:null,ownerEpoch:null,receipt:null,terminal:null,turnsCompleted:0,failure:null,transcript:s?zu(s,k?.transcript??Be):Be,stale:k?.stale??!1,missing:!1,loadingOlder:!1,subagentPulses:{},labelPending:k?.owedLabels??tt,labelMarked:k?.markLabels??At,labelHoldLate:!1,hydrated:!1}}),o=T.useRef(r),c=T.useCallback(k=>{const P=k(o.current);return P===o.current||(o.current=P,i(P)),P},[]),l=T.useRef(e),d=T.useRef([]),u=T.useRef(Be.index),f=T.useRef(Jr(e)),p=T.useRef(new Set),w=T.useRef(null),E=T.useRef({}),h=T.useRef(null),_=T.useRef(0);T.useEffect(()=>{if(!e||!t)return;const k=++_.current;let P=null,U=!1,te=0,W=0,me=0,ie=0,We=0,Tt=0,Ye=0,Pn=!1;const Xt=()=>{Tt&&(window.clearTimeout(Tt),Tt=0)},Zo=j=>{for(const F of j)f.current.attempts.set(F,(f.current.attempts.get(F)??0)+1)},Dn=j=>{c(F=>{const Z=new Set;for(const J of F.labelPending)F.labelPending.has(J)&&(Kn(f.current,F.transcript.argsByCall,J,Vn(F))||Z.add(J));let G=null;for(const J of F.labelMarked)Kn(f.current,F.transcript.argsByCall,J,Vn(F))||(G=G??new Set(F.labelMarked),G.delete(J));if(Z.size===0&&!G)return F;const oe=new Set(F.labelPending);for(const J of Z)oe.delete(J);return{...F,labelPending:oe.size?oe:tt,labelMarked:G&&G.size===0?At:G??F.labelMarked}})},Go=j=>{c(F=>{let Z=null,G=null;for(const oe of j)F.labelPending.has(oe)&&(Z=Z??new Set(F.labelPending),Z.delete(oe),G=G??new Set(F.labelMarked),G.add(oe));return!Z||!G?F:{...F,labelPending:Z.size?Z:tt,labelMarked:G}})},Ln=async(j,F,Z=Qr,G=1,oe)=>{for(const ve of Z.targets)f.current.inFlight.add(ve),p.current.add(ve);let J=!1;try{J=await Ho(j,F,Z,G,oe)}finally{if(!J){for(const ve of Z.targets)f.current.inFlight.delete(ve);f.current.refused&&Go(Z.targets),Dn()}}},Ho=async(j,F,Z,G,oe)=>{const J=new Set;let ve,lt=0,dt=0,Qe=!1,ut=!1;const xe=new Set(Z.found),Xe=()=>Zd(Z.order,Z.targets,xe),ft=()=>no(Z.order,Z.targets,xe),Je=()=>{const K=new Map;for(const L of v){if(xe.has(L))continue;const de=g.get(L);de!==void 0&&K.set(L,de)}return K},Ue=new Set(Z.every);for(const K of xe)Ue.add(K);const v=new Set,g=new Map;let q=1;const fe=Z.targets.size>0;let pt=Math.max(jr(Xe()),fe?f.current.depth:0),$=0;for(;lt<Yr&&dt<Ou;){dt+=1;let K;try{K=await ce({op:"sessions.history",sessionId:e,...ve?{beforeId:ve}:{},limit:Math.min(pt,Yr-lt)})}catch{if(o.current.transcript.records.length>0){if($++>0)return f.current.refused=!0,!1;continue}return G<Cu?(We=window.setTimeout(()=>{if(We=0,_.current!==j){Dn();return}Ln(j,F,Z,G+1,oe)},zr(G)),!0):(c(ee=>({...ee,status:"unavailable",failure:il,heldFrontend:null})),!1)}finally{Dn()}if(_.current!==j)return!1;f.current.refused=!1;const L=K.entries[0];lt+=K.entries.length,oe?.(K.entries.length),c(ee=>{const Ie=Rt(ee.transcript,K),ht=Gn(K.entries,Ue),Mn=new Set(ee.labelPending);for(const Ko of ht)Mn.delete(Ko);return{...ee,hydrated:!0,labelPending:Mn.size?Mn:tt,labelMarked:Su(ee.labelMarked,ht),transcript:Ie}}),e&&ve===void 0&&Ze.getState().resolveHeldFromServer(e,K.entries.map(ee=>ee.id),!K.cursor_missing);const de=Xe();for(const ee of Gn(K.entries,Ue))xe.add(ee),Ue.add(ee);if($d(K.entries)&&(ut=!0),fe){const ee=Ud(K.entries,Ue);for(const Ie of ee)v.add(Ie),Ue.add(Ie);for(const[Ie,ht]of Nd(K.entries,ee))g.set(Ie,ht);for(const Ie of[...v])xe.has(Ie)&&v.delete(Ie);v.size>0&&q--<=0&&v.clear()}Qe=Qe||F.size===0||K.entries.some(ee=>F.has(ee.id)||J.has(ee.id));for(const ee of K.entries)J.add(ee.id);const Fe=Xe()+v.size;if(fe&&Xe()<de&&(f.current.depth=Math.min($s,Math.max(f.current.depth,lt))),fe){const ee=ft();if(Md(K.entries,ee,Z.starts,Je(),new Set(ee.filter(ht=>Z.waiting.has(ht))))||ut)return!1}if(Fd(Qe,Fe)||!L||!K.has_more)return!1;ve=L.id,pt=Fe>0?jr(Fe):fs}return!1},Ks=()=>{if(te&&cancelAnimationFrame(te),W&&clearTimeout(W),te=0,W=0,_.current!==k)return;const j=d.current;if(d.current=[],j.length===0)return;bu(j);const F=v=>{const q=v.payload.history.entries.at(-1);return q?Yu(v.payload)?!0:q.id===v.payload.frontend.snapshot.history_cursor?!1:u.current.has(q.id):!1},Z=v=>v!=null&&u.current.has(v),G=j.some(v=>v.type==="attention"?!Z(v.payload.anchor_id):v.type==="snapshot"&&!F(v)),oe=new Set(o.current.transcript.argsByCall.keys()),J=[],ve=new Set;for(const v of j)if(v.type==="snapshot"){for(const g of v.payload.history.entries){ve.add(g.id);const q=g.payload?.tool_calls;if(Array.isArray(q))for(const fe of q)fe&&typeof fe.id=="string"&&oe.add(fe.id)}for(const g of v.payload.frontend.snapshot.live_events??[]){const q=g.message;typeof q?.id=="string"&&ve.add(q.id)}J.push(...v.payload.frontend.snapshot.live_events??[])}const lt=j.some(v=>v.type==="event"&&Kr.has(String(v.payload.type??""))),dt=Mr(f.current.attempts,Nr(J,oe),oe,Wr),Qe=lt?Mr(f.current.attempts,[...f.current.attempts.keys(),...f.current.settled],oe,Wr):[],ut=[];for(const v of j){if(v.type!=="event")continue;const g=v.payload;String(g.type??"")==="tool_execution_end"&&String(g.tool_call_id??"")&&ut.push(g)}const xe=[];for(const v of ut){const g=String(v.tool_call_id??"");oe.has(g)||f.current.settled.has(g)||xe.push(g)}for(const v of xe)f.current.settled.add(v);for(;f.current.settled.size>Vr;){const v=f.current.settled.values().next().value;if(v===void 0)break;f.current.settled.delete(v)}for(const[v,g]of Lr(ut))f.current.starts.set(v,g);for(;f.current.starts.size>Xr;){const v=f.current.starts.keys().next().value;if(v===void 0)break;f.current.starts.delete(v)}const Xe=f.current.settleRows<Au?xe:[],ft=[...new Set([...dt,...Qe,...Xe])],Je=ft.filter(v=>!f.current.painted.has(v));if(J.length>0){f.current.order=Nr(J,new Set);for(const[v,g]of Lr(J))f.current.starts.set(v,g);for(;f.current.starts.size>Xr;){const v=f.current.starts.keys().next().value;if(v===void 0)break;f.current.starts.delete(v)}for(const v of Dd(J))f.current.waiting.add(v);for(const v of Bd(J))f.current.waiting.delete(v);for(;f.current.waiting.size>Nu;){const v=f.current.waiting.values().next().value;if(v===void 0)break;f.current.waiting.delete(v)}}for(const v of[...f.current.attempts.keys()])oe.has(v)&&f.current.attempts.delete(v);for(Zo([...dt,...Qe]);f.current.attempts.size>Vr;){const v=f.current.attempts.keys().next().value;if(v===void 0)break;f.current.attempts.delete(v)}if(performance.mark("lop:transcript:flush:start"),c(v=>{let g={...v},q=g.frontend!==null,fe=null;const pt=Date.now();for(const $ of j){if($.type==="heartbeat")continue;if($.type==="gap"){g={...g,frontend:null,heldFrontend:g.frontend??g.heldFrontend,history:null,terminal:null,status:"reconnecting",transcript:$r(g.transcript)},q=!1;continue}const K=w.current;if(($.type==="open"||"seq"in $)&&(w.current={epoch:$.epoch,seq:$.seq},g={...g,receipt:w.current}),$.type==="open"){if(g={...g,subscriptionId:$.payload.subscription_id},$.payload.gap){const L=g.frontend??g.heldFrontend;g={...g,frontend:null,heldFrontend:L,history:null,transcript:$r(g.transcript)},L&&g.status==="live"&&(g={...g,status:"reconnecting"}),q=!1}continue}if(!q){if($.type==="event"&&(fe=us(fe??g.transcript,$.payload,pt,{frame:{epoch:$.epoch,seq:$.seq}})),$.type==="snapshot"){const L=$.payload;let de=fe??g.transcript;L.history.cursor_missing||(de=Rt(de,L.history)),e&&Ze.getState().resolveHeldFromServer(e,L.history.entries.map(Fe=>Fe.id),!L.history.cursor_missing),de=Pd(de,L.frontend.snapshot,pt,{epoch:$.epoch,seq:$.seq}),g={...g,subagentPulses:vu(L.frontend.snapshot.live_events),status:"live",stale:!1,frontend:{...L.frontend.snapshot,attention:vt(g.frontend?.attention,L.frontend.snapshot.attention,e)},history:L.history,cold:L.cold,ownerEpoch:L.frontend.epoch,failure:null,hydrated:g.hydrated||!L.history.cursor_missing&&L.history.entries.length>0,transcript:de},q=!0,fe=null}continue}if($.type==="attention"){g.frontend&&(g={...g,frontend:{...g.frontend,attention:vt(g.frontend.attention,$.payload,e)}});continue}if($.type==="frontend.update"){const L=$.payload;if(!g.frontend)continue;const de=L.epoch!==g.ownerEpoch&&L.changes.epoch===L.epoch;(de||L.epoch===g.ownerEpoch&&g.frontend.sequence<L.sequence)&&(g={...g,ownerEpoch:de?L.epoch:g.ownerEpoch,frontend:{...g.frontend,...L.changes,attention:vt(g.frontend.attention,L.changes.attention,e),sequence:L.sequence}});continue}if($.type==="frontend.replace"){if(g.frontend&&ml(K,e,$)){const L=$.payload.frontend;g={...g,frontend:{...L.snapshot,attention:vt(g.frontend.attention,L.snapshot.attention,e)},ownerEpoch:L.epoch,cold:$.payload.cold}}continue}if($.type==="event"){const L=String($.payload.type??"");ku.has(L)&&(g={...g,terminal:L}),Kr.has(L)&&(g={...g,turnsCompleted:g.turnsCompleted+1});const de=us(g.transcript,$.payload,pt,{frame:{epoch:$.epoch,seq:$.seq},userStoppedAt:e?Ze.getState().stoppedTurns[e]??null:null});de!==g.transcript&&(g={...g,transcript:de});const Fe=_u(g.subagentPulses,$.payload);Fe!==g.subagentPulses&&(g={...g,subagentPulses:Fe})}}if(!q&&fe&&(g={...g,transcript:fe}),performance.mark("lop:transcript:flush:end"),performance.measure("lop:transcript:flush","lop:transcript:flush:start","lop:transcript:flush:end"),u.current=g.transcript.index,!wu(j))return v;if(Je.length>0){const $=new Set(g.labelPending);for(const K of Je)$.add(K);g={...g,labelPending:$}}return g.frontend!==null&&g.frontend!==g.heldFrontend&&(g={...g,heldFrontend:g.frontend}),g}),Je.length>0){for(const v of Je)f.current.painted.add(v);for(;f.current.painted.size>Lu;){const v=f.current.painted.values().next().value;if(v===void 0)break;f.current.painted.delete(v)}}const Ue=Xe.length>0&&dt.length===0&&Qe.length===0&&!G;if(G||ft.length>0){const v=new Set(ft),g=f.current.order;Ln(k,ve,ft.length>0?{targets:v,order:g,starts:f.current.starts,waiting:f.current.waiting,every:new Set([...g,...v]),found:new Set(Gn(j.flatMap(q=>q.type==="snapshot"?q.payload.history.entries:[]),new Set(g))),pending:Je}:Qr,1,Ue?q=>{f.current.settleRows+=q}:void 0)}},Nn=()=>{const j=P;if(P=null,!!j){U=!0;try{j()}finally{U=!1}}},Jt=()=>{Xt(),Tt=window.setTimeout(()=>{Tt=0,_.current===k&&(Nn(),c(j=>({...j,subscriptionId:null,status:"unavailable",failure:kr(Pt.ended),heldFrontend:null})),!Pn&&(Pn=!0,Ye=window.setTimeout(()=>{Ye=0,_.current===k&&Ws()},Iu)))},xu),P=ul({sessionId:e,epoch:E.current.epoch,afterSeq:E.current.afterSeq},j=>{if(_.current===k){if(j.kind==="error"||j.kind==="end"){if(U)return;if(Xt(),Nn(),j.kind==="error"&&j.status===404){e&&(du(e),mu(e)),c(G=>({...G,subscriptionId:null,status:"unavailable",missing:!0,failure:null,heldFrontend:null}));return}const F=j.kind==="error"?j.detail??"The event stream failed.":"The event stream closed unexpectedly.";if(c(G=>({...G,subscriptionId:null})),me>=Eu){c(G=>({...G,status:"unavailable",failure:kr(F),heldFrontend:null}));return}me+=1;const Z=w.current;Z&&(E.current={epoch:Z.epoch,afterSeq:Z.seq}),c(G=>G.status==="unavailable"&&me>1?G:{...G,status:"reconnecting",failure:null}),ie=window.setTimeout(()=>{ie=0,_.current===k&&Jt()},zr(me));return}if(j.data!==void 0)try{const F=JSON.parse(j.data);F.type==="snapshot"&&(me=0,Xt(),Pn=!1),d.current.push(F),te||(te=requestAnimationFrame(Ks)),W||(W=window.setTimeout(Ks,Ru))}catch{}}})},zo=()=>{ie!==0&&(window.clearTimeout(ie),ie=0),E.current={},w.current=null,Nn(),Jt()},Ws=()=>{me=0,Ye&&(window.clearTimeout(Ye),Ye=0),ie&&(window.clearTimeout(ie),ie=0),We&&(window.clearTimeout(We),We=0),c(j=>({...j,failure:null,status:j.status==="unavailable"?"connecting":j.status})),o.current.hydrated||Ln(k,new Set(o.current.transcript.index.keys())),!P&&Jt()};Jt(),h.current=Ws;const Vo=ju(e,zo);return()=>{_.current+=1,h.current=null,Vo(),P?.(),te&&cancelAnimationFrame(te),W&&clearTimeout(W),ie&&clearTimeout(ie),We&&clearTimeout(We),x.current&&(window.clearTimeout(x.current),x.current=0),I.current&&(window.clearTimeout(I.current),I.current=0),Ye&&window.clearTimeout(Ye),Xt(),d.current=[]}},[c,e,t]),T.useEffect(()=>{E.current={},w.current=null,u.current=Be.index;const k=Vu(l.current,e,n);l.current=e;const P=e?ao(e):null;c(U=>({...U,frontend:null,heldFrontend:k?U.heldFrontend:null,pendingModel:null,history:null,terminal:null,turnsCompleted:k?U.turnsCompleted:0,transcript:k?U.transcript:P?.transcript??Be,stale:k?U.stale:P!==null,missing:k?U.missing:!1,status:"connecting",subagentPulses:{},labelPending:P?.owedLabels??tt,labelMarked:P?.markLabels??At,labelHoldLate:!1,hydrated:!1,loadingOlder:!1})),f.current=Jr(e)},[e,n]),T.useEffect(()=>{if(e)return()=>{const k=o.current.transcript;k.records.length>0&&lu(e,{transcript:k,owedLabels:new Set([...o.current.labelPending].filter(P=>Kn(f.current,o.current.transcript.argsByCall,P,Vn(o.current)))),markLabels:new Set(o.current.labelMarked)});for(const P of p.current)f.current.inFlight.delete(P);p.current.clear()}},[e]);const x=T.useRef(0);T.useEffect(()=>{if(r.labelPending.size===0&&r.labelMarked.size===0){x.current&&(window.clearTimeout(x.current),x.current=0);return}if(x.current)return;const k=()=>{x.current=0;const P=o.current.labelPending,U=o.current.labelMarked;if(P.size===0&&U.size===0)return;const te=f.current;for(const W of P)if(te.inFlight.has(W)){x.current=window.setTimeout(k,zn);return}for(const W of U)if(te.inFlight.has(W)){x.current=window.setTimeout(k,zn);return}c(W=>W.labelPending.size===0&&W.labelMarked.size===0?W:{...W,labelPending:tt,labelMarked:At})};x.current=window.setTimeout(k,zn)},[c,r.labelPending,r.labelMarked]);const I=T.useRef(0);T.useEffect(()=>{if(r.labelPending.size===0){I.current&&(window.clearTimeout(I.current),I.current=0),c(k=>k.labelHoldLate?{...k,labelHoldLate:!1}:k);return}r.labelHoldLate||I.current||(I.current=window.setTimeout(()=>{I.current=0,c(k=>k.labelPending.size===0||k.labelHoldLate?k:{...k,labelHoldLate:!0})},Pu))},[c,r.labelPending,r.labelHoldLate]);const re=T.useRef(e);re.current=e;const H=T.useRef(!1),ae=T.useRef({session:null,cursor:null});ae.current.session!==e&&(ae.current={session:e??null,cursor:null});const Te=T.useCallback(async()=>{if(!e||H.current)return!1;const{transcript:k}=o.current;if(!k.hasMore||!k.oldestId)return!1;const P=e;H.current=!0,c(U=>({...U,loadingOlder:!0}));try{const U=ie=>ce({op:"sessions.history",sessionId:P,beforeId:ie,limit:100}),te=ae.current.cursor??k.oldestId;let W=await U(te),me=Dr(W,te,!1);return me.cursor!==null&&(ae.current={session:P,cursor:me.cursor},W=await U(me.cursor),me=Dr(W,me.cursor,!0)),ae.current={session:P,cursor:me.cursor},me.failed?(c(ie=>({...ie,loadingOlder:!1})),!1):re.current!==P?(c(ie=>({...ie,loadingOlder:!1})),!1):(c(ie=>({...ie,loadingOlder:!1,transcript:Rt(ie.transcript,W)})),!0)}catch{return c(U=>({...U,loadingOlder:!1})),!1}finally{H.current=!1}},[c,e]),M=T.useRef(!1),z=T.useCallback(async(k,P)=>{if(!e||M.current)return!1;const U=e;M.current=!0;try{const te=await ce({op:"sessions.history",sessionId:U,limit:100});return re.current!==U||o.current.transcript.viewEpoch!==P?!1:(c(W=>({...W,transcript:Rt(W.transcript,te,{keepPaging:!0})})),Qd(te.entries,k))}catch{return!1}finally{M.current=!1}},[c,e]);T.useEffect(()=>s?Hu(s,P=>{c(U=>{const te=P(U.transcript);return te===U.transcript?U:{...U,transcript:te}})}):void 0,[c,s]),T.useEffect(()=>{s&&Gu(s,r.transcript)},[s,r.transcript]);const V=T.useCallback(()=>{c(k=>({...k,transcript:Gd(k.transcript),heldFrontend:null}))},[c]),le=T.useCallback(()=>{h.current?.()},[]),he=T.useCallback((k,P="info")=>{c(U=>({...U,transcript:Kd(U.transcript,k,P)}))},[c]),Ee=T.useCallback(k=>{c(P=>({...P,pendingModel:k}))},[c]),Qt=T.useCallback(()=>{c(k=>k.pendingModel===null?k:{...k,pendingModel:null})},[c]);return T.useEffect(()=>{const k=r.pendingModel;if(!k)return;const P=Hn(k);if(!P)return;const U=r.frontend;(Hn(U?.selected_model)===P||Hn(U?.effective_model)===P)&&c(te=>({...te,pendingModel:null}))},[c,r.frontend,r.pendingModel]),T.useEffect(()=>{if(!r.pendingModel)return;const k=window.setTimeout(()=>c(P=>({...P,pendingModel:null})),Tu);return()=>window.clearTimeout(k)},[c,r.pendingModel]),T.useMemo(()=>({...r,awaitingHydration:t&&!!e&&n&&!r.hydrated,loadOlder:Te,refreshTail:z,clearView:V,addNote:he,paintPendingModel:Ee,clearPendingModel:Qt,retry:le}),[r,t,e,n,Te,z,V,he,Ee,Qt,le])}function Rn(e,t){return t===""?e:e===""?t:e===t||e.startsWith(`${t}
|
|
15
15
|
|
|
16
16
|
`)?e:`${t}
|
|
17
17
|
|
|
18
|
-
${e}`}const Wn={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function dn(e,t,n){const s=[...e.attachments??[]],r=[],i=[],o=new Set;for(const p of t.attachments){const w=s.find(h=>h.path===p&&!o.has(h.id));if(w){o.add(w.id),i.push(w.id);continue}const E={id:n(),path:p};r.push(E),i.push(E.id)}const c=[...e.replies??[]],l=t.replies.filter(p=>!c.some(w=>w.id===p.id)),d=t.text,u=[...r,...s],f=[...l,...c];return{...e,attachments:u,replies:f,textRevision:(e.textRevision??0)+1,volatilePendingText:e.volatilePendingText===!0||t.volatileText===!0,pendingText:d===""?e.pendingText:Rn(e.pendingText??"",d),unredactedChars:Math.max(e.unredactedChars??0,t.unredactedChars??0),returned:{text:d,chipIds:i,replyIds:t.replies.map(p=>f.find(w=>w.id===p.id)?.id).filter(p=>p!==void 0),volatileText:t.volatileText},inFlight:void 0,lateDelivered:void 0}}function Ku(e,t){const n=e.lateDeliveredText??e.returned?.text;if(!n||t.includes(n))return!0;const s=Math.max(8,Math.min(24,Math.floor(n.length/3)));for(let r=0;r+s<=n.length;r++)if(t.includes(n.slice(r,r+s)))return!0;return!1}function Wu(e){return{text:Rn(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function Yu(e,t){if(!e||!t)return!1;const n=Wu(e),s=e.attachments??[],r=e.replies??[];return n.text.trim()===t.text.trim()&&s.length===t.chipIds.length&&s.every((i,o)=>i.id===t.chipIds[o])&&r.length===t.replyIds.length&&r.every((i,o)=>i.id===t.replyIds[o])}function Qu(e,t=()=>crypto.randomUUID()){const n={};for(const[s,r]of Object.entries(e??{}))n[s]=r.inFlight?dn(r,r.inFlight,t):r;return n}function Xu(e,t){const n=t.text,s=Rn(e.currentInput??"",e.pendingText??"");let r=s,i="overlap";n===""?i="draft-only":s.startsWith(n)&&(r=s.slice(n.length).replace(/^\n+/,""),i="draft-only");const o=new Set(t.chipIds),c=new Set(t.replyIds);return{row:{...e,currentInput:r,pendingText:void 0,attachments:(e.attachments??[]).filter(l=>!o.has(l.id)),replies:(e.replies??[]).filter(l=>!c.has(l.id)),unredactedChars:n===""?e.unredactedChars??0:0},box:i}}const Ce=As()(gi((e,t)=>({inputByConversation:{},addReply:(n,s)=>{const r=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=Array.isArray(r.replies)?r.replies:[];e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:[...i,s]}}})},removeReply:(n,s)=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:r.replies.filter(i=>i.id!==s)}}})},clearReplies:n=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,replies:[]}}})},addAttachment:(n,s)=>{const r=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=Array.isArray(r.attachments)?r.attachments:[];e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:[...i,s]}}})},removeAttachment:(n,s)=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:r.attachments.filter(i=>i.id!==s)}}})},clearAttachments:n=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,attachments:[]}}})},setCurrentInput:(n,s,r=0)=>{const i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...i,lateDelivered:i.lateDelivered==="overlap"&&!Ku(i,s)?void 0:i.lateDelivered,currentInput:s,unredactedChars:s?r:0}}})},getUnredactedChars:n=>t().inputByConversation[n]?.unredactedChars||0,getCurrentInput:n=>t().inputByConversation[n]?.currentInput||"",addSubmittedMessage:(n,s)=>{const r=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=r.submittedMessages[r.submittedMessages.length-1],o=s&&s!==i?[...r.submittedMessages.slice(-19),s]:r.submittedMessages;e({inputByConversation:{...t().inputByConversation,[n]:{...r,submittedMessages:o}}})},getSubmittedMessages:n=>t().inputByConversation[n]?.submittedMessages||[],clearSubmittedMessages:n=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,submittedMessages:[]}}})},getCurrentHistoryIndex:n=>t().inputByConversation[n]?.currentHistoryIndex??null,setCurrentHistoryIndex:(n,s)=>{const r=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=r.submittedMessages;let o=null;typeof s=="number"&&i.length>0&&(o=Math.max(0,Math.min(s,i.length-1))),e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentHistoryIndex:o}}})},resetCurrentHistoryIndex:n=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentHistoryIndex:null}}})},clearAll:n=>{const{[n]:s,...r}=t().inputByConversation;e({inputByConversation:r})},restoreRow:(n,s)=>{e({inputByConversation:{...t().inputByConversation,[n]:{...s,textRevision:(s.textRevision??0)+1}}})},beginInFlight:(n,s,r=!0)=>{const i=t().inputByConversation[n]??Wn,o=new Set(s.attachments.map(d=>d.id)),c=new Set(s.replies.map(d=>d.id)),l=i.currentInput===s.text;e({inputByConversation:{...t().inputByConversation,[n]:{...i,currentInput:l?"":i.currentInput,unredactedChars:l?0:i.unredactedChars,textRevision:l?(i.textRevision??0)+1:i.textRevision,attachments:(i.attachments??[]).filter(d=>!o.has(d.id)),replies:(i.replies??[]).filter(d=>!c.has(d.id)),inFlight:r?{text:s.text,attachments:s.attachments.map(d=>d.path),replies:[...s.replies],unredactedChars:l?i.unredactedChars:0,volatileText:s.volatileText}:i.inFlight,returned:void 0,lateDelivered:void 0}}})},settleInFlight:n=>{const s={...t().inputByConversation};let r=!1;for(const i of n){const o=s[i];!o||!o.inFlight&&!o.returned||(s[i]={...o,inFlight:void 0,returned:void 0},r=!0)}r&&e({inputByConversation:s})},returnInFlight:(n,s)=>{const r={...t().inputByConversation},i=r[n],o=i?.inFlight??r[s]?.inFlight;let c=r[s]??Wn;n!==s&&i&&(c=dn(c,{text:i.currentInput??"",attachments:(i.attachments??[]).map(l=>l.path),replies:i.replies??[],unredactedChars:i.unredactedChars},()=>crypto.randomUUID()),c={...c,returned:r[s]?.returned},delete r[n]),o&&(c=dn(c,o,()=>crypto.randomUUID())),!(!o&&n===s)&&(r[s]=c,e({inputByConversation:r}))},adoptReturnedText:n=>{const s=t().inputByConversation[n];if(s?.pendingText===void 0)return null;const r=Rn(s.currentInput??"",s.pendingText);return e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentInput:r,pendingText:void 0,textRevision:(s.textRevision??0)+1}}}),r},returnPayload:(n,s)=>{const r=t().inputByConversation[n]??Wn;r.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:dn(r,s,()=>crypto.randomUUID())}})},reconcileDelivered:n=>{const s=t().inputByConversation[n];if(!s)return;const r=f=>(f.currentInput??"")===""&&(f.attachments??[]).length===0&&(f.replies??[]).length===0,i=s.returned!==void 0||s.inFlight!==void 0,o=s.returned?Yu(s,s.returned):r(s),c=s.returned?Xu(s,s.returned):null,l={...s,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,volatilePendingText:void 0,textRevision:(s.textRevision??0)+1},d=(c?.row.currentInput??"")==="",u=c&&!r(c.row)?{...c.row,returned:void 0,inFlight:void 0,volatilePendingText:d?void 0:s.volatilePendingText,lateDelivered:c.box==="overlap"&&d?"draft-only":c.box,lateDeliveredText:c.box==="overlap"&&!d?s.returned?.text:void 0,textRevision:(s.textRevision??0)+1}:{...s,returned:void 0,inFlight:void 0,lateDelivered:i&&s.returned?.text?"overlap":i?"delivered":void 0,lateDeliveredText:i?s.returned?.text:void 0};e({inputByConversation:{...t().inputByConversation,[n]:o||c!==null&&r(c.row)?l:u}})},dismissLateDelivery:n=>{const s=t().inputByConversation[n];s?.lateDelivered&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,lateDelivered:void 0,lateDeliveredText:void 0}}})},clearComposer:n=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,volatilePendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,textRevision:(s.textRevision??0)+1}}})}}),{name:"conversation-input-store",partialize:e=>({inputByConversation:Object.fromEntries(Object.entries(e.inputByConversation).map(([t,n])=>{let s=n;return s.inFlight?.volatileText&&(s={...s,inFlight:{...s.inFlight,text:""}}),s.returned?.volatileText&&(s={...s,returned:{...s.returned,text:""}}),s.volatilePendingText&&(s={...s,pendingText:void 0}),s.volatilePendingText&&(s={...s,lateDeliveredText:void 0}),[t,s]}))}),merge:(e,t)=>({...t,inputByConversation:Qu(e?.inputByConversation)})})),an=(e,t)=>e instanceof X?In(e,t):e instanceof Error?e.message:t,An="session_unvalidated",Ju="This chat is not ready for messages yet, so the message was not sent. Sending works once it is ready.",kn="leading_slash_message",uo="A message can't start with / — that is a command. Move it below your text, or send it on its own.";function qu(e,t){return e instanceof X&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const fo="attachment_read_failed",po="store_out_of_space",ho="store_unavailable";function ei(e){return e===po||e===ho}const ef="answer_not_sent",mo="aside_not_answered",go="aside_still_answering";function Ot(e){return e===kn||e===fo||e===po||e===ho||e===ef||e===mo||e===go||e===An}function tf(e){return e instanceof X&&e.status===409&&Bs(e)===void 0}function yo(e,t=!1){return rf(e)||tf(e)&&!t?"not_sent":e instanceof X&&e.status===404?"gone":"unknown"}function Bs(e){if(e instanceof X||e instanceof at)return e.code;if(e&&typeof e=="object"&&"code"in e){const t=e.code;if(typeof t=="string")return t}}const ge={unconfirmed:"Couldn't confirm your message was sent. Sending it again is safe.",unreachable:"Couldn't reach Local Operator. Your message may not have been sent.",busy:"The agent is busy, so your message wasn't sent.",asideNotAnswered:"The aside was not answered.",asideStillAnswering:"The aside is still answering. Press Enter again once the answer is in.",retiring:"Local Operator is restarting, so your message wasn't sent. Try again in a moment.",notReady:"This chat isn't ready yet, so your message wasn't sent.",generic:"Your message wasn't sent.",gone:"This conversation no longer exists, so your message wasn't sent.",sendLock:"Your last message is still sending.",queuedSend:"Your message will send as soon as the conversation is ready.",gateLock:"Answer the question above first.",lateDelivery:"Your earlier message was delivered.",lateDeliveryDraft:"Your earlier message was delivered. What's here now hasn't been sent.",lateDeliveryOverlap:"Your earlier message was delivered. Its words are still in the box, so sending again would repeat them."};function im(e){return e?ge.gateLock:ge.sendLock}const om="Retry",am="Clear";function nf(e,t,n=!1){const s=yo(e,n),r=t??Bs(e),i=In(e,ge.generic);return s==="gone"?{message:ge.gone,retry:!1,code:r}:s==="not_sent"?r===Ps?{message:ge.busy,retry:!0,code:r}:r===Ri?{message:ge.retiring,retry:!0,code:r}:r===An?{message:ge.notReady,retry:!Ot(r),code:r}:r===mo?{message:ge.asideNotAnswered,retry:!1,code:r}:r===go?{message:ge.asideStillAnswering,retry:!1,code:r}:r===kn?{message:uo,retry:!1,code:r}:{message:i,retry:!1,code:r}:r===_e.transportFailed?{message:ge.unreachable,retry:!0,code:r}:Ls(r)?{message:Ds[r],retry:!1,code:r}:r===Ns?{message:ge.unconfirmed,retry:!Ot(r),code:r}:r===Rc.runtimeUnreachable?{message:ge.unconfirmed,retry:!0,code:r}:r?{message:i,retry:!Ot(r),code:r}:{message:ge.unconfirmed,retry:!Ot(r),code:r}}function ys(e){return e.trim()}function cm(e,t){if(t.length===0)return ys(e);const n=t.map(s=>`<reply-to>${s.text}</reply-to>`).join(`
|
|
18
|
+
${e}`}const Wn={currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};function dn(e,t,n){const s=[...e.attachments??[]],r=[],i=[],o=new Set;for(const p of t.attachments){const w=s.find(h=>h.path===p&&!o.has(h.id));if(w){o.add(w.id),i.push(w.id);continue}const E={id:n(),path:p};r.push(E),i.push(E.id)}const c=[...e.replies??[]],l=t.replies.filter(p=>!c.some(w=>w.id===p.id)),d=t.text,u=[...r,...s],f=[...l,...c];return{...e,attachments:u,replies:f,textRevision:(e.textRevision??0)+1,volatilePendingText:e.volatilePendingText===!0||t.volatileText===!0,pendingText:d===""?e.pendingText:Rn(e.pendingText??"",d),unredactedChars:Math.max(e.unredactedChars??0,t.unredactedChars??0),returned:{text:d,chipIds:i,replyIds:t.replies.map(p=>f.find(w=>w.id===p.id)?.id).filter(p=>p!==void 0),volatileText:t.volatileText},inFlight:void 0,lateDelivered:void 0}}function Qu(e,t){const n=e.lateDeliveredText??e.returned?.text;if(!n||t.includes(n))return!0;const s=Math.max(8,Math.min(24,Math.floor(n.length/3)));for(let r=0;r+s<=n.length;r++)if(t.includes(n.slice(r,r+s)))return!0;return!1}function Xu(e){return{text:Rn(e.currentInput??"",e.pendingText??""),attachments:(e.attachments??[]).map(t=>t.path),replies:e.replies??[]}}function Ju(e,t){if(!e||!t)return!1;const n=Xu(e),s=e.attachments??[],r=e.replies??[];return n.text.trim()===t.text.trim()&&s.length===t.chipIds.length&&s.every((i,o)=>i.id===t.chipIds[o])&&r.length===t.replyIds.length&&r.every((i,o)=>i.id===t.replyIds[o])}function qu(e,t=()=>crypto.randomUUID()){const n={};for(const[s,r]of Object.entries(e??{}))n[s]=r.inFlight?dn(r,r.inFlight,t):r;return n}function ef(e,t){const n=t.text,s=Rn(e.currentInput??"",e.pendingText??"");let r=s,i="overlap";n===""?i="draft-only":s.startsWith(n)&&(r=s.slice(n.length).replace(/^\n+/,""),i="draft-only");const o=new Set(t.chipIds),c=new Set(t.replyIds);return{row:{...e,currentInput:r,pendingText:void 0,attachments:(e.attachments??[]).filter(l=>!o.has(l.id)),replies:(e.replies??[]).filter(l=>!c.has(l.id)),unredactedChars:n===""?e.unredactedChars??0:0},box:i}}const Ce=As()(gi((e,t)=>({inputByConversation:{},addReply:(n,s)=>{const r=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=Array.isArray(r.replies)?r.replies:[];e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:[...i,s]}}})},removeReply:(n,s)=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,replies:r.replies.filter(i=>i.id!==s)}}})},clearReplies:n=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,replies:[]}}})},addAttachment:(n,s)=>{const r=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=Array.isArray(r.attachments)?r.attachments:[];e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:[...i,s]}}})},removeAttachment:(n,s)=>{const r=t().inputByConversation[n];r&&e({inputByConversation:{...t().inputByConversation,[n]:{...r,attachments:r.attachments.filter(i=>i.id!==s)}}})},clearAttachments:n=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,attachments:[]}}})},setCurrentInput:(n,s,r=0)=>{const i=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]};e({inputByConversation:{...t().inputByConversation,[n]:{...i,lateDelivered:i.lateDelivered==="overlap"&&!Qu(i,s)?void 0:i.lateDelivered,currentInput:s,unredactedChars:s?r:0}}})},getUnredactedChars:n=>t().inputByConversation[n]?.unredactedChars||0,getCurrentInput:n=>t().inputByConversation[n]?.currentInput||"",addSubmittedMessage:(n,s)=>{const r=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=r.submittedMessages[r.submittedMessages.length-1],o=s&&s!==i?[...r.submittedMessages.slice(-19),s]:r.submittedMessages;e({inputByConversation:{...t().inputByConversation,[n]:{...r,submittedMessages:o}}})},getSubmittedMessages:n=>t().inputByConversation[n]?.submittedMessages||[],clearSubmittedMessages:n=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,submittedMessages:[]}}})},getCurrentHistoryIndex:n=>t().inputByConversation[n]?.currentHistoryIndex??null,setCurrentHistoryIndex:(n,s)=>{const r=t().inputByConversation[n]||{currentInput:"",submittedMessages:[],currentHistoryIndex:null,replies:[],attachments:[]},i=r.submittedMessages;let o=null;typeof s=="number"&&i.length>0&&(o=Math.max(0,Math.min(s,i.length-1))),e({inputByConversation:{...t().inputByConversation,[n]:{...r,currentHistoryIndex:o}}})},resetCurrentHistoryIndex:n=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentHistoryIndex:null}}})},clearAll:n=>{const{[n]:s,...r}=t().inputByConversation;e({inputByConversation:r})},restoreRow:(n,s)=>{e({inputByConversation:{...t().inputByConversation,[n]:{...s,textRevision:(s.textRevision??0)+1}}})},beginInFlight:(n,s,r=!0)=>{const i=t().inputByConversation[n]??Wn,o=new Set(s.attachments.map(d=>d.id)),c=new Set(s.replies.map(d=>d.id)),l=i.currentInput===s.text;e({inputByConversation:{...t().inputByConversation,[n]:{...i,currentInput:l?"":i.currentInput,unredactedChars:l?0:i.unredactedChars,textRevision:l?(i.textRevision??0)+1:i.textRevision,attachments:(i.attachments??[]).filter(d=>!o.has(d.id)),replies:(i.replies??[]).filter(d=>!c.has(d.id)),inFlight:r?{text:s.text,attachments:s.attachments.map(d=>d.path),replies:[...s.replies],unredactedChars:l?i.unredactedChars:0,volatileText:s.volatileText}:i.inFlight,returned:void 0,lateDelivered:void 0}}})},settleInFlight:n=>{const s={...t().inputByConversation};let r=!1;for(const i of n){const o=s[i];!o||!o.inFlight&&!o.returned||(s[i]={...o,inFlight:void 0,returned:void 0},r=!0)}r&&e({inputByConversation:s})},returnInFlight:(n,s)=>{const r={...t().inputByConversation},i=r[n],o=i?.inFlight??r[s]?.inFlight;let c=r[s]??Wn;n!==s&&i&&(c=dn(c,{text:i.currentInput??"",attachments:(i.attachments??[]).map(l=>l.path),replies:i.replies??[],unredactedChars:i.unredactedChars},()=>crypto.randomUUID()),c={...c,returned:r[s]?.returned},delete r[n]),o&&(c=dn(c,o,()=>crypto.randomUUID())),!(!o&&n===s)&&(r[s]=c,e({inputByConversation:r}))},adoptReturnedText:n=>{const s=t().inputByConversation[n];if(s?.pendingText===void 0)return null;const r=Rn(s.currentInput??"",s.pendingText);return e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentInput:r,pendingText:void 0,textRevision:(s.textRevision??0)+1}}}),r},returnPayload:(n,s)=>{const r=t().inputByConversation[n]??Wn;r.inFlight||e({inputByConversation:{...t().inputByConversation,[n]:dn(r,s,()=>crypto.randomUUID())}})},reconcileDelivered:n=>{const s=t().inputByConversation[n];if(!s)return;const r=f=>(f.currentInput??"")===""&&(f.attachments??[]).length===0&&(f.replies??[]).length===0,i=s.returned!==void 0||s.inFlight!==void 0,o=s.returned?Ju(s,s.returned):r(s),c=s.returned?ef(s,s.returned):null,l={...s,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,volatilePendingText:void 0,textRevision:(s.textRevision??0)+1},d=(c?.row.currentInput??"")==="",u=c&&!r(c.row)?{...c.row,returned:void 0,inFlight:void 0,volatilePendingText:d?void 0:s.volatilePendingText,lateDelivered:c.box==="overlap"&&d?"draft-only":c.box,lateDeliveredText:c.box==="overlap"&&!d?s.returned?.text:void 0,textRevision:(s.textRevision??0)+1}:{...s,returned:void 0,inFlight:void 0,lateDelivered:i&&s.returned?.text?"overlap":i?"delivered":void 0,lateDeliveredText:i?s.returned?.text:void 0};e({inputByConversation:{...t().inputByConversation,[n]:o||c!==null&&r(c.row)?l:u}})},dismissLateDelivery:n=>{const s=t().inputByConversation[n];s?.lateDelivered&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,lateDelivered:void 0,lateDeliveredText:void 0}}})},clearComposer:n=>{const s=t().inputByConversation[n];s&&e({inputByConversation:{...t().inputByConversation,[n]:{...s,currentInput:"",unredactedChars:0,attachments:[],replies:[],pendingText:void 0,volatilePendingText:void 0,returned:void 0,inFlight:void 0,lateDelivered:void 0,lateDeliveredText:void 0,textRevision:(s.textRevision??0)+1}}})}}),{name:"conversation-input-store",partialize:e=>({inputByConversation:Object.fromEntries(Object.entries(e.inputByConversation).map(([t,n])=>{let s=n;return s.inFlight?.volatileText&&(s={...s,inFlight:{...s.inFlight,text:""}}),s.returned?.volatileText&&(s={...s,returned:{...s.returned,text:""}}),s.volatilePendingText&&(s={...s,pendingText:void 0}),s.volatilePendingText&&(s={...s,lateDeliveredText:void 0}),[t,s]}))}),merge:(e,t)=>({...t,inputByConversation:qu(e?.inputByConversation)})})),an=(e,t)=>e instanceof X?In(e,t):e instanceof Error?e.message:t,An="session_unvalidated",tf="This chat is not ready for messages yet, so the message was not sent. Sending works once it is ready.",kn="leading_slash_message",fo="A message can't start with / — that is a command. Move it below your text, or send it on its own.";function nf(e,t){return e instanceof X&&e.status===422&&e.code===void 0&&t.trimStart().startsWith("/")}const po="attachment_read_failed",ho="store_out_of_space",mo="store_unavailable";function ei(e){return e===ho||e===mo}const sf="answer_not_sent",go="aside_not_answered",yo="aside_still_answering";function Ot(e){return e===kn||e===po||e===ho||e===mo||e===sf||e===go||e===yo||e===An}function rf(e){return e instanceof X&&e.status===409&&Bs(e)===void 0}function vo(e,t=!1){return cf(e)||rf(e)&&!t?"not_sent":e instanceof X&&e.status===404?"gone":"unknown"}function Bs(e){if(e instanceof X||e instanceof Ke)return e.code;if(e&&typeof e=="object"&&"code"in e){const t=e.code;if(typeof t=="string")return t}}const ge={unconfirmed:"Couldn't confirm your message was sent. Sending it again is safe.",unreachable:"Couldn't reach Local Operator. Your message may not have been sent.",busy:"The agent is busy, so your message wasn't sent.",asideNotAnswered:"The aside was not answered.",asideStillAnswering:"The aside is still answering. Press Enter again once the answer is in.",retiring:"Local Operator is restarting, so your message wasn't sent. Try again in a moment.",notReady:"This chat isn't ready yet, so your message wasn't sent.",generic:"Your message wasn't sent.",gone:"This conversation no longer exists, so your message wasn't sent.",sendLock:"Your last message is still sending.",queuedSend:"Your message will send as soon as the conversation is ready.",gateLock:"Answer the question above first.",lateDelivery:"Your earlier message was delivered.",lateDeliveryDraft:"Your earlier message was delivered. What's here now hasn't been sent.",lateDeliveryOverlap:"Your earlier message was delivered. Its words are still in the box, so sending again would repeat them."};function lm(e){return e?ge.gateLock:ge.sendLock}const dm="Retry",um="Clear";function of(e,t,n=!1){const s=vo(e,n),r=t??Bs(e),i=In(e,ge.generic);return s==="gone"?{message:ge.gone,retry:!1,code:r}:s==="not_sent"?r===Ps?{message:ge.busy,retry:!0,code:r}:r===Ri?{message:ge.retiring,retry:!0,code:r}:r===An?{message:ge.notReady,retry:!Ot(r),code:r}:r===go?{message:ge.asideNotAnswered,retry:!1,code:r}:r===yo?{message:ge.asideStillAnswering,retry:!1,code:r}:r===kn?{message:fo,retry:!1,code:r}:{message:i,retry:!1,code:r}:r===_e.transportFailed?{message:ge.unreachable,retry:!0,code:r}:Ls(r)?{message:Ds[r],retry:!1,code:r}:r===Ns?{message:ge.unconfirmed,retry:!Ot(r),code:r}:r===Dc.runtimeUnreachable?{message:ge.unconfirmed,retry:!0,code:r}:r?{message:i,retry:!Ot(r),code:r}:{message:ge.unconfirmed,retry:!Ot(r),code:r}}function ys(e){return e.trim()}function fm(e,t){if(t.length===0)return ys(e);const n=t.map(s=>`<reply-to>${s.text}</reply-to>`).join(`
|
|
19
19
|
`);return ys(`${n}
|
|
20
|
-
${e}`)}function vs(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function lm(e,t,n){if(e)return e;if(!t)return null;const s=Object.entries(n).filter(([,i])=>vs(i,t));return(s.find(([,i])=>i.submittedText!==void 0||i.undelivered!==void 0||i.error!==void 0||i.admissionAttempted===!0||i.pending===!0)??s[0])?.[0]??`send:${t}`}function Zs(e,t){return t??e??void 0}function sf(e,t,n){return e?t??void 0:n??void 0}function dm(e,t,n){return Zs(e,sf(e,t,n))}function rf(e){return e instanceof X?e.status===413||e.status===422?!0:e.code===Ps||e.code===Ri||e.code===_e.noCredential||ei(e.code):e instanceof at&&(e.code===An||e.code===fo||ei(e.code))}function On(e,t){const n=e.startsWith("send:")?e.slice(5):null;return Zs(e.startsWith("draft:")?e:null,t??n)??e}function of(e,t){const n=Ce.getState(),s=On(e,t),r=s===""||s===e?[e]:[e,s];n.settleInFlight(r),s!==""&&s!==e&&n.inputByConversation[e]&&n.returnInFlight(e,s)}function um(e,t){if(!t||t.migratedHeld||t.pending||!(t.heldClaimCode!==void 0||t.errorRetry===void 0&&t.submittedRendered===void 0)||!t.admissionAttempted||t.submittedText===void 0)return!1;const s=On(e,t.sessionId);return Ce.getState().returnPayload(s,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),Ze.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:ge.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!Ot(t.heldClaimCode),heldClaimCode:void 0}),!0}function fm(e,t){if(!t)return!1;const n=t.undelivered,s=t.submittedText,r=s!==void 0&&t.error!==void 0&&t.errorRetry!==void 0;if(!n&&!r)return!1;const i=On(e,t.sessionId);if(n)return qr(i,n.recordId)?!1:(hs(i,{id:n.recordId,text:n.text,images:[],settled:!0,submittedAt:t.submittedAt}),!0);if(s===void 0)return!1;const o=t.admissionRequestId;return qr(i,o)?!1:(hs(i,{id:o,text:t.submittedRendered??s,submittedAt:t.submittedAt,images:(t.submittedImages??[]).map((c,l)=>({id:`${o}:${l}`,data:c.data_b64,attachment:null,mimeType:c.mime_type}))}),!0)}function af(e,t,n){if(e.submittedText!==t)return!1;const s=e.submittedAttachments??[];return s.length!==n.length?!1:s.every((r,i)=>r===n[i])}function cf(e,t){return!!t&&e===t}const lf=3,df=5e3,uf=2e3;async function ff(e){for(let t=0;;t++)try{await ce(e);return}catch(n){if(t>=lf||!(n instanceof X)||n.code!==Ps)throw n;const s=Math.min(Math.max(0,n.retryAfterMs??uf),df);await new Promise(r=>setTimeout(r,s))}}async function pm(e,t,n,s,r){const i=Ze.getState();if(cf(i.validatingSessionId,n))throw new at(Ju,An);const o=i.drafts[e];if(o?.pending)return null;const c=ys(t.text),l=o?.submittedText!==void 0&&af(o,c,t.attachments),d=o??{key:e,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()},u=l?o?.submittedImages??t.images:t.images,f=l?o?.submittedMode??t.mode:t.mode,p=l&&o?o.submittedInputMode:t.inputMode,w=l&&o?o.submittedInputPath:t.inputPath,E=o?.submittedText===void 0||l?o?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),h=Date.now();i.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:E,submittedRendered:l?o?.submittedRendered:void 0,migratedHeld:o?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedMode:f,submittedInputMode:p,submittedInputPath:w,error:void 0,errorCode:void 0,submittedAt:h});const _=Zs(e.startsWith("draft:")?e:null,n??d.sessionId)??null;_&&hs(_,{id:E,submittedAt:h,text:c,images:u.map((H,ae)=>({id:`${E}:${ae}`,data:H.data_b64,attachment:null,mimeType:H.mime_type})),onPainted:s});let x=l,I=n??d.sessionId,re=null;try{if(!I){if(re="sessions.create",I=await i.createSession(t.cwd,d.target,d.createRequestId,d.model??null,d.warmId)??void 0,!I)throw new at(Ze.getState().error??"Chat could not start.");i.updateDraft(e,{sessionId:I}),_&&Uu(_,I),i.fetchSessions()}const H=l&&o?.submittedRendered!==void 0?o.submittedRendered:r?await r(I)??c:c;return x=!0,i.updateDraft(e,{error:void 0,errorCode:void 0,errorRetry:void 0,admissionAttempted:!0,submittedRendered:H}),I&&$u(I,E,H),re="sessions.message",await ff({op:"sessions.message",sessionId:I,requestId:E,text:H,images:u.length?u:void 0,mode:f,inputMode:p,inputPath:w}),i.finishDraft(e,I),Ze.setState({error:null}),I}catch(H){Ze.setState({error:null});const ae=l&&o?.admissionAttempted===!0,Te=yo(H,ae),M=re==="sessions.message"&&qu(H,c),V=M?kn:Bs(H),z=nf(H,V,ae);let le=!1;const he=I??_??void 0;if(he&&Te==="unknown"&&(le=x&&Hu(he,E)==="owner"),i.updateDraft(e,{pending:!1,admissionAttempted:Te==="unknown"&&x,errorCode:V,error:z.message,errorRetry:z.retry}),le)return I?(i.finishDraft(e,I),I):null;const Ee=On(e,I??d.sessionId),Qt=_&&_!==Ee?[_,Ee]:[Ee];throw Ce.getState().settleInFlight(Qt),_&&_!==Ee&&Ce.getState().returnInFlight(_,Ee),he&&gs(he,E),e!==he&&gs(e,E),M?new X(422,uo,H,kn):H}}const vo=50,pf=25,hf=500;function mf(e){return e?vo:hf}function ti(e,t){return`${e}:${t}`}function gf(e){const t=new Set;for(const n of Object.values(e))for(const s of n.ids)t.add(s);return t}function yf(e){const t=new Set(e.tailIds),n=new Set(e.keepIds??[]),s=new Set(e.page.map(c=>c.session_id)),r=e.sessions.filter(c=>s.has(c.session_id)?!1:e.scopeIds.has(c.session_id)||n.has(c.session_id)?!0:t.has(c.session_id)),i=e.merge(e.sessions,e.page),o=new Set(i.map(c=>c.session_id));for(const c of r)o.has(c.session_id)||(o.add(c.session_id),i.push(c));return{rows:i,tailIds:e.tailIds.filter(c=>o.has(c))}}function vf(e){const t=[...e.previousIds],n=new Set(t);for(const i of e.page)n.has(i.session_id)||(n.add(i.session_id),t.push(i.session_id));const s=[...e.sessions],r=new Map(s.map((i,o)=>[i.session_id,o]));for(const i of e.page){const o=r.get(i.session_id);if(o===void 0){r.set(i.session_id,s.length),s.push(i);continue}s[o]=e.merge(s[o],i)}return{rows:s,ids:t}}function un(e,t){return{...e,...t,...Sf(e,t),...kf(t,e),attention:vt(e?.attention,t.attention,t.session_id)}}const _f=e=>{if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null},bf=e=>e.filter(t=>{if(_f(t)===null)return!1;const n=t.attention?.completion_token;return typeof n=="string"&&n.length>0}),ni=(e,t,n)=>{const s=e.findIndex(c=>c.session_id===t);if(s<0)return e;const r=e[s],i=vt(r.attention,n,t);if(i===r.attention)return e;const o=e.slice();return o[s]={...r,attention:i},o},wf=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function Sf(e,t){const n=s=>typeof s?.status_revision=="number"&&typeof s?.status_epoch=="string"?{status_revision:s.status_revision,status_epoch:s.status_epoch}:void 0;return n(t)??n(e)??{}}function kf(e,t){const n=typeof t?.status_epoch=="string"&&t.status_epoch===e.status_epoch,s=t?.status_revision,r=e.status_revision;return t?.status!==void 0&&n&&typeof s=="number"&&typeof r=="number"&&s>r?{status:t?.status,status_revision:t?.status_revision,status_epoch:t?.status_epoch}:{}}function Tf(e,t){const n={};let s=!1;for(const[r,i]of Object.entries(e)){if(i.at<t){s=!0;continue}n[r]=i}return s?n:e}function Yn(e,t){const n={...e.archiveFacts};delete n[t];const s=e.answerSeq+1;return{sessions:e.sessions.filter(r=>r.session_id!==t),archiveFacts:n,answerSeq:s,forgotten:{...e.forgotten,[t]:{at:s,title:e.sessions.find(r=>r.session_id===t)?.title??void 0}},deleteCandidate:e.deleteCandidate===t?null:e.deleteCandidate}}function _o(e){return e.map(({id:t,name:n,mtime:s,...r})=>({...r,session_id:t,title:n,updated_at:s}))}function si(e,t){return _o(e).filter(n=>t[n.session_id]===void 0)}function Qn(e){return typeof e=="string"&&e.length>0?e:null}function Ef(e){if(e===null||typeof e!="object")return null;const t=e,n=c=>typeof c=="number"&&Number.isFinite(c)&&c>=0?Math.floor(c):null,s=n(t.total),r=n(t.active),i=n(t.unbound);if(s===null||r===null||i===null||!Array.isArray(t.scopes))return null;const o=[];for(const c of t.scopes){if(c===null||typeof c!="object")return null;const l=c;if(l.kind!=="team"&&l.kind!=="agent"||typeof l.name!="string"||l.name.length===0)continue;const d=n(l.total),u=n(l.active);d===null||u===null||o.push({kind:l.kind,name:l.name,total:d,active:u})}return{total:s,active:r,unbound:i,scopes:o}}function xf(e,t){const n=new Map(e.map(s=>[s.session_id,s]));return[...new Map(t.map(s=>[s.session_id,un(n.get(s.session_id),s)])).values()]}let Xn=0,mt=null;function If(e,t,n){const s=mt;if(s)return s.invalidated=!0,s.limit=e,s.withCounts=t,s.promise;const r={limit:e,withCounts:t,invalidated:!1,promise:null};return mt=r,r.promise=(async()=>{try{for(;;){r.invalidated=!1;let i;try{i=await n(r.limit,r.withCounts)}catch(o){if(r.invalidated)continue;throw o}if(!r.invalidated)return mt===r&&(mt=null),i}}finally{mt===r&&(mt=null)}})(),r.promise}function bo(){try{const e=window.api?.desktop;return e?e.initialSession?{kind:"session",sessionId:e.initialSession}:e.initialCatalogue?{kind:"catalogue"}:{kind:"restore"}:{kind:"restore"}}catch{return{kind:"restore"}}}function Cf(){const e=bo();return e.kind==="session"?e.sessionId:null}function Rf(e){if(e.activeSessionId||e.activeDraftKey)return null;const t=`draft:${crypto.randomUUID()}`;return{activeDraftKey:t,drafts:{...e.drafts,[t]:{key:t,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}}}function Af(e,t){const n={...t,...e},s=bo();if(s.kind==="session")return{...n,activeSessionId:s.sessionId};if(s.kind==="catalogue")return{...n,activeSessionId:null};const r=Rf(n);return r?{...n,...r}:n}const Ze=As()(gi((e,t)=>({sessions:[],cataloguePageable:!1,draftWarmable:!1,activeSessionId:Cf(),activeDraftKey:null,drafts:{},sessionByAgent:{},validatingSessionId:null,pinFailure:null,pinFacts:{},answerSeq:0,readAckRearm:null,readAckNotice:null,loading:!1,truncated:!1,head:{pageIds:[],tailIds:[],nextCursor:null,tailCursor:null,tailStarted:!1,complete:!1,loading:!1,error:null,at:0},scopes:{},counts:null,statusUnavailable:[],archiveFacts:{},forgotten:{},stoppedTurns:{},archiveFailure:null,archiveUndo:null,draftsUndo:null,stagedByDiscard:null,deleteCandidate:null,error:null,cwd:"~",setCwd:n=>e(s=>{const r=Object.entries(s.drafts);return r.some(([,i])=>!i.sessionId)?{cwd:n,drafts:Object.fromEntries(r.map(([i,o])=>o.sessionId?[i,o]:[i,{...o,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=mf(t().cataloguePageable),s=!1)=>{const r=++Xn,i=t().answerSeq+1;e({answerSeq:i}),e({loading:!0,error:null});try{const o=await If(n,s,(l,d)=>ce({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{}}));if(r!==Xn)return;const c=_o(o.sessions);e(l=>{const d={...l.pinFacts};for(const[M,V]of Object.entries(d))V.at>=i||delete d[M];const u=new Set(c.map(M=>M.session_id));let f=!1;const p={...l.forgotten};for(const[M,V]of Object.entries(p))V.at<i&&u.has(M)&&(delete p[M],f=!0);const w=f?p:l.forgotten,E=c.filter(M=>w[M.session_id]===void 0),h=Qn(o.next_cursor),_=h===null&&o.truncated!==!0,x=E.map(M=>M.session_id),I=l.sessions.filter(M=>w[M.session_id]===void 0&&(l.pinFacts[M.session_id]?.at??-1)>=i),re=yf({sessions:l.sessions,scopeIds:gf(l.scopes),keepIds:l.activeSessionId===null?[]:[l.activeSessionId],tailIds:_?[]:l.head.tailIds,page:E,merge:xf});let H=re.rows;for(const M of I){const V=l.pinFacts[M.session_id],z=H.findIndex(le=>le.session_id===M.session_id);z===-1?H=[...H,{...M,pinned:V.pinned}]:H[z]={...H[z],pinned:V.pinned}}const ae=Tf(l.archiveFacts,i),Te=Ef(o.counts);return{sessions:H,pinFacts:d,archiveFacts:ae,forgotten:w,loading:!1,truncated:o.truncated===!0,head:{pageIds:x,tailIds:re.tailIds,nextCursor:h,tailCursor:_?null:l.head.tailStarted?l.head.tailCursor:h,tailStarted:l.head.tailStarted,complete:_,loading:!1,error:null,at:i},...Te===null?{}:{counts:Te},statusUnavailable:Array.isArray(o.degraded)?o.degraded.filter(M=>typeof M=="string"):[]}})}catch(o){r===Xn&&e({loading:!1,error:an(o,"Chats could not refresh. Retry to reconnect.")})}},fetchCatalogueTail:async()=>{const n=t().head,s=n.tailCursor;if(!(s===null||n.loading)){e(r=>({head:{...r.head,loading:!0,error:null,tailStarted:!0,tailCursor:s}}));try{const r=await ce({op:"sessions.list",limit:vo,include_archived:!0,cursor:s}),i=si(r.sessions,t().forgotten);e(o=>{const c=new Map(o.sessions.map((f,p)=>[f.session_id,p])),l=[...o.sessions],d=[];for(const f of i){const p=c.get(f.session_id);if(p===void 0){c.set(f.session_id,l.length),l.push(f),d.push(f.session_id);continue}l[p]=un(l[p],f)}const u=Qn(r.next_cursor);return{sessions:l,head:{...o.head,tailIds:[...o.head.tailIds,...d],tailCursor:u,complete:u===null,loading:!1,error:null}}})}catch(r){e(i=>({head:{...i.head,loading:!1,error:an(r,"Could not load more chats.")}}))}}},fetchScopePage:async(n,s,r=null,i=pf)=>{const o=ti(n,s);if(t().scopes[o]?.loading)return;const c=t().answerSeq+1;e({answerSeq:c}),e(l=>({scopes:{...l.scopes,[o]:{ids:l.scopes[o]?.ids??[],nextCursor:l.scopes[o]?.nextCursor??null,loading:!0,error:null,at:c}}}));try{const l=await ce({op:"sessions.list",limit:i,include_archived:!1,scope_kind:n,scope_name:s,...r===null?{}:{cursor:r}}),d=si(l.sessions,t().forgotten);e(u=>{const f=u.scopes[o];if(f===void 0||f.at!==c)return{};const p=r!==null&&l.cursor_missing!==!0,w=vf({sessions:u.sessions,previousIds:p?f.ids:[],page:d,merge:un}),E=Qn(l.next_cursor);return{sessions:w.rows,scopes:{...u.scopes,[o]:{ids:w.ids,nextCursor:E,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[o];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[o]:{...u,loading:!1,error:an(l,"Could not load this group's chats.")}}}})}},clearScope:(n,s)=>{const r=ti(n,s);e(i=>{const o=i.scopes[r];if(o===void 0)return{};const c={...i.scopes};delete c[r];const l=i.activeSessionId,d=new Set(o.ids),u=new Set(i.head.pageIds),f=i.sessions.filter(p=>!d.has(p.session_id)||u.has(p.session_id)||l!==null&&p.session_id===l);return{scopes:c,sessions:f}})},setCataloguePageable:n=>{t().cataloguePageable!==n&&e({cataloguePageable:n})},setDraftWarmable:n=>{if(t().draftWarmable===n||(e({draftWarmable:n}),!n))return;const s=t().activeDraftKey,r=s?t().drafts[s]:void 0;if(!s||!r||r.sessionId||r.warmId)return;Ce.getState().inputByConversation[s]?.currentInput&&t().ensureDraftWarm(s)},setArchiveUndo:n=>{e({archiveUndo:n})},setDraftsUndo:n=>{e({draftsUndo:n})},setStagedByDiscard:n=>{e({stagedByDiscard:n})},restoreDraftsUndo:()=>e(n=>{const s=n.draftsUndo;if(!s)return{};const r={...n.drafts};for(const[o,c]of Object.entries(s.drafts))o in r||(r[o]=c);const i=Ce.getState();for(const[o,c]of Object.entries(s.composer)){const l=i.inputByConversation[o];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||i.restoreRow(o,c)}return{drafts:r,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,s,r)=>{const i=t().answerSeq+1,o=t().archiveFacts[n]??null,c=r??t().sessions.find(l=>l.session_id===n)?.title;e(l=>({answerSeq:i,archiveFacts:{...l.archiveFacts,[n]:{archived:s,at:i,answered:!1}}}));try{return await ce({op:"sessions.archive",sessionId:n,archived:s}),e(l=>{const u=l.archiveFacts[n]?.at!==i;return{archiveFacts:u?l.archiveFacts:{...l.archiveFacts,[n]:{archived:s,at:i,answered:!0}},archiveUndo:u?l.archiveUndo:s?{sessionId:n,title:c??void 0,archived:!0,at:i}:null,archiveFailure:l.archiveFailure?.sessionId===n?null:l.archiveFailure}}),!0}catch(l){return e(d=>{const u=d.archiveFacts[n]?.at!==i,f={...d.archiveFacts};return u||(o?.answered===!0?f[n]=o:(delete f[n],o!==null&&t().fetchSessions())),{archiveFacts:u?d.archiveFacts:f,answerSeq:d.answerSeq+1,archiveFailure:{sessionId:n,at:d.answerSeq+1,archived:s,title:c||"Untitled chat",detail:l instanceof X&&l.message?l.message:""}}}),!1}},deleteSession:async n=>{try{return await ce({op:"sessions.delete",sessionId:n,confirmed:!0}),e(s=>Yn(s,n)),{ok:!0}}catch(s){const r=s instanceof X?s.status:null,i=s instanceof X?s.code??null:null;return r===404?(e(o=>Yn(o,n)),{ok:!0}):{ok:!1,guarded:i==="session_delete_refused",detail:s instanceof X&&s.message?s.message:"The conversation could not be deleted."}}},requestSessionDelete:n=>e({deleteCandidate:n}),createSession:async(n,s,r=crypto.randomUUID(),i,o)=>{try{const c=await ce({op:"sessions.create",requestId:r,cwd:n,...s?{target:s}:{},...i?{model:i}:{},...o?{draftId:o}:{}});return t().upsertSession({session_id:c.session_id,cwd:n,binding:c.binding}),c.session_id}catch(c){throw e({error:an(c,"Chat could not start. Retry with the same draft.")}),c}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,s=Date.now())=>e(r=>({stoppedTurns:{...r.stoppedTurns,[n]:s}})),clearTurnStopped:n=>e(s=>{if(!(n in s.stoppedTurns))return s;const{[n]:r,...i}=s.stoppedTurns;return{stoppedTurns:i}}),openDraft:n=>{t().drafts[n]&&e({activeDraftKey:n,activeSessionId:null,validatingSessionId:null,error:null})},confirmSessionLive:n=>{n&&t().validatingSessionId===n&&e({validatingSessionId:null})},confirmSessionMissing:n=>{!n||t().validatingSessionId!==n||e({validatingSessionId:null,...Yn(t(),n)})},rearmReadAck:n=>{e(s=>({readAckRearm:wf(s.readAckRearm,n)}))},publishReadAckNotice:(n,s,r)=>{e(i=>{const o=i.readAckNotice;return o?.sessionId===n&&o.kind===s?i:{readAckNotice:{sessionId:n,kind:s,revision:(o?.revision??0)+1,reason:r}}})},clearReadAckNotice:n=>{e(s=>s.readAckNotice?.sessionId===n?{readAckNotice:null}:s)},applyAttention:(n,s)=>{e(r=>{const i=ni(r.sessions,n,s);return i===r.sessions?r:{...r,sessions:i}})},applyAttentionMany:n=>{e(s=>{let r=s.sessions;for(const i of n){const o=i?.conversation_id;typeof o!="string"||!o.startsWith("session/")||(r=ni(r,o.slice(8),i))}return r===s.sessions?s:{...s,sessions:r}})},markAllRead:async()=>{const n=bf(t().sessions).map(r=>({sessionId:r.session_id,completionToken:r.attention?.completion_token}));if(n.length===0)return{attempted:0,cleared:0,superseded:0,unknown:0};const s=await ce({op:"attention.seen",items:n});return t().applyAttentionMany(s.read),{attempted:n.length,cleared:s.read.length,superseded:s.superseded.length,unknown:s.unknown.length}},applySessionStatus:(n,s,r,i)=>{e(o=>{const c=o.sessions.findIndex(p=>p.session_id===n);let l=!1;const d=o.sessions.map(p=>{if(p.status_epoch===void 0&&p.status_revision===void 0||p.status_epoch===i)return p;l=!0;const{status_revision:w,status_epoch:E,...h}=p;return h});if(c<0)return l?{...o,sessions:d}:o;const u=d[c],f=u.status?.code===s.code&&u.status?.label===s.label&&u.status_revision===r&&u.status_epoch===i;return f&&!l?o:(f||(d[c]={...u,status:s,status_revision:r,status_epoch:i}),{...o,sessions:d})})},openSession:async n=>t().activeSessionId===n&&!t().activeDraftKey?(t().rearmReadAck(n),!0):(e({activeSessionId:n,activeDraftKey:null,validatingSessionId:n,error:null}),t().rearmReadAck(n),!0),stageDraft:(n,s=!1)=>{const r=!s&&n?`draft:${n.kind}:${n.name}`:`draft:${crypto.randomUUID()}`,i=t().drafts[r];return e(o=>({activeDraftKey:r,validatingSessionId:null,error:null,drafts:{...o.drafts,[r]:i??{key:r,target:n,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}})),r},updateDraft:(n,s)=>e(r=>{const i=r.drafts[n],o=s.key!==void 0&&s.createRequestId!==void 0&&s.admissionRequestId!==void 0;return!i&&!o?{}:{drafts:{...r.drafts,[n]:{...r.drafts[n],...s}}}}),setDraftModel:(n,s)=>e(r=>{const i=r.drafts[n];return i?{drafts:{...r.drafts,[n]:{...i,model:s,...i.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}:{}}),ensureDraftWarm:n=>{const s=t();if(!s.draftWarmable)return;const r=s.drafts[n];if(!r||r.sessionId||r.warmId||!s.cwd)return;const i=r.draftRequestId??crypto.randomUUID();r.draftRequestId||t().updateDraft(n,{draftRequestId:i}),ce({op:"sessions.draft",requestId:i,cwd:s.cwd,...r.target?{target:r.target}:{},...r.model?{model:r.model}:{}}).then(o=>{const c=t().drafts[n];c&&!c.warmId&&!c.sessionId&&c.draftRequestId===i&&t().updateDraft(n,{warmId:o.draft_id})}).catch(()=>{})},finishDraft:(n,s)=>e(r=>{of(n,s);const i={...r.drafts};return delete i[n],{drafts:i,...r.activeDraftKey===n?{activeDraftKey:null,activeSessionId:s}:{}}}),discardDraft:n=>e(s=>{const r={...s.drafts},i=r[n]?.sessionId??(n.startsWith("send:")?n.slice(5):void 0),o=r[n],c=Ce.getState().inputByConversation[n];on(n),i&&i!==n&&on(i),delete r[n],Ce.getState().clearAll(n);const l=o?{at:s.answerSeq+1,keys:[n],drafts:{[n]:o},composer:c?{[n]:c}:{}}:null;return{drafts:r,...l?{answerSeq:l.at,draftsUndo:l}:{},...s.activeDraftKey===n?{activeDraftKey:null}:{}}}),discardDrafts:n=>e(s=>{const r={...s.drafts};let i=!1;const o=[],c={},l={};for(const u of n){if(!(u in r))continue;const f=r[u];if(!f)continue;const p=f.sessionId??(u.startsWith("send:")?u.slice(5):void 0);on(u),p&&p!==u&&on(p),o.push(u),c[u]=f;const w=Ce.getState().inputByConversation[u];w&&(l[u]=w),delete r[u],Ce.getState().clearAll(u),s.activeDraftKey===u&&(i=!0)}if(o.length===0)return{};const d=s.answerSeq+1;return{drafts:r,answerSeq:d,draftsUndo:{at:d,keys:o,drafts:c,composer:l},...i?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,s,r)=>e(i=>{const o=Object.entries(i.drafts).filter(([,z])=>vs(z,n)&&z.undelivered!==void 0&&s.includes(z.undelivered.recordId));let c=i.drafts;if(o.length>0){c={...c};for(const[z,le]of o){const{undelivered:he,...Ee}=le;c[z]=Ee}}const l=Object.entries(c).find(([,z])=>vs(z,n)&&z.admissionAttempted===!0&&z.pending!==!0&&z.submittedText!==void 0);if(!l)return o.length>0?{drafts:c}:{};const[d,u]=l,f=u.admissionRequestId,p=s.includes(f);if(!p&&!r)return o.length>0?{drafts:c}:{};const{admissionAttempted:w,submittedText:E,submittedAttachments:h,submittedImages:_,submittedMode:x,submittedInputMode:I,submittedInputPath:re,heldClaimCode:H,error:ae,errorCode:Te,errorRetry:M,...V}=u;return p||gs(n,f),{drafts:{...c,[d]:{...V,...p?{}:{undelivered:{recordId:f,text:E??"",attachments:h??[]}},admissionRequestId:crypto.randomUUID()}}}}),bindSession:(n,s)=>t().setActiveSession(s),beginAnswer:()=>{const n=t().answerSeq+1;return e({answerSeq:n}),n},applySearchAnswer:(n,s)=>e(r=>{let i=null,o=null,c=null;for(const l of s){const d=r.archiveFacts[l.id];if(d!==void 0&&d.at<n&&(c=c??{...r.archiveFacts},delete c[l.id]),typeof l.pinned!="boolean")continue;const u=r.pinFacts[l.id];if(!(u!==void 0&&u.at>=n)&&(u!==void 0&&(i=i??{...r.pinFacts},delete i[l.id]),r.sessions.some(f=>f.session_id===l.id&&f.pinned!==l.pinned))){o=o??r.sessions.map(f=>({...f}));for(const f of o)f.session_id===l.id&&(f.pinned=l.pinned===!0)}}return i===null&&o===null&&c===null?{}:{...i===null?{}:{pinFacts:i},...o===null?{}:{sessions:o},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,s,r)=>{const i=t().sessions.find(p=>p.session_id===n),o=t().pinFacts[n]??null,c=i===void 0?o?.pinned??!1:i.pinned===!0,l=i===void 0&&r!==void 0?{session_id:n,title:r.title||"Untitled chat",updated_at:r.updated_at,pinned:s}:null,d=t().beginAnswer(),u=i?.title??r?.title,f=i?.updated_at??r?.updated_at;e(p=>({sessions:l===null?p.sessions.map(w=>w.session_id===n?{...w,pinned:s}:w):[...p.sessions,l],pinFacts:{...p.pinFacts,[n]:{pinned:s,at:d,title:u,updated_at:f}},pinFailure:null}));try{const p=await ce({op:"sessions.pin",sessionId:n,pinned:s});let w=!1;return e(E=>{const h=E.pinFacts[n];return h===void 0||h.at!==d?{}:(w=!0,{sessions:E.sessions.map(_=>_.session_id===n?{..._,pinned:p.pinned===!0}:_),pinFacts:{...E.pinFacts,[n]:{...h,pinned:p.pinned===!0}}})}),w}catch(p){return e(w=>{const E=w.pinFacts[n];if(E!==void 0&&E.at!==d)return{};const h={...w.pinFacts};return o===null&&i===void 0?delete h[n]:h[n]={pinned:c,at:Math.max(o?.at??0,d),title:o?.title??u,updated_at:o?.updated_at??f},{sessions:w.sessions.map(_=>_.session_id===n?{..._,pinned:c}:_),pinFacts:h,pinFailure:{sessionId:n,pinned:s,title:i?.title||"this chat",detail:In(p,"")}}}),!1}},upsertSession:n=>e(s=>({sessions:s.sessions.some(i=>i.session_id===n.session_id)?s.sessions.map(i=>i.session_id===n.session_id?un(i,n):i):[...s.sessions,n]}))}),{name:"canonical-sessions-storage",merge:Af,partialize:e=>({sessionByAgent:e.sessionByAgent,activeSessionId:e.activeSessionId,activeDraftKey:e.activeDraftKey,cwd:e.cwd,forgotten:Object.fromEntries(Object.entries(e.forgotten).map(([t,n])=>[t,{at:0,title:n.title}])),drafts:Object.fromEntries(Object.entries(e.drafts).map(([t,n])=>[t,{...n,pending:!1,warmId:void 0}]))})}));var Gs=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},ct=typeof window>"u"||"Deno"in globalThis;function _s(){}function hm(e,t){return typeof e=="function"?e(t):e}function bs(e){return typeof e=="number"&&e>=0&&e!==1/0}function wo(e,t){return Math.max(e+(t||0)-Date.now(),0)}function fn(e,t){return typeof e=="function"?e(t):e}function be(e,t){return typeof e=="function"?e(t):e}function mm(e,t){const{type:n="all",exact:s,fetchStatus:r,predicate:i,queryKey:o,stale:c}=e;if(o){if(s){if(t.queryHash!==Of(o,t.options))return!1}else if(!Hs(t.queryKey,o))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||r&&r!==t.state.fetchStatus||i&&!i(t))}function gm(e,t){const{exact:n,status:s,predicate:r,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(ws(t.options.mutationKey)!==ws(i))return!1}else if(!Hs(t.options.mutationKey,i))return!1}return!(s&&t.state.status!==s||r&&!r(t))}function Of(e,t){return(t?.queryKeyHashFn||ws)(e)}function ws(e){return JSON.stringify(e,(t,n)=>ks(n)?Object.keys(n).sort().reduce((s,r)=>(s[r]=n[r],s),{}):n)}function Hs(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Hs(e[n],t[n])):!1}function So(e,t){if(e===t)return e;const n=ri(e)&&ri(t);if(n||ks(e)&&ks(t)){const s=n?e:Object.keys(e),r=s.length,i=n?t:Object.keys(t),o=i.length,c=n?[]:{};let l=0;for(let d=0;d<o;d++){const u=n?d:i[d];(!n&&s.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=So(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return r===o&&l===r?e:c}return t}function Ss(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function ri(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ks(e){if(!ii(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!ii(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ii(e){return Object.prototype.toString.call(e)==="[object Object]"}function Pf(e){return new Promise(t=>{setTimeout(t,e)})}function Ts(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?So(e,t):t}function ym(e){return e}function vm(e,t,n=0){const s=[...e,t];return n&&s.length>n?s.slice(1):s}function _m(e,t,n=0){const s=[t,...e];return n&&s.length>n?s.slice(0,-1):s}var ko=Symbol();function Df(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===ko?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Lf=class extends Gs{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!ct&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#t!==e&&(this.#t=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#t=="boolean"?this.#t:globalThis.document?.visibilityState!=="hidden"}},To=new Lf,Nf=class extends Gs{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!ct&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(this.setOnline.bind(this))}setOnline(e){this.#t!==e&&(this.#t=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#t}},Eo=new Nf;function Es(){let e,t;const n=new Promise((r,i)=>{e=r,t=i});n.status="pending",n.catch(()=>{});function s(r){Object.assign(n,r),delete n.resolve,delete n.reject}return n.resolve=r=>{s({status:"fulfilled",value:r}),e(r)},n.reject=r=>{s({status:"rejected",reason:r}),t(r)},n}function Mf(e){return Math.min(1e3*2**e,3e4)}function xo(e){return(e??"online")==="online"?Eo.isOnline():!0}var Io=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Jn(e){return e instanceof Io}function jf(e){let t=!1,n=0,s=!1,r;const i=Es(),o=h=>{s||(p(new Io(h)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>To.isFocused()&&(e.networkMode==="always"||Eo.isOnline())&&e.canRun(),u=()=>xo(e.networkMode)&&e.canRun(),f=h=>{s||(s=!0,e.onSuccess?.(h),r?.(),i.resolve(h))},p=h=>{s||(s=!0,e.onError?.(h),r?.(),i.reject(h))},w=()=>new Promise(h=>{r=_=>{(s||d())&&h(_)},e.onPause?.()}).then(()=>{r=void 0,s||e.onContinue?.()}),E=()=>{if(s)return;let h;const _=n===0?e.initialPromise:void 0;try{h=_??e.fn()}catch(x){h=Promise.reject(x)}Promise.resolve(h).then(f).catch(x=>{if(s)return;const I=e.retry??(ct?0:3),re=e.retryDelay??Mf,H=typeof re=="function"?re(n,x):re,ae=I===!0||typeof I=="number"&&n<I||typeof I=="function"&&I(n,x);if(t||!ae){p(x);return}n++,e.onFail?.(n,x),Pf(H).then(()=>d()?void 0:w()).then(()=>{t?p(x):E()})})};return{promise:i,cancel:o,continue:()=>(r?.(),i),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?E():w().then(E),i)}}var $f=e=>setTimeout(e,0);function Uf(){let e=[],t=0,n=c=>{c()},s=c=>{c()},r=$f;const i=c=>{t?e.push(c):r(()=>{n(c)})},o=()=>{const c=e;e=[],c.length&&r(()=>{s(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||o()}return l},batchCalls:c=>(...l)=>{i(()=>{c(...l)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{s=c},setScheduler:c=>{r=c}}}var Vs=Uf(),Ff=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),bs(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ct?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},bm=class extends Ff{#t;#e;#n;#r;#s;#a;#o;constructor(e){super(),this.#o=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#n=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Bf(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#s?.promise}setOptions(e){this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,t){const n=Ts(this.state.data,e,this.options);return this.#i({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#s?.promise;return this.#s?.cancel(e),t?t.then(_s).catch(_s):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>be(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ko||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(e=0){return this.state.isInvalidated||this.state.data===void 0||!wo(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#s?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#s?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#s&&(this.#o?this.#s.cancel({revert:!0}):this.#s.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({type:"invalidate"})}fetch(e,t){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#s)return this.#s.continueRetry(),this.#s.promise}if(e&&this.setOptions(e),!this.options.queryFn){const c=this.observers.find(l=>l.options.queryFn);c&&this.setOptions(c.options)}const n=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(this.#o=!0,n.signal)})},r=()=>{const c=Df(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return s(l),this.#o=!1,this.options.persister?this.options.persister(c,l,this):c(l)},i={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:r};s(i),this.options.behavior?.onFetch(i,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==i.fetchOptions?.meta)&&this.#i({type:"fetch",meta:i.fetchOptions?.meta});const o=c=>{Jn(c)&&c.silent||this.#i({type:"error",error:c}),Jn(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#s=jf({initialPromise:t?.initialPromise,fn:i.fetchFn,abort:n.abort.bind(n),onSuccess:c=>{if(c===void 0){o(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(l){o(l);return}this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),this.scheduleGc()},onError:o,onFail:(c,l)=>{this.#i({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:i.options.retry,retryDelay:i.options.retryDelay,networkMode:i.options.networkMode,canRun:()=>!0}),this.#s.start()}#i(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Co(n.data,this.options),fetchMeta:e.meta??null};case"success":return{...n,data:e.data,dataUpdateCount:n.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const s=e.error;return Jn(s)&&s.revert&&this.#e?{...this.#e,fetchStatus:"idle"}:{...n,error:s,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),Vs.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function Co(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:xo(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Bf(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,s=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Zf=class extends Gs{constructor(e,t){super(),this.options=t,this.#t=e,this.#i=null,this.#o=Es(),this.options.experimental_prefetchInRender||this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#n=void 0;#r=void 0;#s;#a;#o;#i;#m;#f;#p;#l;#d;#c;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),oi(this.#e,this.options)?this.#u():this.updateResult(),this.#_())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return xs(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return xs(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#e.removeObserver(this)}setOptions(e){const t=this.options,n=this.#e;if(this.options=this.#t.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof be(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#e.setOptions(this.options),t._defaulted&&!Ss(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const s=this.hasListeners();s&&ai(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),s&&(this.#e!==n||be(this.options.enabled,this.#e)!==be(t.enabled,this.#e)||fn(this.options.staleTime,this.#e)!==fn(t.staleTime,this.#e))&&this.#g();const r=this.#y();s&&(this.#e!==n||be(this.options.enabled,this.#e)!==be(t.enabled,this.#e)||r!==this.#c)&&this.#v(r)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return Hf(this,n)&&(this.#r=n,this.#a=this.options,this.#s=this.#e.state),n}getCurrentResult(){return this.#r}trackResult(e,t){const n={};return Object.keys(e).forEach(s=>{Object.defineProperty(n,s,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(s),t?.(s),e[s])})}),n}trackProp(e){this.#h.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),n=this.#t.getQueryCache().build(this.#t,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#u({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#u(e){this.#S();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(_s)),t}#g(){this.#b();const e=fn(this.options.staleTime,this.#e);if(ct||this.#r.isStale||!bs(e))return;const n=wo(this.#r.dataUpdatedAt,e)+1;this.#l=setTimeout(()=>{this.#r.isStale||this.updateResult()},n)}#y(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#e):this.options.refetchInterval)??!1}#v(e){this.#w(),this.#c=e,!(ct||be(this.options.enabled,this.#e)===!1||!bs(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||To.isFocused())&&this.#u()},this.#c))}#_(){this.#g(),this.#v(this.#y())}#b(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#w(){this.#d&&(clearInterval(this.#d),this.#d=void 0)}createResult(e,t){const n=this.#e,s=this.options,r=this.#r,i=this.#s,o=this.#a,l=e!==n?e.state:this.#n,{state:d}=e;let u={...d},f=!1,p;if(t._optimisticResults){const V=this.hasListeners(),z=!V&&oi(e,t),le=V&&ai(e,n,t,s);(z||le)&&(u={...u,...Co(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:w,errorUpdatedAt:E,status:h}=u;p=u.data;let _=!1;if(t.placeholderData!==void 0&&p===void 0&&h==="pending"){let V;r?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(V=r.data,_=!0):V=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,V!==void 0&&(h="success",p=Ts(r?.data,V,t),f=!0)}if(t.select&&p!==void 0&&!_)if(r&&p===i?.data&&t.select===this.#m)p=this.#f;else try{this.#m=t.select,p=t.select(p),p=Ts(r?.data,p,t),this.#f=p,this.#i=null}catch(V){this.#i=V}this.#i&&(w=this.#i,p=this.#f,E=Date.now(),h="error");const x=u.fetchStatus==="fetching",I=h==="pending",re=h==="error",H=I&&x,ae=p!==void 0,M={status:h,fetchStatus:u.fetchStatus,isPending:I,isSuccess:h==="success",isError:re,isInitialLoading:H,isLoading:H,data:p,dataUpdatedAt:u.dataUpdatedAt,error:w,errorUpdatedAt:E,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:x,isRefetching:x&&!I,isLoadingError:re&&!ae,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:re&&ae,isStale:zs(e,t),refetch:this.refetch,promise:this.#o};if(this.options.experimental_prefetchInRender){const V=he=>{M.status==="error"?he.reject(M.error):M.data!==void 0&&he.resolve(M.data)},z=()=>{const he=this.#o=M.promise=Es();V(he)},le=this.#o;switch(le.status){case"pending":e.queryHash===n.queryHash&&V(le);break;case"fulfilled":(M.status==="error"||M.data!==le.value)&&z();break;case"rejected":(M.status!=="error"||M.error!==le.reason)&&z();break}}return M}updateResult(){const e=this.#r,t=this.createResult(this.#e,this.options);if(this.#s=this.#e.state,this.#a=this.options,this.#s.data!==void 0&&(this.#p=this.#e),Ss(t,e))return;this.#r=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:s}=this.options,r=typeof s=="function"?s():s;if(r==="all"||!r&&!this.#h.size)return!0;const i=new Set(r??this.#h);return this.options.throwOnError&&i.add("error"),Object.keys(this.#r).some(o=>{const c=o;return this.#r[c]!==e[c]&&i.has(c)})};this.#k({listeners:n()})}#S(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#_()}#k(e){Vs.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function Gf(e,t){return be(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function oi(e,t){return Gf(e,t)||e.state.data!==void 0&&xs(e,t,t.refetchOnMount)}function xs(e,t,n){if(be(t.enabled,e)!==!1){const s=typeof n=="function"?n(e):n;return s==="always"||s!==!1&&zs(e,t)}return!1}function ai(e,t,n,s){return(e!==t||be(s.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&zs(e,n)}function zs(e,t){return be(t.enabled,e)!==!1&&e.isStaleByTime(fn(t.staleTime,e))}function Hf(e,t){return!Ss(e.getCurrentResult(),t)}var Ro=T.createContext(void 0),Vf=e=>{const t=T.useContext(Ro);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},wm=({client:e,children:t})=>(T.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),De.jsx(Ro.Provider,{value:e,children:t})),Ao=T.createContext(!1),zf=()=>T.useContext(Ao);Ao.Provider;function Kf(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Wf=T.createContext(Kf()),Yf=()=>T.useContext(Wf);function Qf(e,t){return typeof e=="function"?e(...t):!!e}function ci(){}var Xf=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},Jf=e=>{T.useEffect(()=>{e.clearReset()},[e])},qf=({result:e,errorResetBoundary:t,throwOnError:n,query:s,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&s&&(r&&e.data===void 0||Qf(n,[e.error,s])),ep=e=>{const t=e.staleTime;e.suspense&&(e.staleTime=typeof t=="function"?(...n)=>Math.max(t(...n),1e3):Math.max(t??1e3,1e3),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3)))},tp=(e,t)=>e.isLoading&&e.isFetching&&!t,np=(e,t)=>e?.suspense&&t.isPending,li=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function sp(e,t,n){const s=Vf(),r=zf(),i=Yf(),o=s.defaultQueryOptions(e);s.getDefaultOptions().queries?._experimental_beforeQuery?.(o),o._optimisticResults=r?"isRestoring":"optimistic",ep(o),Xf(o,i),Jf(i);const c=!s.getQueryCache().get(o.queryHash),[l]=T.useState(()=>new t(s,o)),d=l.getOptimisticResult(o),u=!r&&e.subscribed!==!1;if(T.useSyncExternalStore(T.useCallback(f=>{const p=u?l.subscribe(Vs.batchCalls(f)):ci;return l.updateResult(),p},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),T.useEffect(()=>{l.setOptions(o)},[o,l]),np(o,d))throw li(o,l,i);if(qf({result:d,errorResetBoundary:i,throwOnError:o.throwOnError,query:s.getQueryCache().get(o.queryHash),suspense:o.suspense}))throw d.error;return s.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!ct&&tp(d,r)&&(c?li(o,l,i):s.getQueryCache().get(o.queryHash)?.promise)?.catch(ci).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?d:l.trackResult(d)}function Oo(e,t){return sp(e,Zf)}/**
|
|
20
|
+
${e}`)}function vs(e,t){return e.sessionId===t||e.key===t||e.key===`send:${t}`}function pm(e,t,n){if(e)return e;if(!t)return null;const s=Object.entries(n).filter(([,i])=>vs(i,t));return(s.find(([,i])=>i.submittedText!==void 0||i.undelivered!==void 0||i.error!==void 0||i.admissionAttempted===!0||i.pending===!0)??s[0])?.[0]??`send:${t}`}function Zs(e,t){return t??e??void 0}function af(e,t,n){return e?t??void 0:n??void 0}function hm(e,t,n){return Zs(e,af(e,t,n))}function cf(e){return e instanceof X?e.status===413||e.status===422?!0:e.code===Ps||e.code===Ri||e.code===_e.noCredential||ei(e.code):e instanceof Ke&&(e.code===An||e.code===po||ei(e.code))}function On(e,t){const n=e.startsWith("send:")?e.slice(5):null;return Zs(e.startsWith("draft:")?e:null,t??n)??e}function lf(e,t){const n=Ce.getState(),s=On(e,t),r=s===""||s===e?[e]:[e,s];n.settleInFlight(r),s!==""&&s!==e&&n.inputByConversation[e]&&n.returnInFlight(e,s)}function mm(e,t){if(!t||t.migratedHeld||t.pending||!(t.heldClaimCode!==void 0||t.errorRetry===void 0&&t.submittedRendered===void 0)||!t.admissionAttempted||t.submittedText===void 0)return!1;const s=On(e,t.sessionId);return Ce.getState().returnPayload(s,{text:t.submittedText,attachments:t.submittedAttachments??[],replies:[]}),Ze.getState().updateDraft(e,{migratedHeld:!0,submittedText:void 0,submittedAttachments:void 0,error:ge.unconfirmed,errorCode:t.heldClaimCode,errorRetry:!Ot(t.heldClaimCode),heldClaimCode:void 0}),!0}function gm(e,t){if(!t)return!1;const n=t.undelivered,s=t.submittedText,r=s!==void 0&&t.error!==void 0&&t.errorRetry!==void 0;if(!n&&!r)return!1;const i=On(e,t.sessionId);if(n)return qr(i,n.recordId)?!1:(hs(i,{id:n.recordId,text:n.text,images:[],settled:!0,submittedAt:t.submittedAt}),!0);if(s===void 0)return!1;const o=t.admissionRequestId;return qr(i,o)?!1:(hs(i,{id:o,text:t.submittedRendered??s,submittedAt:t.submittedAt,images:(t.submittedImages??[]).map((c,l)=>({id:`${o}:${l}`,data:c.data_b64,attachment:null,mimeType:c.mime_type}))}),!0)}function df(e,t,n){if(e.submittedText!==t)return!1;const s=e.submittedAttachments??[];return s.length!==n.length?!1:s.every((r,i)=>r===n[i])}function uf(e,t){return!!t&&e===t}const ff=3,pf=5e3,hf=2e3;async function mf(e){for(let t=0;;t++)try{await ce(e);return}catch(n){if(t>=ff||!(n instanceof X)||n.code!==Ps)throw n;const s=Math.min(Math.max(0,n.retryAfterMs??hf),pf);await new Promise(r=>setTimeout(r,s))}}async function ym(e,t,n,s,r){const i=Ze.getState();if(uf(i.validatingSessionId,n))throw new Ke(tf,An);const o=i.drafts[e];if(o?.pending)return null;const c=ys(t.text),l=o?.submittedText!==void 0&&df(o,c,t.attachments),d=o??{key:e,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()},u=l?o?.submittedImages??t.images:t.images,f=l?o?.submittedMode??t.mode:t.mode,p=l&&o?o.submittedInputMode:t.inputMode,w=l&&o?o.submittedInputPath:t.inputPath,E=o?.submittedText===void 0||l?o?.admissionRequestId??crypto.randomUUID():crypto.randomUUID(),h=Date.now();i.updateDraft(e,{...d,admissionAttempted:l,admissionRequestId:E,submittedRendered:l?o?.submittedRendered:void 0,migratedHeld:o?.migratedHeld,pending:!0,submittedText:c,submittedAttachments:t.attachments,submittedImages:u,submittedMode:f,submittedInputMode:p,submittedInputPath:w,error:void 0,errorCode:void 0,submittedAt:h});const _=Zs(e.startsWith("draft:")?e:null,n??d.sessionId)??null;_&&hs(_,{id:E,submittedAt:h,text:c,images:u.map((H,ae)=>({id:`${E}:${ae}`,data:H.data_b64,attachment:null,mimeType:H.mime_type})),onPainted:s});let x=l,I=n??d.sessionId,re=null;try{if(!I){if(re="sessions.create",I=await i.createSession(t.cwd,d.target,d.createRequestId,d.model??null,d.warmId)??void 0,!I)throw new Ke(Ze.getState().error??"Chat could not start.");i.updateDraft(e,{sessionId:I}),_&&Zu(_,I),i.fetchSessions()}const H=l&&o?.submittedRendered!==void 0?o.submittedRendered:r?await r(I)??c:c;return x=!0,i.updateDraft(e,{error:void 0,errorCode:void 0,errorRetry:void 0,admissionAttempted:!0,submittedRendered:H}),I&&Bu(I,E,H),re="sessions.message",await mf({op:"sessions.message",sessionId:I,requestId:E,text:H,images:u.length?u:void 0,mode:f,inputMode:p,inputPath:w}),i.finishDraft(e,I),Ze.setState({error:null}),I}catch(H){Ze.setState({error:null});const ae=l&&o?.admissionAttempted===!0,Te=vo(H,ae),M=re==="sessions.message"&&nf(H,c),z=M?kn:Bs(H),V=of(H,z,ae);let le=!1;const he=I??_??void 0;if(he&&Te==="unknown"&&(le=x&&Ku(he,E)==="owner"),i.updateDraft(e,{pending:!1,admissionAttempted:Te==="unknown"&&x,errorCode:z,error:V.message,errorRetry:V.retry}),le)return I?(i.finishDraft(e,I),I):null;const Ee=On(e,I??d.sessionId),Qt=_&&_!==Ee?[_,Ee]:[Ee];throw Ce.getState().settleInFlight(Qt),_&&_!==Ee&&Ce.getState().returnInFlight(_,Ee),he&&gs(he,E),e!==he&&gs(e,E),M?new X(422,fo,H,kn):H}}const _o=50,gf=25,yf=500;function vf(e){return e?_o:yf}function ti(e,t){return`${e}:${t}`}function _f(e){const t=new Set;for(const n of Object.values(e))for(const s of n.ids)t.add(s);return t}function bf(e){const t=new Set(e.tailIds),n=new Set(e.keepIds??[]),s=new Set(e.page.map(c=>c.session_id)),r=e.sessions.filter(c=>s.has(c.session_id)?!1:e.scopeIds.has(c.session_id)||n.has(c.session_id)?!0:t.has(c.session_id)),i=e.merge(e.sessions,e.page),o=new Set(i.map(c=>c.session_id));for(const c of r)o.has(c.session_id)||(o.add(c.session_id),i.push(c));return{rows:i,tailIds:e.tailIds.filter(c=>o.has(c))}}function wf(e){const t=[...e.previousIds],n=new Set(t);for(const i of e.page)n.has(i.session_id)||(n.add(i.session_id),t.push(i.session_id));const s=[...e.sessions],r=new Map(s.map((i,o)=>[i.session_id,o]));for(const i of e.page){const o=r.get(i.session_id);if(o===void 0){r.set(i.session_id,s.length),s.push(i);continue}s[o]=e.merge(s[o],i)}return{rows:s,ids:t}}function un(e,t){return{...e,...t,...Ef(e,t),...xf(t,e),attention:vt(e?.attention,t.attention,t.session_id)}}const Sf=e=>{if(e.attention?.unseen!==!0)return null;const t=e.status?.code;return t==="complete"||t==="error"||t==="interrupted"?t:null},kf=e=>e.filter(t=>{if(Sf(t)===null)return!1;const n=t.attention?.completion_token;return typeof n=="string"&&n.length>0}),ni=(e,t,n)=>{const s=e.findIndex(c=>c.session_id===t);if(s<0)return e;const r=e[s],i=vt(r.attention,n,t);if(i===r.attention)return e;const o=e.slice();return o[s]={...r,attention:i},o},Tf=(e,t)=>({sessionId:t,revision:(e?.revision??0)+1});function Ef(e,t){const n=s=>typeof s?.status_revision=="number"&&typeof s?.status_epoch=="string"?{status_revision:s.status_revision,status_epoch:s.status_epoch}:void 0;return n(t)??n(e)??{}}function xf(e,t){const n=typeof t?.status_epoch=="string"&&t.status_epoch===e.status_epoch,s=t?.status_revision,r=e.status_revision;return t?.status!==void 0&&n&&typeof s=="number"&&typeof r=="number"&&s>r?{status:t?.status,status_revision:t?.status_revision,status_epoch:t?.status_epoch}:{}}function If(e,t){const n={};let s=!1;for(const[r,i]of Object.entries(e)){if(i.at<t){s=!0;continue}n[r]=i}return s?n:e}function Yn(e,t){const n={...e.archiveFacts};delete n[t];const s=e.answerSeq+1;return{sessions:e.sessions.filter(r=>r.session_id!==t),archiveFacts:n,answerSeq:s,forgotten:{...e.forgotten,[t]:{at:s,title:e.sessions.find(r=>r.session_id===t)?.title??void 0}},deleteCandidate:e.deleteCandidate===t?null:e.deleteCandidate}}function bo(e){return e.map(({id:t,name:n,mtime:s,...r})=>({...r,session_id:t,title:n,updated_at:s}))}function si(e,t){return bo(e).filter(n=>t[n.session_id]===void 0)}function Qn(e){return typeof e=="string"&&e.length>0?e:null}function Cf(e){if(e===null||typeof e!="object")return null;const t=e,n=c=>typeof c=="number"&&Number.isFinite(c)&&c>=0?Math.floor(c):null,s=n(t.total),r=n(t.active),i=n(t.unbound);if(s===null||r===null||i===null||!Array.isArray(t.scopes))return null;const o=[];for(const c of t.scopes){if(c===null||typeof c!="object")return null;const l=c;if(l.kind!=="team"&&l.kind!=="agent"||typeof l.name!="string"||l.name.length===0)continue;const d=n(l.total),u=n(l.active);d===null||u===null||o.push({kind:l.kind,name:l.name,total:d,active:u})}return{total:s,active:r,unbound:i,scopes:o}}function Rf(e,t){const n=new Map(e.map(s=>[s.session_id,s]));return[...new Map(t.map(s=>[s.session_id,un(n.get(s.session_id),s)])).values()]}let Xn=0,mt=null;function Af(e,t,n){const s=mt;if(s)return s.invalidated=!0,s.limit=e,s.withCounts=t,s.promise;const r={limit:e,withCounts:t,invalidated:!1,promise:null};return mt=r,r.promise=(async()=>{try{for(;;){r.invalidated=!1;let i;try{i=await n(r.limit,r.withCounts)}catch(o){if(r.invalidated)continue;throw o}if(!r.invalidated)return mt===r&&(mt=null),i}}finally{mt===r&&(mt=null)}})(),r.promise}function wo(){try{const e=window.api?.desktop;return e?e.initialSession?{kind:"session",sessionId:e.initialSession}:e.initialCatalogue?{kind:"catalogue"}:{kind:"restore"}:{kind:"restore"}}catch{return{kind:"restore"}}}function Of(){const e=wo();return e.kind==="session"?e.sessionId:null}function Pf(e){if(e.activeSessionId||e.activeDraftKey)return null;const t=`draft:${crypto.randomUUID()}`;return{activeDraftKey:t,drafts:{...e.drafts,[t]:{key:t,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}}}function Df(e,t){const n={...t,...e},s=wo();if(s.kind==="session")return{...n,activeSessionId:s.sessionId};if(s.kind==="catalogue")return{...n,activeSessionId:null};const r=Pf(n);return r?{...n,...r}:n}const Ze=As()(gi((e,t)=>({sessions:[],cataloguePageable:!1,draftWarmable:!1,activeSessionId:Of(),activeDraftKey:null,drafts:{},sessionByAgent:{},validatingSessionId:null,pinFailure:null,pinFacts:{},answerSeq:0,readAckRearm:null,readAckNotice:null,loading:!1,truncated:!1,head:{pageIds:[],tailIds:[],nextCursor:null,tailCursor:null,tailStarted:!1,complete:!1,loading:!1,error:null,at:0},scopes:{},counts:null,statusUnavailable:[],archiveFacts:{},forgotten:{},stoppedTurns:{},archiveFailure:null,archiveUndo:null,draftsUndo:null,stagedByDiscard:null,deleteCandidate:null,error:null,cwd:"~",setCwd:n=>e(s=>{const r=Object.entries(s.drafts);return r.some(([,i])=>!i.sessionId)?{cwd:n,drafts:Object.fromEntries(r.map(([i,o])=>o.sessionId?[i,o]:[i,{...o,warmId:void 0,draftRequestId:crypto.randomUUID()}]))}:{cwd:n}}),fetchSessions:async(n=vf(t().cataloguePageable),s=!1)=>{const r=++Xn,i=t().answerSeq+1;e({answerSeq:i}),e({loading:!0,error:null});try{const o=await Af(n,s,(l,d)=>ce({op:"sessions.list",limit:l,include_archived:!0,...d?{with_counts:!0}:{}}));if(r!==Xn)return;const c=bo(o.sessions);e(l=>{const d={...l.pinFacts};for(const[M,z]of Object.entries(d))z.at>=i||delete d[M];const u=new Set(c.map(M=>M.session_id));let f=!1;const p={...l.forgotten};for(const[M,z]of Object.entries(p))z.at<i&&u.has(M)&&(delete p[M],f=!0);const w=f?p:l.forgotten,E=c.filter(M=>w[M.session_id]===void 0),h=Qn(o.next_cursor),_=h===null&&o.truncated!==!0,x=E.map(M=>M.session_id),I=l.sessions.filter(M=>w[M.session_id]===void 0&&(l.pinFacts[M.session_id]?.at??-1)>=i),re=bf({sessions:l.sessions,scopeIds:_f(l.scopes),keepIds:l.activeSessionId===null?[]:[l.activeSessionId],tailIds:_?[]:l.head.tailIds,page:E,merge:Rf});let H=re.rows;for(const M of I){const z=l.pinFacts[M.session_id],V=H.findIndex(le=>le.session_id===M.session_id);V===-1?H=[...H,{...M,pinned:z.pinned}]:H[V]={...H[V],pinned:z.pinned}}const ae=If(l.archiveFacts,i),Te=Cf(o.counts);return{sessions:H,pinFacts:d,archiveFacts:ae,forgotten:w,loading:!1,truncated:o.truncated===!0,head:{pageIds:x,tailIds:re.tailIds,nextCursor:h,tailCursor:_?null:l.head.tailStarted?l.head.tailCursor:h,tailStarted:l.head.tailStarted,complete:_,loading:!1,error:null,at:i},...Te===null?{}:{counts:Te},statusUnavailable:Array.isArray(o.degraded)?o.degraded.filter(M=>typeof M=="string"):[]}})}catch(o){r===Xn&&e({loading:!1,error:an(o,"Chats could not refresh. Retry to reconnect.")})}},fetchCatalogueTail:async()=>{const n=t().head,s=n.tailCursor;if(!(s===null||n.loading)){e(r=>({head:{...r.head,loading:!0,error:null,tailStarted:!0,tailCursor:s}}));try{const r=await ce({op:"sessions.list",limit:_o,include_archived:!0,cursor:s}),i=si(r.sessions,t().forgotten);e(o=>{const c=new Map(o.sessions.map((f,p)=>[f.session_id,p])),l=[...o.sessions],d=[];for(const f of i){const p=c.get(f.session_id);if(p===void 0){c.set(f.session_id,l.length),l.push(f),d.push(f.session_id);continue}l[p]=un(l[p],f)}const u=Qn(r.next_cursor);return{sessions:l,head:{...o.head,tailIds:[...o.head.tailIds,...d],tailCursor:u,complete:u===null,loading:!1,error:null}}})}catch(r){e(i=>({head:{...i.head,loading:!1,error:an(r,"Could not load more chats.")}}))}}},fetchScopePage:async(n,s,r=null,i=gf)=>{const o=ti(n,s);if(t().scopes[o]?.loading)return;const c=t().answerSeq+1;e({answerSeq:c}),e(l=>({scopes:{...l.scopes,[o]:{ids:l.scopes[o]?.ids??[],nextCursor:l.scopes[o]?.nextCursor??null,loading:!0,error:null,at:c}}}));try{const l=await ce({op:"sessions.list",limit:i,include_archived:!1,scope_kind:n,scope_name:s,...r===null?{}:{cursor:r}}),d=si(l.sessions,t().forgotten);e(u=>{const f=u.scopes[o];if(f===void 0||f.at!==c)return{};const p=r!==null&&l.cursor_missing!==!0,w=wf({sessions:u.sessions,previousIds:p?f.ids:[],page:d,merge:un}),E=Qn(l.next_cursor);return{sessions:w.rows,scopes:{...u.scopes,[o]:{ids:w.ids,nextCursor:E,loading:!1,error:null,at:c}}}})}catch(l){e(d=>{const u=d.scopes[o];return u===void 0||u.at!==c?{}:{scopes:{...d.scopes,[o]:{...u,loading:!1,error:an(l,"Could not load this group's chats.")}}}})}},clearScope:(n,s)=>{const r=ti(n,s);e(i=>{const o=i.scopes[r];if(o===void 0)return{};const c={...i.scopes};delete c[r];const l=i.activeSessionId,d=new Set(o.ids),u=new Set(i.head.pageIds),f=i.sessions.filter(p=>!d.has(p.session_id)||u.has(p.session_id)||l!==null&&p.session_id===l);return{scopes:c,sessions:f}})},setCataloguePageable:n=>{t().cataloguePageable!==n&&e({cataloguePageable:n})},setDraftWarmable:n=>{if(t().draftWarmable===n||(e({draftWarmable:n}),!n))return;const s=t().activeDraftKey,r=s?t().drafts[s]:void 0;if(!s||!r||r.sessionId||r.warmId)return;Ce.getState().inputByConversation[s]?.currentInput&&t().ensureDraftWarm(s)},setArchiveUndo:n=>{e({archiveUndo:n})},setDraftsUndo:n=>{e({draftsUndo:n})},setStagedByDiscard:n=>{e({stagedByDiscard:n})},restoreDraftsUndo:()=>e(n=>{const s=n.draftsUndo;if(!s)return{};const r={...n.drafts};for(const[o,c]of Object.entries(s.drafts))o in r||(r[o]=c);const i=Ce.getState();for(const[o,c]of Object.entries(s.composer)){const l=i.inputByConversation[o];(l?.currentInput??"").length>0||(l?.pendingText??null)!==null||i.restoreRow(o,c)}return{drafts:r,draftsUndo:null}}),clearArchiveFailure:()=>{e({archiveFailure:null})},setSessionArchived:async(n,s,r)=>{const i=t().answerSeq+1,o=t().archiveFacts[n]??null,c=r??t().sessions.find(l=>l.session_id===n)?.title;e(l=>({answerSeq:i,archiveFacts:{...l.archiveFacts,[n]:{archived:s,at:i,answered:!1}}}));try{return await ce({op:"sessions.archive",sessionId:n,archived:s}),e(l=>{const u=l.archiveFacts[n]?.at!==i;return{archiveFacts:u?l.archiveFacts:{...l.archiveFacts,[n]:{archived:s,at:i,answered:!0}},archiveUndo:u?l.archiveUndo:s?{sessionId:n,title:c??void 0,archived:!0,at:i}:null,archiveFailure:l.archiveFailure?.sessionId===n?null:l.archiveFailure}}),!0}catch(l){return e(d=>{const u=d.archiveFacts[n]?.at!==i,f={...d.archiveFacts};return u||(o?.answered===!0?f[n]=o:(delete f[n],o!==null&&t().fetchSessions())),{archiveFacts:u?d.archiveFacts:f,answerSeq:d.answerSeq+1,archiveFailure:{sessionId:n,at:d.answerSeq+1,archived:s,title:c||"Untitled chat",detail:l instanceof X&&l.message?l.message:""}}}),!1}},deleteSession:async n=>{try{return await ce({op:"sessions.delete",sessionId:n,confirmed:!0}),e(s=>Yn(s,n)),{ok:!0}}catch(s){const r=s instanceof X?s.status:null,i=s instanceof X?s.code??null:null;return r===404?(e(o=>Yn(o,n)),{ok:!0}):{ok:!1,guarded:i==="session_delete_refused",detail:s instanceof X&&s.message?s.message:"The conversation could not be deleted."}}},requestSessionDelete:n=>e({deleteCandidate:n}),createSession:async(n,s,r=crypto.randomUUID(),i,o)=>{try{const c=await ce({op:"sessions.create",requestId:r,cwd:n,...s?{target:s}:{},...i?{model:i}:{},...o?{draftId:o}:{}});return t().upsertSession({session_id:c.session_id,cwd:n,binding:c.binding}),c.session_id}catch(c){throw e({error:an(c,"Chat could not start. Retry with the same draft.")}),c}},setActiveSession:n=>{e({activeSessionId:n,activeDraftKey:null,validatingSessionId:null})},markTurnStopped:(n,s=Date.now())=>e(r=>({stoppedTurns:{...r.stoppedTurns,[n]:s}})),clearTurnStopped:n=>e(s=>{if(!(n in s.stoppedTurns))return s;const{[n]:r,...i}=s.stoppedTurns;return{stoppedTurns:i}}),openDraft:n=>{t().drafts[n]&&e({activeDraftKey:n,activeSessionId:null,validatingSessionId:null,error:null})},confirmSessionLive:n=>{n&&t().validatingSessionId===n&&e({validatingSessionId:null})},confirmSessionMissing:n=>{!n||t().validatingSessionId!==n||e({validatingSessionId:null,...Yn(t(),n)})},rearmReadAck:n=>{e(s=>({readAckRearm:Tf(s.readAckRearm,n)}))},publishReadAckNotice:(n,s,r)=>{e(i=>{const o=i.readAckNotice;return o?.sessionId===n&&o.kind===s?i:{readAckNotice:{sessionId:n,kind:s,revision:(o?.revision??0)+1,reason:r}}})},clearReadAckNotice:n=>{e(s=>s.readAckNotice?.sessionId===n?{readAckNotice:null}:s)},applyAttention:(n,s)=>{e(r=>{const i=ni(r.sessions,n,s);return i===r.sessions?r:{...r,sessions:i}})},applyAttentionMany:n=>{e(s=>{let r=s.sessions;for(const i of n){const o=i?.conversation_id;typeof o!="string"||!o.startsWith("session/")||(r=ni(r,o.slice(8),i))}return r===s.sessions?s:{...s,sessions:r}})},markAllRead:async()=>{const n=kf(t().sessions).map(r=>({sessionId:r.session_id,completionToken:r.attention?.completion_token}));if(n.length===0)return{attempted:0,cleared:0,superseded:0,unknown:0};const s=await ce({op:"attention.seen",items:n});return t().applyAttentionMany(s.read),{attempted:n.length,cleared:s.read.length,superseded:s.superseded.length,unknown:s.unknown.length}},applySessionStatus:(n,s,r,i)=>{e(o=>{const c=o.sessions.findIndex(p=>p.session_id===n);let l=!1;const d=o.sessions.map(p=>{if(p.status_epoch===void 0&&p.status_revision===void 0||p.status_epoch===i)return p;l=!0;const{status_revision:w,status_epoch:E,...h}=p;return h});if(c<0)return l?{...o,sessions:d}:o;const u=d[c],f=u.status?.code===s.code&&u.status?.label===s.label&&u.status_revision===r&&u.status_epoch===i;return f&&!l?o:(f||(d[c]={...u,status:s,status_revision:r,status_epoch:i}),{...o,sessions:d})})},openSession:async n=>t().activeSessionId===n&&!t().activeDraftKey?(t().rearmReadAck(n),!0):(e({activeSessionId:n,activeDraftKey:null,validatingSessionId:n,error:null}),t().rearmReadAck(n),!0),stageDraft:(n,s=!1)=>{const r=!s&&n?`draft:${n.kind}:${n.name}`:`draft:${crypto.randomUUID()}`,i=t().drafts[r];return e(o=>({activeDraftKey:r,validatingSessionId:null,error:null,drafts:{...o.drafts,[r]:i??{key:r,target:n,createRequestId:crypto.randomUUID(),admissionRequestId:crypto.randomUUID()}}})),r},updateDraft:(n,s)=>e(r=>{const i=r.drafts[n],o=s.key!==void 0&&s.createRequestId!==void 0&&s.admissionRequestId!==void 0;return!i&&!o?{}:{drafts:{...r.drafts,[n]:{...r.drafts[n],...s}}}}),setDraftModel:(n,s)=>e(r=>{const i=r.drafts[n];return i?{drafts:{...r.drafts,[n]:{...i,model:s,...i.sessionId?{}:{createRequestId:crypto.randomUUID(),warmId:void 0,draftRequestId:crypto.randomUUID()}}}}:{}}),ensureDraftWarm:n=>{const s=t();if(!s.draftWarmable)return;const r=s.drafts[n];if(!r||r.sessionId||r.warmId||!s.cwd)return;const i=r.draftRequestId??crypto.randomUUID();r.draftRequestId||t().updateDraft(n,{draftRequestId:i}),ce({op:"sessions.draft",requestId:i,cwd:s.cwd,...r.target?{target:r.target}:{},...r.model?{model:r.model}:{}}).then(o=>{const c=t().drafts[n];c&&!c.warmId&&!c.sessionId&&c.draftRequestId===i&&t().updateDraft(n,{warmId:o.draft_id})}).catch(()=>{})},finishDraft:(n,s)=>e(r=>{lf(n,s);const i={...r.drafts};return delete i[n],{drafts:i,...r.activeDraftKey===n?{activeDraftKey:null,activeSessionId:s}:{}}}),discardDraft:n=>e(s=>{const r={...s.drafts},i=r[n]?.sessionId??(n.startsWith("send:")?n.slice(5):void 0),o=r[n],c=Ce.getState().inputByConversation[n];on(n),i&&i!==n&&on(i),delete r[n],Ce.getState().clearAll(n);const l=o?{at:s.answerSeq+1,keys:[n],drafts:{[n]:o},composer:c?{[n]:c}:{}}:null;return{drafts:r,...l?{answerSeq:l.at,draftsUndo:l}:{},...s.activeDraftKey===n?{activeDraftKey:null}:{}}}),discardDrafts:n=>e(s=>{const r={...s.drafts};let i=!1;const o=[],c={},l={};for(const u of n){if(!(u in r))continue;const f=r[u];if(!f)continue;const p=f.sessionId??(u.startsWith("send:")?u.slice(5):void 0);on(u),p&&p!==u&&on(p),o.push(u),c[u]=f;const w=Ce.getState().inputByConversation[u];w&&(l[u]=w),delete r[u],Ce.getState().clearAll(u),s.activeDraftKey===u&&(i=!0)}if(o.length===0)return{};const d=s.answerSeq+1;return{drafts:r,answerSeq:d,draftsUndo:{at:d,keys:o,drafts:c,composer:l},...i?{activeDraftKey:null}:{}}}),resolveHeldFromServer:(n,s,r)=>e(i=>{const o=Object.entries(i.drafts).filter(([,V])=>vs(V,n)&&V.undelivered!==void 0&&s.includes(V.undelivered.recordId));let c=i.drafts;if(o.length>0){c={...c};for(const[V,le]of o){const{undelivered:he,...Ee}=le;c[V]=Ee}}const l=Object.entries(c).find(([,V])=>vs(V,n)&&V.admissionAttempted===!0&&V.pending!==!0&&V.submittedText!==void 0);if(!l)return o.length>0?{drafts:c}:{};const[d,u]=l,f=u.admissionRequestId,p=s.includes(f);if(!p&&!r)return o.length>0?{drafts:c}:{};const{admissionAttempted:w,submittedText:E,submittedAttachments:h,submittedImages:_,submittedMode:x,submittedInputMode:I,submittedInputPath:re,heldClaimCode:H,error:ae,errorCode:Te,errorRetry:M,...z}=u;return p||gs(n,f),{drafts:{...c,[d]:{...z,...p?{}:{undelivered:{recordId:f,text:E??"",attachments:h??[]}},admissionRequestId:crypto.randomUUID()}}}}),bindSession:(n,s)=>t().setActiveSession(s),beginAnswer:()=>{const n=t().answerSeq+1;return e({answerSeq:n}),n},applySearchAnswer:(n,s)=>e(r=>{let i=null,o=null,c=null;for(const l of s){const d=r.archiveFacts[l.id];if(d!==void 0&&d.at<n&&(c=c??{...r.archiveFacts},delete c[l.id]),typeof l.pinned!="boolean")continue;const u=r.pinFacts[l.id];if(!(u!==void 0&&u.at>=n)&&(u!==void 0&&(i=i??{...r.pinFacts},delete i[l.id]),r.sessions.some(f=>f.session_id===l.id&&f.pinned!==l.pinned))){o=o??r.sessions.map(f=>({...f}));for(const f of o)f.session_id===l.id&&(f.pinned=l.pinned===!0)}}return i===null&&o===null&&c===null?{}:{...i===null?{}:{pinFacts:i},...o===null?{}:{sessions:o},...c===null?{}:{archiveFacts:c}}}),setSessionPin:async(n,s,r)=>{const i=t().sessions.find(p=>p.session_id===n),o=t().pinFacts[n]??null,c=i===void 0?o?.pinned??!1:i.pinned===!0,l=i===void 0&&r!==void 0?{session_id:n,title:r.title||"Untitled chat",updated_at:r.updated_at,pinned:s}:null,d=t().beginAnswer(),u=i?.title??r?.title,f=i?.updated_at??r?.updated_at;e(p=>({sessions:l===null?p.sessions.map(w=>w.session_id===n?{...w,pinned:s}:w):[...p.sessions,l],pinFacts:{...p.pinFacts,[n]:{pinned:s,at:d,title:u,updated_at:f}},pinFailure:null}));try{const p=await ce({op:"sessions.pin",sessionId:n,pinned:s});let w=!1;return e(E=>{const h=E.pinFacts[n];return h===void 0||h.at!==d?{}:(w=!0,{sessions:E.sessions.map(_=>_.session_id===n?{..._,pinned:p.pinned===!0}:_),pinFacts:{...E.pinFacts,[n]:{...h,pinned:p.pinned===!0}}})}),w}catch(p){return e(w=>{const E=w.pinFacts[n];if(E!==void 0&&E.at!==d)return{};const h={...w.pinFacts};return o===null&&i===void 0?delete h[n]:h[n]={pinned:c,at:Math.max(o?.at??0,d),title:o?.title??u,updated_at:o?.updated_at??f},{sessions:w.sessions.map(_=>_.session_id===n?{..._,pinned:c}:_),pinFacts:h,pinFailure:{sessionId:n,pinned:s,title:i?.title||"this chat",detail:In(p,"")}}}),!1}},upsertSession:n=>e(s=>({sessions:s.sessions.some(i=>i.session_id===n.session_id)?s.sessions.map(i=>i.session_id===n.session_id?un(i,n):i):[...s.sessions,n]}))}),{name:"canonical-sessions-storage",merge:Df,partialize:e=>({sessionByAgent:e.sessionByAgent,activeSessionId:e.activeSessionId,activeDraftKey:e.activeDraftKey,cwd:e.cwd,forgotten:Object.fromEntries(Object.entries(e.forgotten).map(([t,n])=>[t,{at:0,title:n.title}])),drafts:Object.fromEntries(Object.entries(e.drafts).map(([t,n])=>[t,{...n,pending:!1,warmId:void 0}]))})}));var Gs=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},ct=typeof window>"u"||"Deno"in globalThis;function _s(){}function vm(e,t){return typeof e=="function"?e(t):e}function bs(e){return typeof e=="number"&&e>=0&&e!==1/0}function So(e,t){return Math.max(e+(t||0)-Date.now(),0)}function fn(e,t){return typeof e=="function"?e(t):e}function be(e,t){return typeof e=="function"?e(t):e}function _m(e,t){const{type:n="all",exact:s,fetchStatus:r,predicate:i,queryKey:o,stale:c}=e;if(o){if(s){if(t.queryHash!==Lf(o,t.options))return!1}else if(!Hs(t.queryKey,o))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||r&&r!==t.state.fetchStatus||i&&!i(t))}function bm(e,t){const{exact:n,status:s,predicate:r,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(ws(t.options.mutationKey)!==ws(i))return!1}else if(!Hs(t.options.mutationKey,i))return!1}return!(s&&t.state.status!==s||r&&!r(t))}function Lf(e,t){return(t?.queryKeyHashFn||ws)(e)}function ws(e){return JSON.stringify(e,(t,n)=>ks(n)?Object.keys(n).sort().reduce((s,r)=>(s[r]=n[r],s),{}):n)}function Hs(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Hs(e[n],t[n])):!1}function ko(e,t){if(e===t)return e;const n=ri(e)&&ri(t);if(n||ks(e)&&ks(t)){const s=n?e:Object.keys(e),r=s.length,i=n?t:Object.keys(t),o=i.length,c=n?[]:{};let l=0;for(let d=0;d<o;d++){const u=n?d:i[d];(!n&&s.includes(u)||n)&&e[u]===void 0&&t[u]===void 0?(c[u]=void 0,l++):(c[u]=ko(e[u],t[u]),c[u]===e[u]&&e[u]!==void 0&&l++)}return r===o&&l===r?e:c}return t}function Ss(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function ri(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ks(e){if(!ii(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!ii(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ii(e){return Object.prototype.toString.call(e)==="[object Object]"}function Nf(e){return new Promise(t=>{setTimeout(t,e)})}function Ts(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?ko(e,t):t}function wm(e){return e}function Sm(e,t,n=0){const s=[...e,t];return n&&s.length>n?s.slice(1):s}function km(e,t,n=0){const s=[t,...e];return n&&s.length>n?s.slice(0,-1):s}var To=Symbol();function Mf(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===To?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var jf=class extends Gs{#t;#e;#n;constructor(){super(),this.#n=e=>{if(!ct&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#t!==e&&(this.#t=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#t=="boolean"?this.#t:globalThis.document?.visibilityState!=="hidden"}},Eo=new jf,$f=class extends Gs{#t=!0;#e;#n;constructor(){super(),this.#n=e=>{if(!ct&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#e||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#e?.(),this.#e=void 0)}setEventListener(e){this.#n=e,this.#e?.(),this.#e=e(this.setOnline.bind(this))}setOnline(e){this.#t!==e&&(this.#t=e,this.listeners.forEach(n=>{n(e)}))}isOnline(){return this.#t}},xo=new $f;function Es(){let e,t;const n=new Promise((r,i)=>{e=r,t=i});n.status="pending",n.catch(()=>{});function s(r){Object.assign(n,r),delete n.resolve,delete n.reject}return n.resolve=r=>{s({status:"fulfilled",value:r}),e(r)},n.reject=r=>{s({status:"rejected",reason:r}),t(r)},n}function Uf(e){return Math.min(1e3*2**e,3e4)}function Io(e){return(e??"online")==="online"?xo.isOnline():!0}var Co=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Jn(e){return e instanceof Co}function Ff(e){let t=!1,n=0,s=!1,r;const i=Es(),o=h=>{s||(p(new Co(h)),e.abort?.())},c=()=>{t=!0},l=()=>{t=!1},d=()=>Eo.isFocused()&&(e.networkMode==="always"||xo.isOnline())&&e.canRun(),u=()=>Io(e.networkMode)&&e.canRun(),f=h=>{s||(s=!0,e.onSuccess?.(h),r?.(),i.resolve(h))},p=h=>{s||(s=!0,e.onError?.(h),r?.(),i.reject(h))},w=()=>new Promise(h=>{r=_=>{(s||d())&&h(_)},e.onPause?.()}).then(()=>{r=void 0,s||e.onContinue?.()}),E=()=>{if(s)return;let h;const _=n===0?e.initialPromise:void 0;try{h=_??e.fn()}catch(x){h=Promise.reject(x)}Promise.resolve(h).then(f).catch(x=>{if(s)return;const I=e.retry??(ct?0:3),re=e.retryDelay??Uf,H=typeof re=="function"?re(n,x):re,ae=I===!0||typeof I=="number"&&n<I||typeof I=="function"&&I(n,x);if(t||!ae){p(x);return}n++,e.onFail?.(n,x),Nf(H).then(()=>d()?void 0:w()).then(()=>{t?p(x):E()})})};return{promise:i,cancel:o,continue:()=>(r?.(),i),cancelRetry:c,continueRetry:l,canStart:u,start:()=>(u()?E():w().then(E),i)}}var Bf=e=>setTimeout(e,0);function Zf(){let e=[],t=0,n=c=>{c()},s=c=>{c()},r=Bf;const i=c=>{t?e.push(c):r(()=>{n(c)})},o=()=>{const c=e;e=[],c.length&&r(()=>{s(()=>{c.forEach(l=>{n(l)})})})};return{batch:c=>{let l;t++;try{l=c()}finally{t--,t||o()}return l},batchCalls:c=>(...l)=>{i(()=>{c(...l)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{s=c},setScheduler:c=>{r=c}}}var zs=Zf(),Gf=class{#t;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),bs(this.gcTime)&&(this.#t=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ct?1/0:5*60*1e3))}clearGcTimeout(){this.#t&&(clearTimeout(this.#t),this.#t=void 0)}},Tm=class extends Gf{#t;#e;#n;#r;#s;#a;#o;constructor(e){super(),this.#o=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#n=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Hf(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#s?.promise}setOptions(e){this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#n.remove(this)}setData(e,t){const n=Ts(this.state.data,e,this.options);return this.#i({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#s?.promise;return this.#s?.cancel(e),t?t.then(_s).catch(_s):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#t)}isActive(){return this.observers.some(e=>be(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===To||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(e=0){return this.state.isInvalidated||this.state.data===void 0||!So(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#s?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#s?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#s&&(this.#o?this.#s.cancel({revert:!0}):this.#s.cancelRetry()),this.scheduleGc()),this.#n.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({type:"invalidate"})}fetch(e,t){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#s)return this.#s.continueRetry(),this.#s.promise}if(e&&this.setOptions(e),!this.options.queryFn){const c=this.observers.find(l=>l.options.queryFn);c&&this.setOptions(c.options)}const n=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(this.#o=!0,n.signal)})},r=()=>{const c=Mf(this.options,t),l={client:this.#r,queryKey:this.queryKey,meta:this.meta};return s(l),this.#o=!1,this.options.persister?this.options.persister(c,l,this):c(l)},i={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:r};s(i),this.options.behavior?.onFetch(i,this),this.#e=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==i.fetchOptions?.meta)&&this.#i({type:"fetch",meta:i.fetchOptions?.meta});const o=c=>{Jn(c)&&c.silent||this.#i({type:"error",error:c}),Jn(c)||(this.#n.config.onError?.(c,this),this.#n.config.onSettled?.(this.state.data,c,this)),this.scheduleGc()};return this.#s=Ff({initialPromise:t?.initialPromise,fn:i.fetchFn,abort:n.abort.bind(n),onSuccess:c=>{if(c===void 0){o(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(c)}catch(l){o(l);return}this.#n.config.onSuccess?.(c,this),this.#n.config.onSettled?.(c,this.state.error,this),this.scheduleGc()},onError:o,onFail:(c,l)=>{this.#i({type:"failed",failureCount:c,error:l})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:i.options.retry,retryDelay:i.options.retryDelay,networkMode:i.options.networkMode,canRun:()=>!0}),this.#s.start()}#i(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...Ro(n.data,this.options),fetchMeta:e.meta??null};case"success":return{...n,data:e.data,dataUpdateCount:n.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const s=e.error;return Jn(s)&&s.revert&&this.#e?{...this.#e,fetchStatus:"idle"}:{...n,error:s,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),zs.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),this.#n.notify({query:this,type:"updated",action:e})})}};function Ro(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Io(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Hf(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,s=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var zf=class extends Gs{constructor(e,t){super(),this.options=t,this.#t=e,this.#i=null,this.#o=Es(),this.options.experimental_prefetchInRender||this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(t)}#t;#e=void 0;#n=void 0;#r=void 0;#s;#a;#o;#i;#m;#f;#p;#l;#d;#c;#h=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#e.addObserver(this),oi(this.#e,this.options)?this.#u():this.updateResult(),this.#_())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return xs(this.#e,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return xs(this.#e,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#w(),this.#e.removeObserver(this)}setOptions(e){const t=this.options,n=this.#e;if(this.options=this.#t.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof be(this.options.enabled,this.#e)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#S(),this.#e.setOptions(this.options),t._defaulted&&!Ss(this.options,t)&&this.#t.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#e,observer:this});const s=this.hasListeners();s&&ai(this.#e,n,this.options,t)&&this.#u(),this.updateResult(),s&&(this.#e!==n||be(this.options.enabled,this.#e)!==be(t.enabled,this.#e)||fn(this.options.staleTime,this.#e)!==fn(t.staleTime,this.#e))&&this.#g();const r=this.#y();s&&(this.#e!==n||be(this.options.enabled,this.#e)!==be(t.enabled,this.#e)||r!==this.#c)&&this.#v(r)}getOptimisticResult(e){const t=this.#t.getQueryCache().build(this.#t,e),n=this.createResult(t,e);return Kf(this,n)&&(this.#r=n,this.#a=this.options,this.#s=this.#e.state),n}getCurrentResult(){return this.#r}trackResult(e,t){const n={};return Object.keys(e).forEach(s=>{Object.defineProperty(n,s,{configurable:!1,enumerable:!0,get:()=>(this.trackProp(s),t?.(s),e[s])})}),n}trackProp(e){this.#h.add(e)}getCurrentQuery(){return this.#e}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#t.defaultQueryOptions(e),n=this.#t.getQueryCache().build(this.#t,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#u({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#u(e){this.#S();let t=this.#e.fetch(this.options,e);return e?.throwOnError||(t=t.catch(_s)),t}#g(){this.#b();const e=fn(this.options.staleTime,this.#e);if(ct||this.#r.isStale||!bs(e))return;const n=So(this.#r.dataUpdatedAt,e)+1;this.#l=setTimeout(()=>{this.#r.isStale||this.updateResult()},n)}#y(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#e):this.options.refetchInterval)??!1}#v(e){this.#w(),this.#c=e,!(ct||be(this.options.enabled,this.#e)===!1||!bs(this.#c)||this.#c===0)&&(this.#d=setInterval(()=>{(this.options.refetchIntervalInBackground||Eo.isFocused())&&this.#u()},this.#c))}#_(){this.#g(),this.#v(this.#y())}#b(){this.#l&&(clearTimeout(this.#l),this.#l=void 0)}#w(){this.#d&&(clearInterval(this.#d),this.#d=void 0)}createResult(e,t){const n=this.#e,s=this.options,r=this.#r,i=this.#s,o=this.#a,l=e!==n?e.state:this.#n,{state:d}=e;let u={...d},f=!1,p;if(t._optimisticResults){const z=this.hasListeners(),V=!z&&oi(e,t),le=z&&ai(e,n,t,s);(V||le)&&(u={...u,...Ro(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:w,errorUpdatedAt:E,status:h}=u;p=u.data;let _=!1;if(t.placeholderData!==void 0&&p===void 0&&h==="pending"){let z;r?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(z=r.data,_=!0):z=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,z!==void 0&&(h="success",p=Ts(r?.data,z,t),f=!0)}if(t.select&&p!==void 0&&!_)if(r&&p===i?.data&&t.select===this.#m)p=this.#f;else try{this.#m=t.select,p=t.select(p),p=Ts(r?.data,p,t),this.#f=p,this.#i=null}catch(z){this.#i=z}this.#i&&(w=this.#i,p=this.#f,E=Date.now(),h="error");const x=u.fetchStatus==="fetching",I=h==="pending",re=h==="error",H=I&&x,ae=p!==void 0,M={status:h,fetchStatus:u.fetchStatus,isPending:I,isSuccess:h==="success",isError:re,isInitialLoading:H,isLoading:H,data:p,dataUpdatedAt:u.dataUpdatedAt,error:w,errorUpdatedAt:E,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:x,isRefetching:x&&!I,isLoadingError:re&&!ae,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:re&&ae,isStale:Vs(e,t),refetch:this.refetch,promise:this.#o};if(this.options.experimental_prefetchInRender){const z=he=>{M.status==="error"?he.reject(M.error):M.data!==void 0&&he.resolve(M.data)},V=()=>{const he=this.#o=M.promise=Es();z(he)},le=this.#o;switch(le.status){case"pending":e.queryHash===n.queryHash&&z(le);break;case"fulfilled":(M.status==="error"||M.data!==le.value)&&V();break;case"rejected":(M.status!=="error"||M.error!==le.reason)&&V();break}}return M}updateResult(){const e=this.#r,t=this.createResult(this.#e,this.options);if(this.#s=this.#e.state,this.#a=this.options,this.#s.data!==void 0&&(this.#p=this.#e),Ss(t,e))return;this.#r=t;const n=()=>{if(!e)return!0;const{notifyOnChangeProps:s}=this.options,r=typeof s=="function"?s():s;if(r==="all"||!r&&!this.#h.size)return!0;const i=new Set(r??this.#h);return this.options.throwOnError&&i.add("error"),Object.keys(this.#r).some(o=>{const c=o;return this.#r[c]!==e[c]&&i.has(c)})};this.#k({listeners:n()})}#S(){const e=this.#t.getQueryCache().build(this.#t,this.options);if(e===this.#e)return;const t=this.#e;this.#e=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#_()}#k(e){zs.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#r)}),this.#t.getQueryCache().notify({query:this.#e,type:"observerResultsUpdated"})})}};function Vf(e,t){return be(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function oi(e,t){return Vf(e,t)||e.state.data!==void 0&&xs(e,t,t.refetchOnMount)}function xs(e,t,n){if(be(t.enabled,e)!==!1){const s=typeof n=="function"?n(e):n;return s==="always"||s!==!1&&Vs(e,t)}return!1}function ai(e,t,n,s){return(e!==t||be(s.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Vs(e,n)}function Vs(e,t){return be(t.enabled,e)!==!1&&e.isStaleByTime(fn(t.staleTime,e))}function Kf(e,t){return!Ss(e.getCurrentResult(),t)}var Ao=T.createContext(void 0),Wf=e=>{const t=T.useContext(Ao);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Em=({client:e,children:t})=>(T.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),De.jsx(Ao.Provider,{value:e,children:t})),Oo=T.createContext(!1),Yf=()=>T.useContext(Oo);Oo.Provider;function Qf(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Xf=T.createContext(Qf()),Jf=()=>T.useContext(Xf);function qf(e,t){return typeof e=="function"?e(...t):!!e}function ci(){}var ep=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},tp=e=>{T.useEffect(()=>{e.clearReset()},[e])},np=({result:e,errorResetBoundary:t,throwOnError:n,query:s,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&s&&(r&&e.data===void 0||qf(n,[e.error,s])),sp=e=>{const t=e.staleTime;e.suspense&&(e.staleTime=typeof t=="function"?(...n)=>Math.max(t(...n),1e3):Math.max(t??1e3,1e3),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3)))},rp=(e,t)=>e.isLoading&&e.isFetching&&!t,ip=(e,t)=>e?.suspense&&t.isPending,li=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function op(e,t,n){const s=Wf(),r=Yf(),i=Jf(),o=s.defaultQueryOptions(e);s.getDefaultOptions().queries?._experimental_beforeQuery?.(o),o._optimisticResults=r?"isRestoring":"optimistic",sp(o),ep(o,i),tp(i);const c=!s.getQueryCache().get(o.queryHash),[l]=T.useState(()=>new t(s,o)),d=l.getOptimisticResult(o),u=!r&&e.subscribed!==!1;if(T.useSyncExternalStore(T.useCallback(f=>{const p=u?l.subscribe(zs.batchCalls(f)):ci;return l.updateResult(),p},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),T.useEffect(()=>{l.setOptions(o)},[o,l]),ip(o,d))throw li(o,l,i);if(np({result:d,errorResetBoundary:i,throwOnError:o.throwOnError,query:s.getQueryCache().get(o.queryHash),suspense:o.suspense}))throw d.error;return s.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!ct&&rp(d,r)&&(c?li(o,l,i):s.getQueryCache().get(o.queryHash)?.promise)?.catch(ci).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?d:l.trackResult(d)}function Po(e,t){return op(e,zf)}/**
|
|
21
21
|
* @license lucide-react v0.507.0 - ISC
|
|
22
22
|
*
|
|
23
23
|
* This source code is licensed under the ISC license.
|
|
24
24
|
* See the LICENSE file in the root directory of this source tree.
|
|
25
|
-
*/const
|
|
25
|
+
*/const ap=[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]],qn=Tn("command",ap);/**
|
|
26
26
|
* @license lucide-react v0.507.0 - ISC
|
|
27
27
|
*
|
|
28
28
|
* This source code is licensed under the ISC license.
|
|
29
29
|
* See the LICENSE file in the root directory of this source tree.
|
|
30
|
-
*/const
|
|
30
|
+
*/const cp=[["polyline",{points:"9 10 4 15 9 20",key:"r3jprv"}],["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}]],di=Tn("corner-down-left",cp);/**
|
|
31
31
|
* @license lucide-react v0.507.0 - ISC
|
|
32
32
|
*
|
|
33
33
|
* This source code is licensed under the ISC license.
|
|
34
34
|
* See the LICENSE file in the root directory of this source tree.
|
|
35
|
-
*/const
|
|
35
|
+
*/const lp=[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]],xm=Tn("mic",lp);/**
|
|
36
36
|
* @license lucide-react v0.507.0 - ISC
|
|
37
37
|
*
|
|
38
38
|
* This source code is licensed under the ISC license.
|
|
39
39
|
* See the LICENSE file in the root directory of this source tree.
|
|
40
|
-
*/const
|
|
40
|
+
*/const dp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Im=Tn("square",dp);class Do extends Error{status;constructor(t,n){super(n),this.name="TranscriptionRequestError",this.status=t}}function Cm(e){const t=e instanceof Do?e.status:null;if(t===402)return gp;if(t===401||t===403)return ui;const n=e instanceof Error?e.message:"",s=Lo(n);if(s==="")return vp;if(bp.test(s)){const o=Cp(s),c=Rp(s);return c!==null?o===null?`Dictation failed: the account behind dictation is out of credits. If it's yours, top it up at ${c}.`:`Dictation failed: the ${o} account behind dictation is out of credits. If it's yours, top it up at ${c}.`:yp}if(wp.test(s))return ui;const r=up(Ap(s)),i=r.endsWith("…")?" ":". ";return`Dictation failed: ${r.replace(mp,"")}${i}${_p}`}function up(e){const[t]=fp.exec(e)??[];return t===void 0||t.length<2||pp.test(t.slice(1))||!hp.test(t)?e:e[0].toLowerCase()+e.slice(1)}const fp=/^[\p{L}\p{N}'’-]+/u,pp=/[\p{Lu}\p{N}]/u,hp=new RegExp("^\\p{Lu}","u"),mp=/\.$/,gp="Dictation failed: you're out of Radient credits. Get more credits, then try again.",ui="Dictation failed: your Radient sign-in was refused. Sign in to Radient, then try again.",yp="Dictation failed: the account behind dictation is out of credits. If it's yours, top it up.",vp="Dictation failed: the server gave no reason. Try again, or report it with the app's log.",_p="Try again, or report it with the app's log.",bp=/insufficient_quota|insufficient funds|no credits remaining|exceeded your current quota|out of credits|billing (?:hard )?limit|credit balance is too low/i,wp=/unauthorized|invalid[ _-]?api[ _-]?key|incorrect api key|no api key|authentication|permission denied|forbidden/i,Sp=/^([A-Za-z][A-Za-z0-9&.+_-]*(?: [A-Za-z][A-Za-z0-9&.+_-]*){0,2}) API error\b/,kp=/\bhttps?:\/\/[^\s"'<>),]+/,Tp=/^https?:\/\//,Ep=/[.,;:]+$/,xp=40,fi=80,Ip=40;function Lo(e){return e.replace(/\s+/g," ").trim()}function Cp(e){return Sp.exec(e)?.[1]??null}function Rp(e){const t=kp.exec(e)?.[0];if(t===void 0)return null;const n=t.replace(Tp,"").replace(Ep,"");return n===""||n.length>xp?null:n}function Ap(e){const t=Pp(e);if(t!==null)return pi(Lo(t));const n=e.replace(Op,"").trim();return pi(n===""?e:n)}const Op=/^(?:GET|POST|PUT|PATCH|DELETE|HEAD)\s+\S+\s+returned\s+\d{3}\s*/i;function Pp(e){const t=e.indexOf("{"),n=e.lastIndexOf("}");if(t===-1||n<=t)return null;let s;try{s=JSON.parse(e.slice(t,n+1))}catch{return null}const r=s;if(typeof r?.message=="string"&&r.message.trim()!=="")return r.message;const i=r?.error??null;return typeof i?.message=="string"&&i.message.trim()!==""?i.message:null}function pi(e){if(e.length<=fi)return e;const t=e.slice(0,fi),n=t.lastIndexOf(" ");return`${(n>Ip?t.slice(0,n):t).trimEnd()}…`}const Rm="No words were picked up. Try again a little closer to the microphone.",Am={async createTranscription(e,t){const n={};t.model!==void 0&&(n.model=t.model),t.prompt!==void 0&&(n.prompt=t.prompt),t.response_format!==void 0&&(n.response_format=t.response_format),t.temperature!==void 0&&(n.temperature=t.temperature.toString()),t.language!==void 0&&(n.language=t.language),t.provider!==void 0&&(n.provider=t.provider);const s=new Uint8Array(await t.file.arrayBuffer()),r=await fl({op:"transcription.create",fileName:t.file.name||"audio",mimeType:t.file.type||"application/octet-stream",fields:n},s);if(r.kind!=="json")throw new Do(r.status,pl(r).message);return r.body}},Dp=a.object({VITE_LOCAL_OPERATOR_API_URL:a.string().url("API URL must be a valid URL").optional().default("http://localhost:1111"),VITE_RADIENT_SERVER_BASE_URL:a.string().url("Radient server base URL must be a valid URL").optional().default("https://api.radienthq.com"),VITE_RADIENT_CLIENT_ID:a.string({required_error:"VITE_RADIENT_CLIENT_ID is required",invalid_type_error:"VITE_RADIENT_CLIENT_ID must be a string"}).optional().default("b0fd1aa8-05a2-4ca2-bac2-82db293e7584"),VITE_DISABLE_BACKEND_MANAGER:a.enum(["true","false"]).optional().default("false"),VITE_LOG_LEVEL:a.enum(["debug","info","warn","error"]).optional().default("info"),VITE_PUBLIC_POSTHOG_KEY:a.string().optional().default("phc_u6n9doAtCUbpFbydIqzupCxqCaGUO4SiHMEU5ESvQRL"),VITE_PUBLIC_POSTHOG_HOST:a.string().url("PostHog host must be a valid URL").optional().default("https://us.i.posthog.com")}),Lp={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_GOOGLE_CLIENT_ID:"778402241192-7akrj44ptshfhh067e1lchko5vslcedk.apps.googleusercontent.com",VITE_GOOGLE_CLIENT_SECRET:"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",VITE_MICROSOFT_CLIENT_ID:"ce6f7818-fa68-4063-ae88-5c4888bc4f9f",VITE_MICROSOFT_TENANT_ID:"1cbff824-c118-40e7-86f6-0e8bef31658d"};function Np(){try{const e={};for(const[t,n]of Object.entries(Lp))t.startsWith("VITE_")&&(e[t]=String(n));return Dp.parse(e)}catch(e){if(e instanceof ye){const t=e.errors.map(n=>`${n.path.join(".")}: ${n.message}`).join(`
|
|
41
41
|
`);throw new Error(`Configuration validation failed:
|
|
42
|
-
${t}`)}throw new Error(`Failed to load configuration: ${e instanceof Error?e.message:String(e)}`)}}const es=Pp();let Lo=null;function Im(e){Lo=e}const Cm={get baseUrl(){return Lo??es.VITE_LOCAL_OPERATOR_API_URL},radientBaseUrl:es.VITE_RADIENT_SERVER_BASE_URL,radientClientId:es.VITE_RADIENT_CLIENT_ID};function Rm(e){return e!=="detached"&&e!=="wedged"}function No(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function Am(e){if(!e)return{title:"Not connected to a Local Operator server.",detail:null,retry:!0};const t=e.addressSubstitution??null;if(t&&e.state!=="detached"&&e.state!=="wedged")return t.kind==="substituted"?{title:`Serving on ${t.serving}, not the address this app is configured for.`,detail:t.holder?`${t.holder}. The app uses ${t.serving} while that holds.${t.reclaim?` ${t.reclaim}`:""} It is back on ${t.configured} on its next launch or recovery.`:`The daemon this app is using was already running, so it did not start one. It looks for ${t.configured} again on its next launch or recovery.`,retry:!0}:{title:`Back on ${t.configured}, the address this app is configured for.`,detail:`It served on ${t.serving} while the configured address was held; it is on the address it was told to use again.`,retry:!1,dismiss:!0};const n=e.detail?.trim()?e.detail.trim():null,s=No(e.pairing?.cause??null);switch(e.state){case"wedged":return{title:"A Local Operator server is running on this machine and this app is not attached to it.",detail:n,retry:s};case"detached":return e.reconnecting?{title:s?"Not connected to a Local Operator server. If one is still running, the app reconnects to it on its own.":"Not connected to a Local Operator server.",detail:n,retry:s}:{title:s?"The Local Operator server stopped. The app keeps looking for one and attaches to it when it appears.":"Not connected to a Local Operator server. The app keeps looking for one.",detail:n,retry:s};default:return null}}function Dp(e){if(ol(e))return"deadline";const t=e instanceof X?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const Mo={unreachable:"",deadline:"",unauthorized:"",outdated:"Update the server and try again.",unknown:""},Is={unreachable:"The Local Operator server is not answering.",deadline:"The Local Operator server did not answer in time.",unauthorized:"This app cannot authenticate to the running Local Operator server.",outdated:"The Local Operator server is older than this app expects.",unknown:""};function Lp(e,t){const n=Dp(t);return[e,Is[n],Mo[n]].filter(Boolean).join(" ")}const Cs={successor:"The Local Operator server was replaced while this app was running. Pairing with the new one.","governed-elsewhere":"The Local Operator server on this machine is already managed by another program, so this app cannot use its settings, provider sign-in, slash commands or MCP management.","pre-handshake":"The Local Operator server on this machine is older than the pairing handshake this app uses, so this app cannot drive its controls. The server itself, and anything you run against it from the terminal, are unaffected.","credential-refused":"This app's credential for the running Local Operator server was refused, so provider sign-in, settings, slash commands and MCP management are unavailable.",unpaired:"This app is not paired with the running Local Operator server, so provider sign-in, settings, slash commands and MCP management are unavailable."},Np={successor:"This conversation cannot be read here until the app finishes pairing with the replacement server. Your chats are still on that server.","governed-elsewhere":"This conversation cannot be read here: the server's desktop controls belong to another program. Your chats are still on that server.","pre-handshake":"This conversation cannot be read here: that server is older than the pairing handshake this app uses. Your chats are still on that server.","credential-refused":"This conversation cannot be read here: the server refused this app's credential. Your chats are still on that server.",unpaired:"This conversation cannot be read here: the app is not paired with the running server. Your chats are still on that server."};function Om(e,t){return e!=="unpaired"?null:Np[t??"unpaired"]}function Pm(e,t){return e!=="unpaired"?null:Cs[t??"unpaired"]}function Dm(e){const{kind:t,unpaired:n,answered:s,cause:r=null,servedByThisApp:i=!1}=e;return r==="pre-handshake"?i:r!==null||n?!1:s?i:t==="outdated"}function Lm(e){const{kind:t,unpaired:n,missing:s,answered:r,cause:i=null}=e;if(i!==null)return Cs[i];if(!r){if(t==="unreachable")return`${Is.unreachable} Provider sign-in, settings, slash commands and MCP management need it running.`;if(t==="unauthorized")return"This app cannot authenticate to the running Local Operator server, so provider sign-in, settings, slash commands and MCP management are unavailable.";if(t==="deadline")return`${Is.deadline} Provider sign-in, settings, slash commands and MCP management need it answering.`;if(t==="outdated")return`The Local Operator server is older than this app expects, so provider sign-in, settings, slash commands and MCP management are off. ${Mo.outdated}`}return n?Cs.unpaired:r?`The Local Operator server is missing ${s.join(", ")} support. Update it to enable those surfaces.`:"Provider sign-in, settings, slash commands and MCP management are unavailable because the Local Operator server did not answer as expected."}const Mp=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function Nm(e,t=null){return t!==null||!e?!0:Mp.filter(s=>(e.features?.[s]??0)<1).length>0||e.desktop_available!==!0}function jp(e,t){return t instanceof X&&t.status===null?!1:e<1}const $p={successor:"Your settings could not be loaded: the app is pairing with the server that replaced the one it was using.","governed-elsewhere":"Your settings could not be loaded: another program is managing this machine's Local Operator server, so this page cannot read or change them here.","pre-handshake":"Your settings could not be loaded: the server this app is talking to is older than the pairing handshake, so this page cannot read them from it.","credential-refused":"Your settings could not be loaded: the server refused this app's credential, so this page cannot read them from it.",unpaired:"Your settings could not be loaded: this app is not paired with the running server, so this page cannot read them from it."};function Mm(e,t,n){return e===null?{sentence:Lp(t,n),remedy:!0}:{sentence:$p[e],remedy:No(e)}}const jo={capabilities:["desktop","capabilities"],providers:["desktop","auth","providers"],commands:["desktop","commands"],accounts:["desktop","auth","accounts"],catalogue:["desktop","models"],credentials:e=>["desktop","credentials",e]},Up=3e4,Fp=15e3;function Bp(e){return e?.desktop_available===!0}function jm(){return Oo({queryKey:jo.capabilities,queryFn:async()=>{try{return await ce({op:"capabilities"})}catch(e){throw e instanceof Error?e:new Error(String(e))}},staleTime:6e4,retry:!1,refetchInterval:e=>Bp(e.state.data)?Up:Fp,refetchIntervalInBackground:!0})}function Zp(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function $m(e,t,n=1){return Zp(e,t,n)==="enabled"}function Um(e){return Oo({queryKey:jo.providers,queryFn:()=>ce({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:jp})}var Gp=(e=>(e[e.MESSAGE_INPUT=1]="MESSAGE_INPUT",e[e.INLINE_EDIT=2]="INLINE_EDIT",e))(Gp||{});const Hp=/Mac|iPhone|iPad/,Vp={darwin:{alt:"Option",meta:"Command",ctrl:"Control"},win32:{alt:"Command",meta:"Win",ctrl:"Control"},other:{alt:"Command",meta:"Super",ctrl:"Control"}},zp=()=>{const e=typeof navigator>"u"?"":navigator.platform??"";return Hp.test(e)?"darwin":/Win/i.test(e)?"win32":"other"},Kp=(e,t,n)=>`${e==="alt"?n==="darwin"?"Alt":"Meta":e==="meta"?"Meta":"Control"}${t==="left"?"Left":"Right"}`,$o=e=>{if(typeof e!="string")return null;const t=/^(alt|meta|ctrl)-(left|right)-hold$/.exec(e.trim().toLowerCase());if(!t)return null;const n=zp(),[,s,r]=t;return{code:Kp(s,r,n),label:`${r==="left"?"Left":"Right"}-${Vp[n][s]}`}},Wp=()=>$o("alt-right-hold");let Uo=null;const hi=()=>Uo??Wp();let xt=null;const Yp=async()=>xt||(xt=(async()=>{try{const t=(await ce({op:"settings.list"})).settings.find(n=>n.key==="keymap.push_to_talk");Uo=$o(t?.value)}catch{}finally{xt=null}})(),xt),Rs=new Set,Fm=(e,t)=>{t?Rs.add(e):Rs.delete(e)},Bm=()=>Rs.size>0;class Qp{handlers=new Map;isListening=!1;engaged=null;register(t,n,s,r){this.handlers.set(t,{id:t,priority:n,handler:s,isActive:r}),Yp(),this.setupListener()}unregister(t){if(this.handlers.delete(t),this.engaged?.id===t){const{handler:n}=this.engaged;this.engaged=null;try{n.stop("abort")}catch{}}this.handlers.size===0&&this.removeListener()}handleSpeechToText=()=>{const t=this.highestActive();t&&t.handler.start()};spaceFocusGuardRefuses(){const t=document.activeElement;return!!(t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable))}highestActive(){return Array.from(this.handlers.values()).filter(n=>n.isActive()).sort((n,s)=>s.priority-n.priority)[0]??null}engage(t){const n=this.highestActive();n&&(t.preventDefault(),this.engaged={id:n.id,handler:n.handler},n.handler.start())}releaseHold(t){const n=this.engaged;n&&(this.engaged=null,n.handler.stop(t))}handleKeyDown=t=>{if(t.isComposing)return;const n=hi(),s=t.code===n.code,r=t.code==="Space";if(!(t.repeat&&(s||r))){if(s){this.engaged||this.engage(t);return}if(this.engaged){t.key==="Escape"&&t.preventDefault(),this.releaseHold("abort");return}if(r){if(this.spaceFocusGuardRefuses())return;this.engage(t)}}};handleKeyUp=t=>{if(!this.engaged)return;const n=hi();(t.code===n.code||t.code==="Space")&&(t.preventDefault(),this.releaseHold("release"))};handleWindowBlur=()=>{this.releaseHold("release")};setupListener(){this.isListening||(window.electron.ipcRenderer.on("start-speech-to-text",this.handleSpeechToText),window.addEventListener("keydown",this.handleKeyDown,!0),window.addEventListener("keyup",this.handleKeyUp),window.addEventListener("blur",this.handleWindowBlur),this.isListening=!0)}removeListener(){if(this.isListening&&(window.electron.ipcRenderer.removeListener("start-speech-to-text",this.handleSpeechToText),window.removeEventListener("keydown",this.handleKeyDown,!0),window.removeEventListener("keyup",this.handleKeyUp),window.removeEventListener("blur",this.handleWindowBlur),this.isListening=!1),this.engaged){const{handler:t}=this.engaged;this.engaged=null;try{t.stop("abort")}catch{}}}}const mi=new Qp,Zm=(e,t,n,s)=>{const r=T.useRef(n),i=T.useRef(s);r.current=n,i.current=s;const o=T.useRef({start:()=>r.current.start(),stop:l=>r.current.stop(l)}),c=T.useCallback(()=>i.current(),[]);T.useEffect(()=>(mi.register(e,t,o.current,c),()=>{mi.unregister(e)}),[e,t,c])},Xp=12,Jp="inline-flex h-5 min-w-5 items-center justify-center rounded-xs px-1 font-mono text-ink-dim text-mono-sm",qp="inline-flex items-center gap-0",eh={"⌘":qn,cmd:qn,command:qn,enter:di,"↵":di},Gm=({shortcut:e,joined:t=!1})=>{const n=e.split("+").map(s=>s.trim());return De.jsx("span",{className:qp,children:n.map((s,r)=>{const i=eh[s.toLowerCase()];return De.jsxs(T.Fragment,{children:[r>0&&!t&&De.jsx("span",{"aria-hidden":"true",className:"text-mono-sm text-ink-dim",children:"+"}),De.jsx("kbd",{className:Jp,children:i?De.jsxs(De.Fragment,{children:[De.jsx(i,{size:Xp,"aria-hidden":"true"}),De.jsx("span",{className:"sr-only",children:s})]}):s})]},`${s}-${r}`)})})};function Hm(e){const t=e.trim();if(t.startsWith("="))return null;const n=t.toLowerCase();return n==="pause"||n==="resume"||n==="status"?n:null}function Vm(e){const t=e.trim();return t.startsWith("=")?t.slice(1).trimStart():t}function zm(e,t){return e==="pause"?{text:"Aida is paused. She will not check in until you resume her.",kind:"success"}:e==="resume"?{text:"Aida is resumed. She will check in on her usual schedule.",kind:"success"}:{kind:"info",text:t.paused?"Aida is paused.":"Aida is active."}}function Km(e){return In(e,"Aida's controls could not reach the backend.")}const Wm="The chief of staff is switched off on this install.",Ym="primary+alt+space",th=/^f([1-9]|1[0-9]|2[0-4])$/;function nh(e){return th.test(e)}function Fo(e,t){const n=sh(e,t);return t==="mac"?n.join(""):n.join("+")}function sh(e,t){const s=t==="mac"?{primary:"⌘",meta:"⌘",ctrl:"⌃",alt:"⌥",shift:"⇧"}:{primary:"Ctrl",meta:t==="win"?"Win":"Super",ctrl:"Ctrl",alt:"Alt",shift:"Shift"},r={space:"Space",backspace:"Backspace",delete:"Delete",insert:"Insert",home:"Home",end:"End",pageup:"PageUp",pagedown:"PageDown",up:"Up",down:"Down",left:"Left",right:"Right"};return e.split("+").map(i=>i.trim().toLowerCase()).filter(i=>i.length>0).map(i=>i in s?s[i]:i in r?r[i]:nh(i)||i.length===1?i.toUpperCase():i)}const Qm="Error accessing microphone. Please ensure microphone permissions are granted.",Xm="Dictation is not available on this device.",Jm={seatLabel:"To: the chief of staff",placeholder:"Message your chief of staff",send:"Send",sent:"Sent",retry:"Retry",hint:"Enter sends, Shift+Enter adds a line, Esc hides",recording:"Recording. Press the stop button when you're done.",transcribing:"Transcribing.",dictationStart:"Dictate a message",dictationStop:"Stop dictation",seatMissing:"This build doesn't have a chief-of-staff seat.",seatOpenFailed:"Couldn't open the chief-of-staff conversation.",seatUnreachable:"Couldn't reach the chief of staff.",keepText:"Your message is still here.",postAdmission:"That didn't reach the chief of staff — check the conversation."},qm="If the chord does nothing, another app or the system owns it — choose another.",eg="Works even when the app isn't focused.",tg="A global shortcut needs a modifier — it would otherwise fire while you type.";function ng(e){const t=n=>Fo(n,e);return`Try ${t("primary+shift+space")}, ${t("primary+alt+shift+space")} or ${t("primary+f8")} if that one is taken.`}function sg(e,t){const n=r=>Fo(r,t);switch(e.split("+").map(r=>r.trim().toLowerCase()).filter(Boolean).sort().join("+")){case"alt+primary+space":return rh(t,"Fantastical and Things Quick Entry use Control+Option+Space; both let you rebind it.","Some capture apps reserve their own chord in this family; the settings inside them can rebind it.");case"primary+shift+space":return`Some editors use ${n("primary+shift+space")} for parameter hints, and word processors for a non-breaking space.`;default:return null}}function rh(e,t,n){return e==="mac"?t:n}function rg(e,t){switch(e){case"registered":return`Registered ${t}`;case"taken":return`Couldn't register ${t} — another app may already use it. Choose another shortcut.`;case"invalid":return"This key can't be used as a global shortcut on this system.";case"unavailable":return"Global shortcuts aren't supported on this system."}}function ig(){try{return window.api?.windowChrome?.facts?.().platform??"linux"}catch{return"linux"}}export{tp as $,Wm as A,lh as B,jp as C,X as D,pc as E,hc as F,mc as G,gc as H,Zp as I,yc as J,Gm as K,Gs as L,Qm as M,Vs as N,So as O,fr as P,Zf as Q,zf as R,ge as S,xm as T,Yf as U,ep as V,Xf as W,Jf as X,ci as Y,np as Z,li as _,Vf as a,ul as a$,qf as a0,vr as a1,dh as a2,uh as a3,Ce as a4,jo as a5,sg as a6,tg as a7,nh as a8,Fo as a9,Hs as aA,ko as aB,Ss as aC,Qf as aD,yh as aE,ll as aF,dl as aG,es as aH,Im as aI,Rm as aJ,fh as aK,tr as aL,qc as aM,ph as aN,sc as aO,qs as aP,nu as aQ,Qh as aR,Xh as aS,Yh as aT,io as aU,Jd as aV,Ns as aW,_e as aX,Rc as aY,ef as aZ,ji as a_,eg as aa,rg as ab,qm as ac,ng as ad,Mm as ae,Ll as af,hf as ag,at as ah,gh as ai,oc as aj,em as ak,Of as al,bm as am,mm as an,Ff as ao,jf as ap,gm as aq,_s as ar,Df as as,_m as at,vm as au,To as av,Eo as aw,fn as ax,hm as ay,ws as az,Oo as b,Bh as b$,Ps as b0,Ri as b1,ym as b2,Vh as b3,ol as b4,Sh as b5,kh as b6,Zh as b7,Gh as b8,ro as b9,Dh as bA,Th as bB,Eh as bC,bl as bD,Ih as bE,xh as bF,Oh as bG,Ch as bH,$h as bI,Jh as bJ,qh as bK,mh as bL,Em as bM,hi as bN,tc as bO,nc as bP,bf as bQ,_f as bR,ei as bS,pf as bT,vo as bU,ti as bV,ch as bW,Be as bX,Rt as bY,vh as bZ,Am as b_,Hn as ba,Hh as bb,Ls as bc,Ds as bd,as as be,Mp as bf,Nm as bg,Dp as bh,Lm as bi,Dm as bj,vt as bk,wh as bl,bh as bm,_h as bn,hh as bo,Mh as bp,jh as bq,Lh as br,Ph as bs,$i as bt,Ah as bu,Hi as bv,nr as bw,$l as bx,Rh as by,Nh as bz,Ze as c,Wh as c0,Kh as c1,Ai as c2,cm as c3,om as c4,am as c5,Hm as c6,zm as c7,Km as c8,Vm as c9,Uh as ca,Fh as cb,On as cc,sf as cd,No as ce,Om as cf,Zs as cg,rm as ch,tm as ci,zh as cj,go as ck,cf as cl,An as cm,um as cn,fm as co,nm as cp,sm as cq,fo as cr,mo as cs,Ju as ct,qr as cu,im as cv,Bm as cw,dm as cx,wm as cy,$m as d,ce as e,Um as f,Pm as g,Xm as h,Cm as i,Ym as j,Jm as k,pm as l,rf as m,Fm as n,Zm as o,lm as p,Gp as q,ig as r,nf as s,Tm as t,jm as u,sh as v,km as w,Sm as x,Lp as y,In as z};
|
|
42
|
+
${t}`)}throw new Error(`Failed to load configuration: ${e instanceof Error?e.message:String(e)}`)}}const es=Np();let No=null;function Om(e){No=e}const Pm={get baseUrl(){return No??es.VITE_LOCAL_OPERATOR_API_URL},radientBaseUrl:es.VITE_RADIENT_SERVER_BASE_URL,radientClientId:es.VITE_RADIENT_CLIENT_ID};function Dm(e){return e!=="detached"&&e!=="wedged"}function Mo(e){return e!=="governed-elsewhere"&&e!=="pre-handshake"}function Lm(e){if(!e)return{title:"Not connected to a Local Operator server.",detail:null,retry:!0};const t=e.addressSubstitution??null;if(t&&e.state!=="detached"&&e.state!=="wedged")return t.kind==="substituted"?{title:`Serving on ${t.serving}, not the address this app is configured for.`,detail:t.holder?`${t.holder}. The app uses ${t.serving} while that holds.${t.reclaim?` ${t.reclaim}`:""} It is back on ${t.configured} on its next launch or recovery.`:`The daemon this app is using was already running, so it did not start one. It looks for ${t.configured} again on its next launch or recovery.`,retry:!0}:{title:`Back on ${t.configured}, the address this app is configured for.`,detail:`It served on ${t.serving} while the configured address was held; it is on the address it was told to use again.`,retry:!1,dismiss:!0};const n=e.detail?.trim()?e.detail.trim():null,s=Mo(e.pairing?.cause??null);switch(e.state){case"wedged":return{title:"A Local Operator server is running on this machine and this app is not attached to it.",detail:n,retry:s};case"detached":return e.reconnecting?{title:s?"Not connected to a Local Operator server. If one is still running, the app reconnects to it on its own.":"Not connected to a Local Operator server.",detail:n,retry:s}:{title:s?"The Local Operator server stopped. The app keeps looking for one and attaches to it when it appears.":"Not connected to a Local Operator server. The app keeps looking for one.",detail:n,retry:s};default:return null}}function Mp(e){if(ll(e))return"deadline";const t=e instanceof X?e.status:null;return t===null||t===503?"unreachable":t===401||t===403?"unauthorized":t===404?"outdated":"unknown"}const jo={unreachable:"",deadline:"",unauthorized:"",outdated:"Update the server and try again.",unknown:""},Is={unreachable:"The Local Operator server is not answering.",deadline:"The Local Operator server did not answer in time.",unauthorized:"This app cannot authenticate to the running Local Operator server.",outdated:"The Local Operator server is older than this app expects.",unknown:""};function jp(e,t){const n=Mp(t);return[e,Is[n],jo[n]].filter(Boolean).join(" ")}const Cs={successor:"The Local Operator server was replaced while this app was running. Pairing with the new one.","governed-elsewhere":"The Local Operator server on this machine is already managed by another program, so this app cannot use its settings, provider sign-in, slash commands or MCP management.","pre-handshake":"The Local Operator server on this machine is older than the pairing handshake this app uses, so this app cannot drive its controls. The server itself, and anything you run against it from the terminal, are unaffected.","credential-refused":"This app's credential for the running Local Operator server was refused, so provider sign-in, settings, slash commands and MCP management are unavailable.",unpaired:"This app is not paired with the running Local Operator server, so provider sign-in, settings, slash commands and MCP management are unavailable."},$p={successor:"This conversation cannot be read here until the app finishes pairing with the replacement server. Your chats are still on that server.","governed-elsewhere":"This conversation cannot be read here: the server's desktop controls belong to another program. Your chats are still on that server.","pre-handshake":"This conversation cannot be read here: that server is older than the pairing handshake this app uses. Your chats are still on that server.","credential-refused":"This conversation cannot be read here: the server refused this app's credential. Your chats are still on that server.",unpaired:"This conversation cannot be read here: the app is not paired with the running server. Your chats are still on that server."};function Nm(e,t){return e!=="unpaired"?null:$p[t??"unpaired"]}function Mm(e,t){return e!=="unpaired"?null:Cs[t??"unpaired"]}function jm(e){const{kind:t,unpaired:n,answered:s,cause:r=null,servedByThisApp:i=!1}=e;return r==="pre-handshake"?i:r!==null||n?!1:s?i:t==="outdated"}function $m(e){const{kind:t,unpaired:n,missing:s,answered:r,cause:i=null}=e;if(i!==null)return Cs[i];if(!r){if(t==="unreachable")return`${Is.unreachable} Provider sign-in, settings, slash commands and MCP management need it running.`;if(t==="unauthorized")return"This app cannot authenticate to the running Local Operator server, so provider sign-in, settings, slash commands and MCP management are unavailable.";if(t==="deadline")return`${Is.deadline} Provider sign-in, settings, slash commands and MCP management need it answering.`;if(t==="outdated")return`The Local Operator server is older than this app expects, so provider sign-in, settings, slash commands and MCP management are off. ${jo.outdated}`}return n?Cs.unpaired:r?`The Local Operator server is missing ${s.join(", ")} support. Update it to enable those surfaces.`:"Provider sign-in, settings, slash commands and MCP management are unavailable because the Local Operator server did not answer as expected."}const Up=["auth","settings","commands","catalogues","lifecycle","mcp","radient"];function Um(e,t=null){return t!==null||!e?!0:Up.filter(s=>(e.features?.[s]??0)<1).length>0||e.desktop_available!==!0}function Fp(e,t){return t instanceof X&&t.status===null?!1:e<1}const Bp={successor:"Your settings could not be loaded: the app is pairing with the server that replaced the one it was using.","governed-elsewhere":"Your settings could not be loaded: another program is managing this machine's Local Operator server, so this page cannot read or change them here.","pre-handshake":"Your settings could not be loaded: the server this app is talking to is older than the pairing handshake, so this page cannot read them from it.","credential-refused":"Your settings could not be loaded: the server refused this app's credential, so this page cannot read them from it.",unpaired:"Your settings could not be loaded: this app is not paired with the running server, so this page cannot read them from it."};function Fm(e,t,n){return e===null?{sentence:jp(t,n),remedy:!0}:{sentence:Bp[e],remedy:Mo(e)}}const $o={capabilities:["desktop","capabilities"],providers:["desktop","auth","providers"],commands:["desktop","commands"],accounts:["desktop","auth","accounts"],catalogue:["desktop","models"],credentials:e=>["desktop","credentials",e]},Zp=3e4,Gp=15e3;function Hp(e){return e?.desktop_available===!0}function Bm(){return Po({queryKey:$o.capabilities,queryFn:async()=>{try{return await ce({op:"capabilities"})}catch(e){throw e instanceof Error?e:new Error(String(e))}},staleTime:6e4,retry:!1,refetchInterval:e=>Hp(e.state.data)?Zp:Gp,refetchIntervalInBackground:!0})}function zp(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function Zm(e,t,n=1){return zp(e,t,n)==="enabled"}function Gm(e){return Po({queryKey:$o.providers,queryFn:()=>ce({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:Fp})}var Vp=(e=>(e[e.MESSAGE_INPUT=1]="MESSAGE_INPUT",e[e.INLINE_EDIT=2]="INLINE_EDIT",e))(Vp||{});const Kp=/Mac|iPhone|iPad/,Wp={darwin:{alt:"Option",meta:"Command",ctrl:"Control"},win32:{alt:"Command",meta:"Win",ctrl:"Control"},other:{alt:"Command",meta:"Super",ctrl:"Control"}},Yp=()=>{const e=typeof navigator>"u"?"":navigator.platform??"";return Kp.test(e)?"darwin":/Win/i.test(e)?"win32":"other"},Qp=(e,t,n)=>`${e==="alt"?n==="darwin"?"Alt":"Meta":e==="meta"?"Meta":"Control"}${t==="left"?"Left":"Right"}`,Uo=e=>{if(typeof e!="string")return null;const t=/^(alt|meta|ctrl)-(left|right)-hold$/.exec(e.trim().toLowerCase());if(!t)return null;const n=Yp(),[,s,r]=t;return{code:Qp(s,r,n),label:`${r==="left"?"Left":"Right"}-${Wp[n][s]}`}},Xp=()=>Uo("alt-right-hold");let Fo=null;const hi=()=>Fo??Xp();let xt=null;const Jp=async()=>xt||(xt=(async()=>{try{const t=(await ce({op:"settings.list"})).settings.find(n=>n.key==="keymap.push_to_talk");Fo=Uo(t?.value)}catch{}finally{xt=null}})(),xt),Rs=new Set,Hm=(e,t)=>{t?Rs.add(e):Rs.delete(e)},zm=()=>Rs.size>0;class qp{handlers=new Map;isListening=!1;engaged=null;register(t,n,s,r){this.handlers.set(t,{id:t,priority:n,handler:s,isActive:r}),Jp(),this.setupListener()}unregister(t){if(this.handlers.delete(t),this.engaged?.id===t){const{handler:n}=this.engaged;this.engaged=null;try{n.stop("abort")}catch{}}this.handlers.size===0&&this.removeListener()}handleSpeechToText=()=>{const t=this.highestActive();t&&t.handler.start()};spaceFocusGuardRefuses(){const t=document.activeElement;return!!(t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable))}highestActive(){return Array.from(this.handlers.values()).filter(n=>n.isActive()).sort((n,s)=>s.priority-n.priority)[0]??null}engage(t){const n=this.highestActive();n&&(t.preventDefault(),this.engaged={id:n.id,handler:n.handler},n.handler.start())}releaseHold(t){const n=this.engaged;n&&(this.engaged=null,n.handler.stop(t))}handleKeyDown=t=>{if(t.isComposing)return;const n=hi(),s=t.code===n.code,r=t.code==="Space";if(!(t.repeat&&(s||r))){if(s){this.engaged||this.engage(t);return}if(this.engaged){t.key==="Escape"&&t.preventDefault(),this.releaseHold("abort");return}if(r){if(this.spaceFocusGuardRefuses())return;this.engage(t)}}};handleKeyUp=t=>{if(!this.engaged)return;const n=hi();(t.code===n.code||t.code==="Space")&&(t.preventDefault(),this.releaseHold("release"))};handleWindowBlur=()=>{this.releaseHold("release")};setupListener(){this.isListening||(window.electron.ipcRenderer.on("start-speech-to-text",this.handleSpeechToText),window.addEventListener("keydown",this.handleKeyDown,!0),window.addEventListener("keyup",this.handleKeyUp),window.addEventListener("blur",this.handleWindowBlur),this.isListening=!0)}removeListener(){if(this.isListening&&(window.electron.ipcRenderer.removeListener("start-speech-to-text",this.handleSpeechToText),window.removeEventListener("keydown",this.handleKeyDown,!0),window.removeEventListener("keyup",this.handleKeyUp),window.removeEventListener("blur",this.handleWindowBlur),this.isListening=!1),this.engaged){const{handler:t}=this.engaged;this.engaged=null;try{t.stop("abort")}catch{}}}}const mi=new qp,Vm=(e,t,n,s)=>{const r=T.useRef(n),i=T.useRef(s);r.current=n,i.current=s;const o=T.useRef({start:()=>r.current.start(),stop:l=>r.current.stop(l)}),c=T.useCallback(()=>i.current(),[]);T.useEffect(()=>(mi.register(e,t,o.current,c),()=>{mi.unregister(e)}),[e,t,c])},eh=12,th="inline-flex h-5 min-w-5 items-center justify-center rounded-xs px-1 font-mono text-ink-dim text-mono-sm",nh="inline-flex items-center gap-0",sh={"⌘":qn,cmd:qn,command:qn,enter:di,"↵":di},Km=({shortcut:e,joined:t=!1})=>{const n=e.split("+").map(s=>s.trim());return De.jsx("span",{className:nh,children:n.map((s,r)=>{const i=sh[s.toLowerCase()];return De.jsxs(T.Fragment,{children:[r>0&&!t&&De.jsx("span",{"aria-hidden":"true",className:"text-mono-sm text-ink-dim",children:"+"}),De.jsx("kbd",{className:th,children:i?De.jsxs(De.Fragment,{children:[De.jsx(i,{size:eh,"aria-hidden":"true"}),De.jsx("span",{className:"sr-only",children:s})]}):s})]},`${s}-${r}`)})})},Wm="primary+alt+shift+space",rh=/^f([1-9]|1[0-9]|2[0-4])$/;function ih(e){return rh.test(e)}function Bo(e,t){const n=oh(e,t);return t==="mac"?n.join(""):n.join("+")}function oh(e,t){const s=t==="mac"?{primary:"⌘",meta:"⌘",ctrl:"⌃",alt:"⌥",shift:"⇧"}:{primary:"Ctrl",meta:t==="win"?"Win":"Super",ctrl:"Ctrl",alt:"Alt",shift:"Shift"},r={space:"Space",backspace:"Backspace",delete:"Delete",insert:"Insert",home:"Home",end:"End",pageup:"PageUp",pagedown:"PageDown",up:"Up",down:"Down",left:"Left",right:"Right"};return e.split("+").map(i=>i.trim().toLowerCase()).filter(i=>i.length>0).map(i=>i in s?s[i]:i in r?r[i]:ih(i)||i.length===1?i.toUpperCase():i)}const Ym="Error accessing microphone. Please ensure microphone permissions are granted.",Qm="Dictation is not available on this device.",Xm={seatLabel:"To: the chief of staff",placeholder:"Message your chief of staff",send:"Send",sent:"Sent",retry:"Retry",hint:"Enter sends, Shift+Enter adds a line, Esc hides",recording:"Recording. Press the stop button when you're done.",transcribing:"Transcribing.",dictationStart:"Dictate a message",dictationStop:"Stop dictation",seatMissing:"This build doesn't have a chief-of-staff seat.",seatOpenFailed:"Couldn't open the chief-of-staff conversation.",seatUnreachable:"Couldn't reach the chief of staff.",keepText:"Your message is still here.",postAdmission:"That didn't reach the chief of staff — check the conversation."},Jm="If the chord does nothing, another app or the system owns it — choose another.",qm="Works even when the app isn't focused.",eg="A global shortcut needs a modifier — it would otherwise fire while you type.";function tg(e){const t=n=>Bo(n,e);return`Try ${t("primary+shift+space")} or ${t("primary+f8")} if that one is taken.`}function ng(e,t){const n=r=>Bo(r,t);switch(e.split("+").map(r=>r.trim().toLowerCase()).filter(Boolean).sort().join("+")){case"alt+primary+space":return ah(t,"Fantastical and Things Quick Entry use Control+Option+Space; both let you rebind it.","Some capture apps reserve their own chord in this family; the settings inside them can rebind it.");case"primary+shift+space":return`Some editors use ${n("primary+shift+space")} for parameter hints, and word processors for a non-breaking space.`;default:return null}}function ah(e,t,n){return e==="mac"?t:n}function sg(e,t){switch(e){case"registered":return`Registered ${t}`;case"taken":return`Couldn't register ${t} — another app may already use it. Choose another shortcut.`;case"invalid":return"This key can't be used as a global shortcut on this system.";case"unavailable":return"Global shortcuts aren't supported on this system."}}function rg(){try{return window.api?.windowChrome?.facts?.().platform??"linux"}catch{return"linux"}}function ig(e){const t=e.trim();if(t.startsWith("="))return null;const n=t.toLowerCase();return n==="pause"||n==="resume"||n==="status"?n:null}function og(e){const t=e.trim();return t.startsWith("=")?t.slice(1).trimStart():t}function ag(e,t){return e==="pause"?{text:"Aida is paused. She will not check in until you resume her.",kind:"success"}:e==="resume"?{text:"Aida is resumed. She will check in on her usual schedule.",kind:"success"}:{kind:"info",text:t.paused?"Aida is paused.":"Aida is active."}}function cg(e){return In(e,"Aida's controls could not reach the backend.")}const lg="The chief of staff is switched off on this install.";export{rp as $,lg as A,fh as B,Fp as C,X as D,yc as E,vc as F,_c as G,bc as H,zp as I,wc as J,Km as K,Gs as L,Ym as M,zs as N,ko as O,fr as P,zf as Q,Yf as R,ge as S,Am as T,Jf as U,sp as V,ep as W,tp as X,ci as Y,ip as Z,li as _,Wf as a,Vh as a$,np as a0,vr as a1,ph as a2,hh as a3,Ce as a4,jl as a5,yf as a6,Fm as a7,Ke as a8,_h as a9,Dm as aA,mh as aB,tr as aC,nl as aD,gh as aE,ac as aF,$o as aG,qs as aH,iu as aI,em as aJ,tm as aK,qh as aL,oo as aM,tu as aN,Ns as aO,_e as aP,Dc as aQ,sf as aR,$i as aS,hl as aT,Ps as aU,Ri as aV,wm as aW,Yh as aX,ll as aY,xh as aZ,Ih as a_,dc as aa,rm as ab,Lf as ac,Tm as ad,_m as ae,Gf as af,Ff as ag,bm as ah,_s as ai,Mf as aj,km as ak,Sm as al,Eo as am,xo as an,fn as ao,vm as ap,ws as aq,Hs as ar,To as as,Ss as at,qf as au,wh as av,fl as aw,pl as ax,es as ay,Om as az,Po as b,uh as b$,Kh as b0,io as b1,Hn as b2,Wh as b3,Ls as b4,Ds as b5,as as b6,Up as b7,Um as b8,Mp as b9,Jm as bA,tg as bB,Bl as bC,Dh as bD,Uh as bE,jh as bF,Ch as bG,Rh as bH,kl as bI,Oh as bJ,Ah as bK,Nh as bL,Ph as bM,Zh as bN,nm as bO,sm as bP,vh as bQ,Rm as bR,hi as bS,nc as bT,sc as bU,kf as bV,Sf as bW,ei as bX,gf as bY,_o as bZ,ti as b_,$m as ba,jm as bb,vt as bc,Eh as bd,bh as be,Th as bf,kh as bg,yh as bh,Fh as bi,Bh as bj,$h as bk,Mh as bl,Ui as bm,Lh as bn,rc as bo,ic as bp,oc as bq,zi as br,nr as bs,Sh as bt,ng as bu,eg as bv,ih as bw,Bo as bx,qm as by,sg as bz,Ze as c,Be as c0,Rt as c1,Lm as c2,zh as c3,Jh as c4,Xh as c5,Ai as c6,fm as c7,dm as c8,um as c9,zm as cA,hm as cB,Em as cC,ig as ca,ag as cb,cg as cc,og as cd,Gh as ce,Hh as cf,On as cg,af as ch,Mo as ci,Nm as cj,Zs as ck,cm as cl,im as cm,Qh as cn,yo as co,uf as cp,An as cq,mm as cr,gm as cs,om as ct,am as cu,po as cv,go as cw,tf as cx,qr as cy,lm as cz,Zm as d,ce as e,Gm as f,Mm as g,Qm as h,Pm as i,Wm as j,Xm as k,ym as l,cf as m,Hm as n,Vm as o,pm as p,Vp as q,rg as r,of as s,Cm as t,Bm as u,oh as v,Im as w,xm as x,jp as y,In as z};
|